• 0

[PHP] redirect back to page after logging in


Question

Hey,

does anyone know where I can get a script that will redirect my users back to the page they were viewing after logging in?

if i have user page2.php and they aren't logged in, they will be redirected to the index.php where the login page is. after login in how can they be taken back to page2.php where the content is viewable only if you are registered and logged in...

16 answers to this question

Recommended Posts

  • 0

When they first visit the login page, look at the $_SERVER['HTTP_REFERER'] variable and either save the referring address in the session, or save a default address in the session if there was no referrer page. After they log in, redirect them to the address you stored in the session.

  • 0

Since your using php, try:

header('Location : http://www.website.com/page2.php');

The problem with that is it is not really dynamic enough, he wants them to return to whatever page they were on before hitting log in, page2.php was simply an example he used. You could however use that along with the first responses solution so you are able to grab the page they came from, then redirect them back there after login using the header function. But, I am not PHP expert (I have experience in it, but far less than many others)....so there may be a better way to handle it.

  • 0

What he could do, my original thought, but wanted to provide him with what he requested, is use a cookie or session, very easy to code.

And just enable parts of the page if the login returns successful.

  • 0

I have it

if (!isset($_SESSION['user_id']))
{
header("Location: account.php");
}

which redirects the user back to account.php after login in.

but if the user was on a different page i would like them to be taken back to that same page dynamically after logging in.

Its cause after my session expires the user will be directed to the login page but then the login page directs them to the default page. I wanted them to be taken back to the page they were on after login in...

  • 0

I have it

if (!isset($_SESSION['user_id']))
{
header("Location: account.php");
}

which redirects the user back to account.php after login in.

but if the user was on a different page i would like them to be taken back to that same page dynamically after logging in.

Its cause after my session expires the user will be directed to the login page but then the login page directs them to the default page. I wanted them to be taken back to the page they were on after login in...

take a look at this page: http://ca.php.net/reserved.variables.server & http://www.tizag.com/phpT/phpsessions.php

My best bet would be to store each page as a session, excluding the login page. Once the user has finished the login section, read the session and add it to

header("Location: ". $_SESSION['page']);

  • 0

Simply use:

<?php
$ref = $_SERVER['HTTP_REFERER'];
header( 'refresh: 0; url='.$ref);
?>

You can change the refresh limit depending on if you choose to display a message.

