php setcookie,在浏览器重启时没有到期

时间:2018-04-05 02:23:14

标签: php cookies

我设置了一个将expire参数设置为0的cookie:

然后我重定向到我检查cookie的另一个页面。浏览器重启后,它仍然存在。

使用" 0"对于过期,当浏览器重新启动时,cookie应该会过期。

session.gc_maxlifetime设置为非常低的值并没有帮助。

编辑: 完整的2个文件:

登录页面:

<html>
<head>
<title>User Logon</title>
</head>
<body>
<?php
/* These are our valid username and passwords */

$user = 'jonny4';
$pass = 'delafoo';

if (isset($_POST['username']) && isset($_POST['password'])) {

    if (($_POST['username'] == $user) && ($_POST['password'] == $pass)) {

        if (isset($_POST['rememberme'])) {
            /* Set cookie to last 1 year */
            setcookie('username', $_POST['username'], time()+60*60*24*365, '/', 'stateful.example.com');
            setcookie('password', md5($_POST['password']), time()+60*60*24*365, '/', 'stateful.example.com');
            echo "you're logged in! (remembers)";

        } else {
            /* Cookie expires when browser closes */
            setcookie('username', $_POST['username'], 0, '/', 'stateful.example.com');
            setcookie('password', md5($_POST['password']), 0, '/', 'stateful.example.com');
            echo "you're logged in!";
        }
        header('Location: statefullogged.php');

    } else {
        echo 'Username/Password Invalid';
    }

} else {
    echo 'You must supply a username and password.';
}
?>

<h2>User Login </h2>
<form name="login" method="post" action="#"> <!--au lieu de action="login.php"-->
   Username: <input type="text" name="username"><br>
   Password: <input type="password" name="password"><br>
   Remember Me: <input type="checkbox" name="rememberme" value="1"><br>
   <input type="submit" name="submit" value="Login!">
</form>
</body>
</html>

记录页面(cookie保持活动状态):

<html>
<head>
<title>User Logged</title>
</head>
<body>
<?php
if(!isset($_COOKIE['username'])) {
    header("Location: statefullogin.php");
} else {
    echo "username: " . $_COOKIE['username'];
}
?>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

如果此测试失败,那么除了浏览器之外没有任何可以与cookie保持活动的其他内容......

if (isset($_COOKIE['session_only'])) {
  echo 'cookie exists';
} else {
  setcookie('session_only', 'testing_cookie', 0);
  echo 'cookie not found, setting new cookie';
}