在PHP中,會(huì)話持久化是將用戶會(huì)話數(shù)據(jù)存儲(chǔ)在服務(wù)器上,以便在不同的請求之間保持用戶狀態(tài)。以下是幾種實(shí)現(xiàn)PHP會(huì)話持久化的方法:
session.save_handler
配置選項(xiàng)設(shè)置為files
時(shí),PHP會(huì)將會(huì)話數(shù)據(jù)保存在服務(wù)器的/tmp
目錄下的臨時(shí)文件中。為了使用默認(rèn)的文件會(huì)話存儲(chǔ)機(jī)制,只需確保php.ini
文件中的以下設(shè)置正確:session.save_handler = files
session_set_save_handler()
函數(shù)將PHP的會(huì)話處理器設(shè)置為自定義的數(shù)據(jù)庫存儲(chǔ)處理器。以下是一個(gè)簡單的示例:首先,創(chuàng)建一個(gè)名為sessions
的表:
CREATE TABLE sessions (
id CHAR(32) PRIMARY KEY,
data TEXT,
expires INT
);
然后,創(chuàng)建一個(gè)自定義的會(huì)話處理器類:
class SessionHandlerDatabase {
private $db;
public function __construct($db) {
$this->db = $db;
}
public function open($savePath, $sessionName) {
return true;
}
public function close() {
return true;
}
public function read($sessionId) {
$query = "SELECT data FROM sessions WHERE id = ? AND expires > ?";
$stmt = $this->db->prepare($query);
$stmt->bind_param("si", $sessionId, time());
$stmt->execute();
$result = $stmt->get_result();
if ($row = $result->fetch_assoc()) {
return $row['data'];
}
return '';
}
public function write($sessionId, $data) {
$expires = time() + ini_get('session.gc_maxlifetime');
$query = "INSERT INTO sessions (id, data, expires) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE data = ?, expires = ?";
$stmt = $this->db->prepare($query);
$stmt->bind_param("ssii", $sessionId, $data, $expires, $data, $expires);
return $stmt->execute();
}
public function destroy($sessionId) {
$query = "DELETE FROM sessions WHERE id = ?";
$stmt = $this->db->prepare($query);
$stmt->bind_param("s", $sessionId);
return $stmt->execute();
}
public function gc($maxlifetime) {
$query = "DELETE FROM sessions WHERE expires < ?";
$stmt = $this->db->prepare($query);
$stmt->bind_param("i", time() - $maxlifetime);
return $stmt->execute();
}
}
接下來,使用session_set_save_handler()
函數(shù)將自定義的數(shù)據(jù)庫會(huì)話處理器設(shè)置為PHP的會(huì)話處理器:
$db = new PDO('mysql:host=localhost;dbname=mydb', 'username', 'password');
$sessionHandler = new SessionHandlerDatabase($db);
session_set_save_handler($sessionHandler, true);
session_start();
現(xiàn)在,您可以像往常一樣使用$_SESSION
超全局?jǐn)?shù)組來存儲(chǔ)和訪問會(huì)話數(shù)據(jù)。會(huì)話數(shù)據(jù)將存儲(chǔ)在數(shù)據(jù)庫中,并在不同的請求之間保持。
phpredis
或memcached
),并創(chuàng)建一個(gè)自定義的會(huì)話處理器類,該類將使用所選存儲(chǔ)機(jī)制來存儲(chǔ)和檢索會(huì)話數(shù)據(jù)。然后,使用session_set_save_handler()
函數(shù)將自定義的會(huì)話處理器設(shè)置為PHP的會(huì)話處理器。