两种选择:一种是创建用户 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, '/');