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 {
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程