[英]Cookies not working properly in PHP to redirect
我的代码似乎有问题。 如果不存在cookie,它就不会重定向;如果存在cookie,它就不会包含我的header.php。 我做了一个测试cookie脚本,可以确认cookie是否存在。
码:
//checks cookies to make sure they are logged in
if(isset($_COOKIE["user"]))
{
$username = $_COOKIE["user"];
$pass = $_COOKIE["password"];
$check = mysql_query("SELECT * FROM members WHERE email = '$username'") or die(mysql_error());
$info = mysql_fetch_array( $check );
//if the cookie has the wrong password, they are taken to the login page
if ($pass != $info['password'])
{
header("Location: login.php");
exit();
}
else //otherwise they are shown the admin area
{
include 'header.php';
}
}
除了脚本中的许多不良做法外,我认为导致故障的原因还包括:
$info = mysql_fetch_array( $check );
if ($pass != $info['password'])
如果您关注手册,它就是它的意思
返回值
返回与获取的行相对应的字符串数组 ;如果没有更多行,则返回FALSE。
所以代码应该看起来像
$info = mysql_fetch_array( $check );
if ($pass != $info[0]['password'])
或者在PHP GTE 5.4中
$info = mysql_fetch_array( $check )[0];
if ($pass != $info['password'])
您应该确保已将display_errors
设置为E_ALL
以便可以轻松调试一些简单的错误。
不建议使用MySQL函数。 应该使用Mysqli或PDO,以及准备好的语句。 例:
//checks cookies to make sure they are logged in
if(isset($_COOKIE["user"]) && isset($_COOKIE["password"])) {
$password = $_COOKIE["password"];
/* Create the prepared statement */
if ($stmt = $mysqli->prepare("SELECT password FROM members WHERE email = ?")) {
/*bind parameters */
$stmt->bind_param("s", $_COOKIE['user']);
/* Execute the prepared Statement */
$stmt->execute();
/* Bind results to variables */
$stmt->bind_result($dbPassword);
/* fetch values */
$stmt->fetch();
if($password != $dbPassword) {
//password didn't match, boot 'em
header('Location:fail.php');
exit();
}
//password matched, let 'em in
else {
header('Location:pass.php');
exit();
}
}
//no cookies set, boot 'em
else {
header('Location:fail.php');
exit();
}
注意事项:不要存储纯文本密码。 您应该对密码进行哈希处理,然后添加盐。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.