PHP session_start 不触及会话文件

PHP session_start without touching session file

我有一个 JavaScript setInterval(),它每 15 秒左右对服务器执行一次 ping 操作。

问题是人为地延长了用户会话,因为用户自己可能很闲。

在不接触实际会话文件的情况下获取我从 session_start() 获得的信息的最佳方法是什么?换句话说,我的调用不会影响延长会话的到期时间。

可以这样做:

$session = $_COOKIE['PHPSESSID']; //obvs. you must know the name
$path = ini_get('session.save_path') . '/sess_' . $session; //your session file syntax may vary

// now read the file.  Note this doesn't touch the file open time, I've tested it
$string = implode('', file($path));

// parsing session string syntax to array looks complex, so do this:
$fp = fopen( substr($path, 0, strlen($path) - 3) . '---', 'w' );
fwrite($fp, $string);
fclose($fp);

// open the created file and let PHP parse it:
session_id( substr($session, 0, strlen($session) - 3) . '---' );
session_start();

// now we correct the Set-Cookie header that would contain dashes at the end
header_remove('Set-Cookie');
setcookie('PHPSESSID', $session);

// and, we're good to go having read the session file but not touched/affected it's expiry time!

显然我更愿意做类似 session_start(['read_without_affecting_expiry' => true]) 的事情,但我认为这不可行,我只希望在某些情况下这样做。