Cookie在PHP中无法正常工作以重定向

时间:2013-11-17 01:12:38

标签: php redirect cookies

我的代码似乎有问题。如果没有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';
    }
}

2 个答案:

答案 0 :(得分:0)

除了脚本中的一堆不良做法之外,我认为导致故障的是:

$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,以便您可以更轻松地调试简单错误。

答案 1 :(得分:0)

不推荐使用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();
}

附注:不要存储纯文本密码。您应该哈希密码并添加盐。