(I use this myself and it works a treat, any problems don't hesitate to message me :))

  • 0

Simply use:

<?php
$ref = $_SERVER['HTTP_REFERER'];
header( 'refresh: 0; url='.$ref);
?>

You can change the refresh limit depending on if you choose to display a message.

(I use this myself and it works a treat, any problems don't hesitate to message me :))

Hmmmm, well after looking around the PHP.net sitr I put this together

function page_protect() {
session_start();

//check for cookies
if(isset($_COOKIE['user_id']) && isset($_COOKIE['username'])){
 	$_SESSION['user_id'] = $_COOKIE['user_id'];
 	$_SESSION['username'] = $_COOKIE['username'];
 }

if (!isset($_SESSION['user_id']))
{
$_SESSION['login_retval'] = $_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'] ; // <- This is what I updated it with, I haven't tried it yet, but I got a feelings its wrong lol
header("Location: account.php");
}

  • 0

Hmmmm, well after looking around the PHP.net sitr I put this together

function page_protect() {
session_start();

//check for cookies
if(isset($_COOKIE['user_id']) && isset($_COOKIE['username'])){
 	$_SESSION['user_id'] = $_COOKIE['user_id'];
 	$_SESSION['username'] = $_COOKIE['username'];
 }

if (!isset($_SESSION['user_id']))
{
$_SESSION['login_retval'] = $_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'] ; // <- This is what I updated it with, I haven't tried it yet, but I got a feelings its wrong lol
header("Location: account.php");
}

Didn't read the part about it redirecting to index.php for login, I'd personally code this differently. If you don't find a solid solution to your problem when I've had some sleep I'll drop you a line :)

  • 0

Didn't read the part about it redirecting to index.php for login, I'd personally code this differently. If you don't find a solid solution to your problem when I've had some sleep I'll drop you a line :)

ya, actually i'm pretty drain too. I'm going to bed now... been tinkering with this and and upload image script i'm getting headaches over.

you can check that out too if you would like to give some feed back ;)

https://www.neowin.net/forum/topic/897196-phpmysql-compare-session-info-to-db-in-a-query/page__gopid__592575702entry592575702

but yes, I think I'm not thinking about this correctly and might need some help getting the referral thing to work.

My thing was to have this scenario

index.php has login details, that when logged in takes you to account.php

say you access www.mysite.com/upload.php without being logged in, my page_protect() will take you to the index.php to login. But onces logged in instead of being redirected to account.php to be redirected to upload.php...

  • 0

I'm no expert on the subject, but the suggestions in this thread are a great way to introduce XSS and injection vulnerabilities. All I'd have to do is set a cookie with a valid userid and username and get to someone else's account page.

well the cookies are sha1 with a salt. you would need to have to guess the entire string for it to match, I have a check on my pages also that the page cannot be accessed unless

user_id matches a md5(user_id) and the password in the cookie doesn't match the sha1(password) from the database.

Its probably still not fully protected, but since I'm learning this is how i figured...

  • 0

One solution i have seen is to append the previous url to the query string, ie like

if (!isset($_SESSION['user_id']))
{
header("Location: index.php?nav=".$whateverpageyouwerebrowsingbefore);
}

// $whateverpageyouwerebrowsingbefore would be something like /account/, /main/ or whatever

It's not much different than storing in a cookie the previous page, but it still need to be sanitized/validated against a list of permitted/allowed urls (or uri segments) you can include an associative array in all your page which maps your "route" to the correct redirect page. As for storing session information in a cookie : bad idea imo you should always store unimportant information in a cookie, even if it's encrypted, session are much more secure in this regard (even though you have to protect your app from session fixation vulnerabilities, but any serious dev will always do that unless they don't use sessions).

  • 0

One solution i have seen is to append the previous url to the query string, ie like

if (!isset($_SESSION['user_id']))
{
header("Location: index.php?nav=".$whateverpageyouwerebrowsingbefore);
}

// $whateverpageyouwerebrowsingbefore would be something like /account/, /main/ or whatever

It's not much different than storing in a cookie the previous page, but it still need to be sanitized/validated against a list of permitted/allowed urls (or uri segments) you can include an associative array in all your page which maps your "route" to the correct redirect page. As for storing session information in a cookie : bad idea imo you should always store unimportant information in a cookie, even if it's encrypted, session are much more secure in this regard (even though you have to protect your app from session fixation vulnerabilities, but any serious dev will always do that unless they don't use sessions).

hmmm, i see

well i'm currently trying to set up a sessions table in my database to store the user sessions. try to be a little more secure that way, when I finish my site i'll look into extreme security measures and how to implements them. but for now i get a headeache thinking that far ahead or how more complicated things will be when i need to learn them.

  • 0

Securing a webapp/website isn't that difficult, you have ready to use libraries that can take care of it (somehow it's not automatic though, and for learning purpose anything "automatic" is evil).

The 4 most important things to recall when making a webapp are : XSS, XSRF (or CSRF), Session Fixations and SQL injection, xss is a matter of removing ability to run (mostly) any client code from your app :

Say you have a comment section somewhere in your code and it's to prevent people from injecting JS so that if someone hits the page they won't have spy scripts gathering your users session (for example).

CSRF/XSRF (Cross site request forgery) is to protect your admin functions, they should be built so that accessing them requires double authentication or in a separate process altogether, it's the trickier thing to protect.

Session fixations, well it's to prevent people to catch your session for one (through XSS usually) and access your website without even have to log in, there are a couple of ways to deal with that (special handshake at login, then stored in the DB ; the handshake is compiled and compared to the value stored in the DB each time a page is loaded, if the handshake is different, mostlikely to happen if someone got a session by vile means => logout/boot the user. Note that regarding session fixations the more restrictive you get the more likely you may kick legit users from accessing your applications. Things like transparent proxies, people behind nat etc etc... You will have to find the correct mix !. Also as you are using php, there is a server.ini settings that do not allow session information to be used as a query string (it disables the global variable $SSID if i recall)

And lastly Sql injection, (this is where validation comes in to play 99% of the time) attack vectors are most of the time forms/query strings/client cookies, validation should be done with anything that acts as an input, hopefully php has a bunch of tools that will help escape your sql commands.

But even if you master all of this and know how to protect your application, the number one flaw in your app will always be the dev, it's just a matter of "forgetting" to validate an input, or having a logic error in the code that will allow bad doers to f*ck around with your web app.

Edit: Fixed somethings that didn't make any sense, English is not my mother tongue.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Quantum Error Correction Validated in Nature: Microsoft and Quantinuum Log 800-Fold Improvement Two years after the original press-release announcement, independently peer-reviewed results published in Nature on June 10, 2026, have confirmed that Microsoft and Quantinuum achieved an 800-fold reduction in quantum error rates on real trapped-ion hardware — the largest gap between physical and logical error rates ever independently validated.    What Quantum Error Correction Actually Does — and Why Breaking Even Is Hard https://www.techtimes.com/articles/318329/20260613/quantum-error-correction-validated-nature-microsoft-quantinuum-log-800-fold-improvement.htm   Quantum Computing Wiring Bottleneck Cracked by HKU Silicon Carbide Chip at Qubit Temperature Engineers at the University of Hong Kong have built the first cryogenic control chip that operates at the same temperature as superconducting qubits — 10 millikelvin, or just one-hundredth of a degree above absolute zero — without generating the heat that has forced every competing approach to park its electronics hundreds of meters of cable away. https://www.techtimes.com/articles/318325/20260613/quantum-computing-wiring-bottleneck-cracked-hku-silicon-carbide-chip-qubit-temperature.htm  
    • RevPDF 4.5.0 by Razvan Serea RevPDF is a free, fully offline PDF editor for Windows, macOS, and Linux that lets you edit text and images directly inside PDF files — no internet connection, no account, and no cloud uploads required. Unlike bloated alternatives that demand subscriptions and constant connectivity, RevPDF fits in under 60MB on desktop while delivering a complete editing toolkit: annotate, redact, sign, compress, split, merge, convert, and reorganize pages, all processed locally on your device. Smart font matching ensures edited text blends seamlessly with the original, and multi-language support includes RTL scripts such as Arabic and Hebrew. Where most PDF editors force you to choose between features and simplicity, RevPDF manages both. You can build interactive forms from scratch with text fields, checkboxes, and dropdowns, permanently redact sensitive data before sharing, draw freehand on contracts and diagrams, and add custom watermarks — all without a single file leaving your machine. Edit Text and Images Directly Inside PDFs RevPDF supports true inline PDF editing — not just annotation layers on top of a document, but actual modification of existing text and images within the file. A smart font-matching engine identifies the font used in the original document and applies it automatically when you make edits, so changes blend naturally with the surrounding content. You can reposition elements, resize images, and update text across single pages or entire documents. RevPDF 4.5.0 release notes: This is one of the biggest updates to RevPDF yet. A lot of things people have been asking for are finally here. New Features Auto Redaction Permanently redact sensitive text and areas from your PDFs before sharing. Clean, irreversible, and fully offline. Comments, Links & Bookmarks Add comments for review, insert clickable links, and create bookmarks to jump around long documents without scrolling forever. Find & Replace Search across the whole document and replace text in one go. Long overdue. Split Pages Vertically or Horizontally Split any page down the middle, vertically or horizontally. Perfect for scanned books or double-page spreads. New Drawing Tools More tools for freehand drawing and markup, better for annotations, sketches, and detailed notes. Continuous Scrolling in Editor The editor now scrolls continuously through pages instead of jumping between them. Working through long documents is a lot smoother now. PDF Metadata Editor View and edit the metadata stored inside your PDFs, including title, author, subject, and keywords. Better Font Matching Text edits now blend in more naturally by doing a better job of matching the original font. Tabbed PDF Viewer Open multiple PDFs at once in tabs and switch between them without going back to the home screen. Add Links Insert hyperlinks anywhere in your PDF, to external URLs or to other pages within the document. Share & Print Shortcuts Share or print directly from the editing screen, home screen, and viewer. No extra steps. Minor Updates Paste images directly from clipboard into your PDF New image editing tools for more control over images inside documents Bug Fixes Fixed file saving issues on Windows and Linux Everything still works fully offline. No login, no cloud, no account. Your files stay on your device. Download: RevPDF 4.5.0 | 58.0 MB (Open Source) Links: RevPDF Home Page | Github | Screenshots 1 | 2 Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Interesting. I'm not using a VPN with my phone. I tried though my home internet (Rogers) and my cellular internet (Telus) using their respective DNS servers and both trigger the dialog above.
    • Three days after Anthropic launched Claude Fable 5 as the most capable AI model it had ever released to the public, the United States government ordered it switched off — and now the company is refunding customers who paid to use a product that vanished almost overnight https://www.techtimes.com/articles/318342/20260613/us-government-pulls-anthropics-fable-5-offline-now-come-refunds-vanished-ai.htm  
    • Microsoft fired the team and replaced them with AI and this is what you get.
  • Recent Achievements

    • Week One Done
      agatameier earned a badge
      Week One Done
    • One Month Later
      agatameier earned a badge
      One Month Later
    • Week One Done
      ssd21345 earned a badge
      Week One Done
    • Contributor
      MarkHughes4096 went up a rank
      Contributor
    • Dedicated
      jordanspringer earned a badge
      Dedicated
  • Popular Contributors

    1. 1
      +primortal
      507
    2. 2
      +Edouard
      175
    3. 3
      PsYcHoKiLLa
      139
    4. 4
      ATLien_0
      90
    5. 5
      Steven P.
      76
  • Tell a friend

    Love Neowin? Tell a friend!