0

你好,

如果用户在我的网站上有多个帐户,我如何设置像“last_visit”这样的 cookie 我尝试了一些方法但我失败了。

这是用户注销时的代码

setcookie('last_visit',time(),time()+60*60*24*30*12);

但是当用户使用另一个帐户重新登录时,页面会使用此代码读取他第一个帐户的最后一次访问

  $lastvisit = $_COOKIE['last_visit'];

我可以在一个 cookie 中将上次访问 cookie 与用户 id cookie 链接起来吗

请帮助我正确的方法

4

2 回答 2

0

在编写新的 cookie 时尝试删除现有的或旧的 cookie。进行互斥登录,当人们登录到一个帐户时,他们会从其他帐户中注销。

于 2012-06-15T07:37:36.427 回答
0

两种选择:一种是创建用户 ID 和上次访问的关联数组,并将其存储为 cookie 的内容。第二个选项是为每个用户创建一个名为“last_visit_[user_id]”的 cookie。第一个可能更友好,它需要更少的用户 cookie。


编辑 - 这是一个未经测试的示例。抱歉有任何错误,但这应该给你要点。

关键数据存储在 $aLastLogged[UserID] = TimeLastLogged; 的关联数组中。

// This will be the user id of hte current user as set somewhere else.
$userID = 123;


// This will store the time the user last logged on. 0 = not logged on
$LastLoggedOn = 0;

// Read the cookie - allow for errors!
$aLastLogged = false;  // Start with "false" and we'll correct later if is works
// Check if cookie exists
if (isset($_COOKIE['last_logged'])) {
    // Read the cookie contents. The @ hides the errors in case the cookie is corrupted
    $aLastLogged = @unserialize($_COOKIE['last_logged']);
}

// At this point, aLastLogged will be an array, or false if it was not set or failed

if ($aLastLogged) {
    // See if this user has been here before by checking if there is an element in the array
    if (isset($aLastLogged[$userID])) {
        $LastLoggedOn = (int)$aLastLogged[$userID];
        // Note - I cast as "int" to check it's a valid number. You could alos check hte range is valid - just in case someone's been fiddlign with the cookie. Trust no input, ever, including cookies
    }
} else {
    // Create a blank array for the cookie
    $aLastLogged = array();
}


// At this point, you have the time in $LastLoggedOn

// Now update the cookie by creating / updating hte associative element
$aLastLogged[$user_ID] = time();
// Set the cookie; set the time and path and domain as required - the following is for 1 day - you'll want longer.
setcookie('last_logged', serialize($aLastLogged), time() + 86400, '/');  
于 2012-06-15T07:38:28.530 回答