0

所以,我现在在这个 PHP 代码上苦苦挣扎了 1 周,但仍然无法正常工作。我需要为用户设置 1 年的 cookie,并且当他关闭浏览器并稍后再次访问我们的网站时,不必再次登录。如果有人可以编写应该​​在我的文件中设置的代码,我将不胜感激。我的原始代码如下,它来自我的 config.php 文件。提前谢谢了!

function create_slrememberme() {
        $key = md5(uniqid(rand(), true));
        global $conn;
        $sql="update members set remember_me_time='".date('Y-m-d H:i:s')."', remember_me_key='".$key."' WHERE username='".mysql_real_escape_string($_SESSION[USERNAME])."'";
        $conn->execute($sql);
        setcookie('slrememberme', gzcompress(serialize(array($_SESSION[USERNAME], $key)), 9), time()+60*60*24*30);
}

function destroy_slrememberme($username) {
        if (strlen($username) > 0) {
                global $conn;
                $sql="update members set remember_me_time=NULL, remember_me_key=NULL WHERE username='".mysql_real_escape_string($username)."'";
                $conn->execute($sql);
        }
        setcookie ("slrememberme", "", time() - 3600);
}

if (!isset($_SESSION["USERNAME"]) && isset($_COOKIE['slrememberme'])) 
{
        $sql="update members set remember_me_time=NULL and remember_me_key=NULL WHERE remember_me_time<'".date('Y-m-d H:i:s', mktime(0, 0, 0, date("m")-1, date("d"),   date("Y")))."'";
        $conn->execute($sql);
        list($username, $key) = @unserialize(gzuncompress(stripslashes($_COOKIE['slrememberme'])));
        if (strlen($username) > 0 && strlen($key) > 0)
        {
            $sql="SELECT status,USERID,email,username,verified from members WHERE username='".mysql_real_escape_string($username)."' and remember_me_key='".mysql_real_escape_string($key)."'";
            $rs=$conn->execute($sql);
            if($rs->recordcount()<1)
            {
                $error = "Error: Could not locate your account.";
            }
            elseif($rs->fields['status'] == "0")
            {
                $error = "Error: Your account has been disabled by the administrator.";
            }
            if($error=="")
            {               
                $_SESSION['USERID']=$rs->fields['USERID'];
                $_SESSION['EMAIL']=$rs->fields['email'];
                $_SESSION['USERNAME']=$rs->fields['username'];
                $_SESSION['VERIFIED']=$rs->fields['verified'];
                create_slrememberme();
            }
            else
            {
                destroy_slrememberme($username);
            }
        }
}
4

2 回答 2

3

这一行: -

setcookie ("slrememberme", "", time() - 3600);

正在将您的 cookie 设置为过去过期,即它已经过期!

要将其设置为一年,您需要执行以下操作:-

setcookie("slrememberme", "", time()+60*60*24*30*365);

将设置大约 1 年。

有关详细信息,请参阅手册。

此外,这一行: -

if (!isset($_SESSION["USERNAME"]) && isset($_COOKIE['slrememberme']))

应该:-

if (isset($_SESSION["USERNAME"]) && isset($_COOKIE['slrememberme']))

您可能需要设置位于 php.ini 文件中的 cookie-expiry 函数,名为session.cookie_lifetime. 您应该将其设置为 31536000,这将使其在 1 年后到期,它可能设置为 0。

于 2012-07-29T20:12:41.950 回答
0
setcookie('usuario-logado', 'true', (time() + ( 24 * 3600)));
于 2015-08-21T19:03:54.647 回答