一种常见的方法是通过
$_GET变量将用户的当前页面传递到“登录”表单。
例如:如果您正在阅读文章,并且想要发表评论。评论的网址为
comment.php?articleid=17。虽然
comment.php是装载,它注意到您还没有登录,它要送你去
login.php,像你刚才表现。但是,我们将更改您的脚本,这样也可以告诉登录页面记住您的位置:
header("Location:login.php?location=" . urlenpre($_SERVER['REQUEST_URI']));// Note: $_SERVER['REQUEST_URI'] is your current page这会将用户发送至:
login.php?location=comment.php%3Farticleid%3D17。
login.php现在应该检查是否
$_GET['location']已填充。如果已填充,则将用户发送到该位置(在这种情况下为
comment.php?articleid=17)。例如:
// login.phpecho '<input type="hidden" name="location" value="';if(isset($_GET['location'])) { echo htmlspecialchars($_GET['location']);}echo '" />';// Will show something like this:// <input type="hidden" name="location" value="comment.php?articleid=17" />// login-check.phpsession_start();// our url is now stored as $_POST['location'] (posted from login.php). If it's blank, let's ignore it. Otherwise, let's do something with it.$redirect = NULL;if($_POST['location'] != '') { $redirect = $_POST['location'];}if((empty($username) OR empty($password) AND !isset($_SESSION['id_login']))) { $url = 'login.php?p=1'; // if we have a redirect URL, pass it back to login.php so we don't forget it if(isset($redirect)) { $url .= '&location=' . urlenpre($redirect); } header("Location: " . $url); exit();}elseif (!user_exists($username,$password) AND !isset($_SESSION['id_login'])) { $url = 'login.php?p=2'; if(isset($redirect)) { $url .= '&location=' . urlenpre($redirect); } header("Location:" . $url); exit();}elseif(isset($_SESSION['id_login'])) { // if login is successful and there is a redirect address, send the user directly there if($redirect) { header("Location:". $redirect); } else { header("Location:login.php?p=3"); } exit();}陷阱
$_GET['location']在将用户发送到那里之前,应该对它进行一些验证。例如,如果我告诉使用您网站的人单击此链接:
login.php?location=http%3A%2F%2Fmalice.com%2Fevilpage.php…,那么他们将被发送到一个外部URL,该URL会尝试执行不良操作。
始终
urlenpre在将URL作为
$_GET参数传递时使用。这种编码特殊网址字符(例如
?,
&和
%),以便它们不会打破你的URL(如:
login.php?location=comment.php?id=17<
-这样做有两个
?的,将无法正常工作)



