Cookie无效

时间:2012-08-27 14:03:56

标签: php cookies

我尝试使用cookie记住登录信息,但cookie似乎从来没有像现在这样“采取”。这是初始登录脚本:

//try to login using cookies, but first make sure it doesn't have a $_SESSION variable for it
if (!(isset($_SESSION['valid_user']))) {
    if (isset($_COOKIE["login"])) {
        //try to login using cookie
        $query = "select from cookie_users where uniqueid = '".$_COOKIE["login"]."')";
        $conn = new mysqli('localhost', 'user', 'password', 'test');
        $result = $conn->query($query);
        if ($result->num_rows>0) {
            $result->fetch_assoc();
            $result['username'] = $username;
            $result['password'] = $password;
            //try to login using password and username from cookie database
            $query = "select * from authorized_users where username = '".$username."' and password = '".$password."'";
            $result2 = $conn->query($query);
            if ($result->num_rows>0) {
                $_SESSION['valid_user'] = $username;
            }
        }
    }
}

if (isset($_POST['userid']) && isset($_POST['password'])) {
    // if the user has just tried to log in
    $userid = $_POST['userid'];
    $password = $_POST['password'];

    $db_conn=new mysqli('localhost', 'user', 'password', 'test');

    if (mysqli_connect_errno()) {
        echo 'Connection to database failed: '.mysqli_connect_errno();
        exit;
    }
    $query = 'select * from authorized_users '."where name='$userid' "."and password=sha1('$password')";

    $result = $db_conn->query($query);
    if ($result->num_rows > 0) {
        //if they are in the database, register the user id
        $_SESSION['valid_user'] = $userid;
        //set up cookie
        setcookie("login", $uniqueid, time()*60*60*24*14);
        $query = "insert into cookie_users values ('".$userid."', sha1('".$password."'), '".$uniqueid."')";
        $result = $db_conn->query($query);
        if (!$result) {
            echo 'Could not update cookie in database';
        }
    }
    $db_conn->close();
}

仅限会员:

if (isset($_SESSION['valid_user'] {
echo "members only content goes here";
} else {
echo "you need to login"; }

会话和登录脚本工作得很好。如果他们直接使用登录页面登录,则会显示。如果他们去另一页然后回来,它仍然有效;这让我相信会议工作得很好。但是,如果您关闭浏览器并返回,则不会注册。如果有什么东西搞砸了剧本,请告诉我。无论哪种方式,我做了一个测试脚本,甚至没有工作。这是:

<?php

setcookie("test", "the test is good", time()*60*60);

?>

<html>
<body>
<?php
echo $_COOKIE["test"];
?>
</body>
</html>

所以我认为我缺少一些基本的东西。很抱歉,如果答案很明显,那么Cookie对我来说是新的。谢谢你们给予的任何帮助。

1 个答案:

答案 0 :(得分:3)

你的问题在这一行:

setcookie("login", $uniqueid, time()*60*60*24*14);

在这里,您将时间乘以而不是添加时间。您已将其乘以超过 MAX_INT 尺寸(请参阅Y2038)。无论出于何种原因,Apache(至少在我的系统上)将忽略该标头,然后浏览器将仅保留会话的长度。幸运的是,您可以非常简单地解决问题:

setcookie("login", $uniqueid, time() + 60*60*24*14); // Adding two weeks, not multipying by >9000