创建具有唯一 ID 的会话 1 小时 - PHP


Creating a session with a unique ID for 1 hour - PHP

我正在尝试为用户创建一个持续 1 小时的会话 ID。

用户登录一次 - 随机ID 生成 - 添加到会话。

用户在 1 小时内再次登录,相同的会话 ID 适用。

如果用户在 1 小时后登录,请生成新 ID。

到目前为止,我有这个

session_start();  
//create random sid
$today = date('YmdHi');
$startDate = date('YmdHi', strtotime('2012-03-14 09:06:00'));
$range = $today - $startDate;
$rand = rand(0, $range);
$sid= ($startDate + $rand);
 //first time user
if(isset($_SESSION['sessionid'])) {
    $_SESSION['sessionid'] = $sid;
}
   //visiting user
else
    {
        $_SESSION['sessionid'] = $_SESSION['sessionid'];
     }
echo $_SESSION['sessionid']; 

如何添加 1 小时的超时?我见过使用饼干的例子。我希望只能使用服务器端会话?

有什么想法吗?

如果您希望将

随机 ID 附加到一小时后刷新的会话,只需存储上次与会话一起生成的时间。

例如:

session_start();
function regenerate() {
    $_SESSION['code'] = uniqid();
    $_SESSION['code_time'] = time();
}
if (empty($_SESSION['code']) || time() - $_SESSION['code_time'] > 3600)
    //if there's no code, or the code has expired
    regenerate();
echo "Your code is " . $_SESSION['code'] . " it was generated on " . date('m/d/Y h:i:s a', $_SESSION['code_time']);

如果您希望会话在首次访问后 600 秒过期:

<?php
  $lifetime=600;
  session_set_cookie_params($lifetime);
  session_start();
?>

如果您希望会话在用户最近一次访问后 600 秒过期:

<?php
  $lifetime=600;
  session_start();
  setcookie(session_name(),session_id(),time()+$lifetime);
?>

文档:http://php.net/manual/en/book.session.php