我无法让自定义会话处理程序在不同的页面请求之间工作。最初创建会话时,处理程序按预期工作,但是当我导航到另一个页面时,会话cookie和会话ID保持不变,但会话数据被删除。
例如,
class NativeSessionHandler implements \SessionHandlerInterface
{
protected $rootDir = '/tmp';
protected $savePath;
public function open($savePath, $name)
{
$this->savePath = $this->rootDir . '/' . $savePath;
if (! is_dir($this->savePath)) {
mkdir($this->savePath);
}
return true;
}
public function close()
{
return true;
}
public function read($sessionId)
{
$file = $this->savePath . $sessionId;
if (file_exists($file)) {
file_get_contents($file);
}
return true;
}
public function write($sessionId, $data)
{
$file = $this->savePath . $sessionId;
return file_put_contents($file, $data);
}
public function destroy($sessionId)
{
$file = $this->savePath . $sessionId;
if (file_exists($file)) {
unlink($file);
}
return true;
}
public function gc($maxlifetime)
{
foreach (glob($this->savePath) as $file) {
if (file_exists($file) && filemtime($file) + $maxlifetime < time()) {
unlink($file);
}
}
return true;
}
}
// index.php
$handler = new NativeSessionHandler();
session_set_save_handler($handler);
session_start();
$_SESSION['foo'] = 'bar';
echo session_id();
var_dump($_SESSION); // 'foo' => 'bar'
// page.php
$handler = new NativeSessionHandler();
session_set_save_handler($handler);
session_start();
echo session_id(); // same session ID as on index.php
var_dump($_SESSION); // returns null
任何有助于确定如何使其正常工作的帮助将不胜感激!
答案 0 :(得分:1)
显然,会话处理程序的write
或read
方法不起作用。尝试解决它。您可以在$ _SESSION中设置变量并在同一页面中使用它,因为PHP在脚本的末尾使用您的会话处理程序。
答案 1 :(得分:0)
能够弄清楚。你读/写功能被破坏是对的。我需要在读写时序列化和反序列化数据。谢谢你的帮助。
public function read($sessionId)
{
$file = $this->savePath . $sessionId;
if (file_exists($file)) {
$data = file_get_contents($file);
return unserialize($data);
}
}
public function write($sessionId, $data)
{
$file = $this->savePath . $sessionId;
return file_put_contents($file, serialize($data));
}