1

我正在使用 PHP/MySQL 登录代码,我希望它永久存储 cookie(通过浏览器关闭),但是它不起作用。它可以正常登录,并且会记住浏览器关闭,但之后会忘记它。我怎样才能解决这个问题?

这是我认为的所有重要代码;

<?php
define('INCLUDE_CHECK',true);

require 'connect.php';
require 'functions.php';

// Those two files can be included only if INCLUDE_CHECK is defined

session_name('tzLogin');
// Starting the session

session_set_cookie_params(1000000*7*24*60*60);

session_start();

if($_SESSION['id'] && !isset($_COOKIE['tzRemember']) && !$_SESSION['rememberMe'])
{
    // If you are logged in, but you don't have the tzRemember cookie (browser restart)
    // and you have not checked the rememberMe checkbox:

    $_SESSION = array();
    session_destroy();

    // Destroy the session
}

if(isset($_GET['logoff']))
{
    $_SESSION = array();
    session_destroy();
    header("Location: index.php");
    exit;
}

if($_POST['submit']=='Login')
{
    // Checking whether the Login form has been submitted

    $err = array();
    // Will hold our errors

    if(!$_POST['username'] || !$_POST['password'])
        $err[] = 'All the fields must be filled in!';

    if(!count($err))
    {
        $_POST['username'] = mysql_real_escape_string($_POST['username']);
        $_POST['password'] = mysql_real_escape_string($_POST['password']);
        $_POST['rememberMe'] = (int)$_POST['rememberMe'];

        // Escaping all input data

        $row = mysql_fetch_assoc(mysql_query("SELECT id,usr FROM tz_members WHERE usr='{$_POST['username']}' AND pass='".md5($_POST['password'])."'"));

        if($row['usr'])
        {
            // If everything is OK login

            $_SESSION['usr']=$row['usr'];
            $_SESSION['id'] = $row['id'];
            $_SESSION['rememberMe'] = $_POST['rememberMe'];

            // Store some data in the session

            setcookie('tzRemember',$_POST['rememberMe']);
            // We create the tzRemember cookie
        }
        else $err[]='Wrong username and/or password!';
    }

    if($err)
        $_SESSION['msg']['login-err'] = implode('<br />',$err);
        // Save the error messages in the session

    header("Location: nowloggedin.php");
    exit;
}
?>
4

3 回答 3

2

您需要为 cookie 设置过期时间:

setcookie('tzRemember',$_POST['rememberMe'], time()+3600);

例如,这将使其持续一小时。如果您不设置时间,会话结束时它将过期。

我刚刚注意到您正在使用 session_set_cookie_params 设置生命周期 - 正如其他人所说,您将这种方式设置为未来太远了。

于 2012-04-12T11:02:05.783 回答
1

今年最好保持在以下...

2038 

否则会出现问题,您的浏览器不会存储它。

于 2012-04-12T11:04:40.223 回答
0

您将 cookie 设置为:

session_set_cookie_params(1000000*7*24*60*60);

这将 cookie 设置为在 1000000*7*24*60*60 = 7*1000000/365 = 19000+ 年后过期。据我所知,UNIX 时间戳没有设置这么长的持续时间。

于 2012-04-12T11:06:20.103 回答