1

I was trying to redirect users to the previous page after authentication. It works well with the below codes.

The file login_page.php (the page where users enter login credentials) contains the below code which stores the SOURCE URL and passes it to next page.

<input type="hidden" name="url" value=<?php echo $_SERVER['HTTP_REFERER'] ; ?> />

File do_authentication.php (page which does the authentication) has the code echo "<meta http-equiv='Refresh' content=0;url='$_POST[url]'>"; which redirects to SOURCE URL

In the normal situation it works, but in situations when user enters wrong credentials, the page is redirected to login_page.php and it asks the user to try again with correct credentials. At that time, 'url' value changes to login_page.php.

What is the correct/better logic to solve this?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jestin
  • 111
  • 6

5 Answers5

0

Use:

header("location: ".$_POST['url']); // Redirects to posted page
exit; // Prevents execution of other code after this
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Luceos
  • 6,629
  • 1
  • 35
  • 65
  • this and the referer both work first time around, but not after a failed login. At that point the referer and url are the login itself. – Peter Wooster Jan 16 '13 at 12:37
0

I've always used the session to retain the original page when doing login. This will not work if the session isn't supported. Then I just send the user to the home page.

A Stack Overflow post discussing this is Redirect to previous page after logging in using PHP.

Community
  • 1
  • 1
Peter Wooster
  • 6,009
  • 2
  • 27
  • 39
  • Session works for me.... Login_page.php `//Create session to redirect page to original pg if(!isset($_SESSION['url'])) { $_SESSION['url'] = $_SERVER['HTTP_REFERER']; }` do_authentication.php `echo ""; unset($_SESSION['url']);` – Jestin Jan 17 '13 at 05:28
0

In login_page.php, you could check if you already passed a URL; if so, pass this one instead of the HTTP_REFERER.

<?php if(isset($_POST['url']) ?>
    <input type="hidden" name="url" value=<?php echo $_POST['url'] ; ?> />
<?php else ?>
    <input type="hidden" name="url" value=<?php echo $_SERVER['HTTP_REFERER'] ; ?> />

Or in a more concise way

<?php $url= (isset($_POST['url'])) ? $_POST['url'] : $_SERVER['HTTP_REFERER']; ?>
<input type="hidden" name="url" value=<?php echo $url; ?> />
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Winks
  • 395
  • 2
  • 9
0

You should consider using session variables to store the value of the page you want to redirect to. HTTP_REFERRER is not right option.

CuriousMind
  • 3,143
  • 3
  • 29
  • 54
0

Just try below:

<input type="hidden" name="url" value=<?php echo pathinfo(__FILE__,PATHINFO_FILENAME ).".".pathinfo(__FILE__,PATHINFO_EXTENSION); ?> />
Suresh Kamrushi
  • 15,627
  • 13
  • 75
  • 90