为用户设置cookie以保持登录状态

时间:2012-07-29 20:03:24

标签: php cookies

所以,我现在在这个PHP代码上挣扎了一个星期,但仍然无法使其工作。我需要为用户设置一个cookie 1年,并且当他关闭浏览器并稍后再次访问我们的网站时,不需要再次登录。如果有人可以编写应该​​在我的文件中设置的代码,我将非常感激。我的原始代码如下,它来自我的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);
            }
        }
}

2 个答案:

答案 0 :(得分:3)

这一行: -

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

将您的Cookie设置为过去过期,即它已经过期了!

要将其设置为您需要执行的一年: -

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

将设置约1年。

有关详细信息,请参阅the manual

此外,这一行: -

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

应该是: -

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

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

答案 1 :(得分:0)

setcookie('usuario-logado', 'true', (time() + ( 24 * 3600)));