2

我尝试使用 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 对我来说是新的。感谢你们提供的任何帮助。

4

1 回答 1

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
于 2012-08-27T14:23:29.723 回答