doubijiao2094 2014-03-27 15:54
浏览 32

PHP setcookie()问题

I have a php file:

<?php 
$username = $_POST["username"];

if((!$username) || (!$_POST["password"])){
    header("Location:http://localhost/login.html");
    exit;
}

$db_name = "muzak";
$tblname = "auth_users";
$connection = mysqli_connect("localhost", "***username***", "***password***", $db_name) or die("Couldn't connect to database");
$sql = "SELECT * FROM $tblname WHERE username = '$username' AND password= password('$_POST[password]')";

$result = mysqli_query($connection, $sql) or die(mysqli_error($connection));

$numHits = mysqli_num_rows($result);
var_dump($numHits);//equal to one

if($numHits > 0){
    $cookie_name = "auth";
    $cookie_value = "ok";
    $cookie_expire = "0";
    $cookie_domain = "127.0.0.1";
    setcookie($cookie_name, $cookie_value, $cookie_expire, "/" , $cookie_domain, 0);

    $display = "<li><a href=\"secret_areaA.php\">Secret Area A</a></li>
                <li><a href=\"secret_areaB.php\">Secret Area B</a>  </li>";
}else{
    header("Location:http://localhost/login.html");
}
?>
<html>
<head>
<title>Secret Menu</title>
</head>
<body>
<?php echo $display;?>
</body>
</html>

Which takes input from an html file and asks a database for confirmation. The HTML part works fine, but when I try to check for the presence of the cookie in the secret_areaA.php file . . .

<?php 
if($_COOKIE["auth"] == "ok"){
    $msg = "<p><Welcome to the first secret area!<p>";
}else{
    die("Cookie wasn't valid");
}
?>
<html>
<head>
<title>
    Secret Area A
</title>
</head>
<body>
<?php echo $msg;?>
</body>
</html>

I get this error: Notice: Undefined index: auth in C:\xampp\htdocs\secret_areaA.php on line 2.

What am I doing wrong?

  • 写回答

2条回答 默认 最新

  • dongzhi6905 2014-03-27 15:56
    关注

    You need to check if the cookie is set (exists) using isset(), before you try to compare the value. This way, if the cookie hasn't been set, we don't try to access a part of the $_COOKIE array that can't exist (['auth']).

    if ( isset( $_COOKIE['auth'] ) && $_COOKIE['auth'] == 'ok' ){
    } else {
    }
    
    评论

报告相同问题?