PHP redirect back to previous page

懵懂的女人 提交于 2019-12-06 07:32:57

问题


What I have done for the login.php page is if a user has logged in, he will be redirected to first.php page.

session_start();
if(isset($_SESSION['usr']) && isset($_SESSION['pswd'])){
    header("Location: first.php");
} 

In all other pages, if user hasn't logged in he will be redirected to login.php page.

session_start();
if(!isset($_SESSION['usr']) || !isset($_SESSION['pswd'])){
    header("Location: login.php");
} 

Here is the problem: is there a way to redirect the user back to where he was from? Say if you are trying to reach second.php while you are not logged in, you will be redirected to login.php page now; once you log in, can you be redirected back to second.php instead of first.php?

I have tried to use $_SERVER['HTTP_REFERER'], but this variable doesn't contain anything; it only contain something if you are here because you have clicked a link.


回答1:


  1. On the page they try to login set a session variable containing the URL of that page.
  2. Then redirect them to the login page.
  3. After a successful login get the previous URL from their session and redirect them there.

Have the page that does the redirecting set a session variable that is the URL of that page:

session_start();
if (!$logged_in)
{
    $_SESSION['redirect_url'] = $_SERVER['PHP_SELF']; 
    header('Location: login.php');
    exit;
}

Then after a successful login redirect them to that URL:

session_start();

/* Login code goes here */

$redirect_url = (isset($_SESSION['redirect_url'])) ? $_SESSION['redirect_url'] : '/';
unset($_SESSION['redirect_url']);
header("Location: $redirect_url", true, 303);
exit;

The above can be improved upon but this should give you the idea.




回答2:


$_SERVER['HTTP_REFERER'] depends on the Web Browser, not all browser sends the referrer back to the server. A better approach, used by many big sites, is passing on the current page to the login page:

header("Location: first.php?".$currentPageUrl);

The $currentPageUrl can be get from the $_SERVER['REQUEST_URI'] or $_SERVER['PHP_SELF'];

Upon login you can redirect user to the $currentPageUrl again.

Apart from this, it does not sound right to store the user name and password in the $_SESSION, but this is a separate issue.



来源:https://stackoverflow.com/questions/17847316/php-redirect-back-to-previous-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!