簡體   English   中英

PHP自定義會話處理程序行為

[英]PHP Custom Session Handler Behavior

我無法讓我的自定義會話處理程序在不同的頁面請求之間工作。 最初創建會話時,處理程序將按預期工作,但是當我導航到另一個頁面時,會話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

任何幫助弄清楚如何使其正常工作將不勝感激!

顯然,會話處理程序的writeread方法無效。 嘗試修復它。 您可以在$ _SESSION中設置變量,並在同一頁面中使用它,因為PHP在腳本末尾使用了會話處理程序。

能夠弄清楚。 您是正確的,讀/寫功能已損壞。 在讀寫時,我需要對數據進行序列化和反序列化。 謝謝你的幫助。

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));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM