如何在登录后将用户重定向回所需的URL(php)

如何在登录后将用户重定向回所需的URL(php)

问题描述:

user clicked the link

http:://www.myapp.com/anypage.php he is not logged then he should be redirect to

http://www.myapp.com/login.php

how to redirect him back to http:://www.myapp.com/anypage.php after success login

i do this

if (strpos($_SERVER["HTTP_REFERER"],'myapp.com') !== false && strpos($_SERVER["HTTP_REFERER"],'login')  !== false) {
                            //echo found

                                //$this->redirect($_SERVER["HTTP_REFERER"]);
                            }

i know this error but i could not found other solution as i will read HTTP_REFERER to login page

After login, you can change the http header to a different location to create a redirect.

if(Successful Login) {
    header("location: success.php");
    exit(); //to stop script 
}
else { //unsuccessful
    header("location: login.php");
    exit(); 
}

Just make sure this code goes before any html markup, or before you echo/print anything out with php.

To get the script to redirect to the page the user was on before their session expired combine the above with the following:

This next line of code must be AFTER where you check for a timeout in your script.

Get the current page and store it in the session:

$_SESSION['page'] = __FILE__;

In the part of the script where we check if the login has expired, which must be before the line of code above, we can pull out what was the last page from the 'page' field in the session, and pass it in the query string back to the login page. This means that if the user logs in successfully again, you can pull the page they were on from the query string and redirect them from it.

To check for a timeout

if(user login is timed out) {

    $header = "login.php?redirect=".$_SESSION['page']; //won't have been changed to the current page yet.
    header("location: ".$header);

}

On login.php or whatever your login page is, check if the redirect field is set in the query string. If it is you could add it as a hidden field in your form

if(isset($_GET['redirect'])) {

    echo "<input name='redirect' type='hidden' value='".$_GET['redirect']."' />";

}

And finally on the script where you validate your login, you could check to see if the redirect field was present or set.

If you posted the form you could do:

//Validate login

if(valid login) {

   //check if redirect was set
   if(isset($_POST['redirect'])) {

       header("location: ".$_POST['redirect']);
       exit();

   }
   else
     //go to normal landing page

}