我目前正在使用PHP / MySQL,我想知道进行未经身份验证的用户登录的最佳方法,然后让它们自动重定向到他们登录的页面。
例如:
1)用户尝试打开安全页面 2)他们被重新定向并提示登录 3)成功登录后,他们将被带回他们试图访问的URL。
目前,在我的“安全”页面上,我设置了以下PHP代码:(甚至不确定这是否是正确的'安全'方式):
<?php
session_start();
if ($_SESSION['first'] == "" && $_SESSION['usrID'] == "") {
print" <script>
window.location=\"../login/index.php\"
</script> ";
}
?>
有关如何提供此功能的任何建议(并可能使我的'安全'代码更好),我将非常感激。
谢谢!
答案 0 :(得分:2)
您可以将请求网址存储在会话版本
中$_SESSION['destination'] = $_SERVER['REQUEST_URI'];
然后,登录后,您可以执行以下操作:
if (isset($_SESSION['destination'])) {
header('Location: ' . $_SESSION['destination']);
exit;
}
此外,这不是一个好主意
print" <script>
window.location=\"../login/index.php\"
</script> ";
使用JavaScript重定向存在问题。首先,禁用JavaScript不会发生任何事情。尝试发送位置标题
header('Location: ../login/index.php');
exit; // Call exit to make sure the rest of your code never executes
答案 1 :(得分:1)
您可以在/login/index.php文件中检索引荐来源URI,并将其作为隐藏字段提供给登录表单。在用户登录后,您只需将他重定向到他之前尝试访问的页面。
类似的东西:
/login/index.php:
<?php
// if user submitted login form
if(isset($_POST['login'])) {
// do your login actions here
// and after...
header("Location: " . $_POST['returnto']);
}
//
$user_came_from = htmlspecialchars( $_SERVER['HTTP_REFERER'] );
?>
<form name="my_login_form" action="" method="post">
user: <input type="text" name="user" value="" />
pass: <input type="password" name="pass" value="" />
<input type="hidden" name="returnto" value="<?php echo $user_came_from ?>" />
<input type="submit" name="login" value="login" />
</form>