我试图使用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>
所以我觉得我错过了一些基本的东西。很抱歉,如果答案很明显,饼干对我来说是新的。谢谢你们的帮助。
您的问题在这一行:
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