<?php
class FileSessionHandler
{
private $savePath;
public function __construct($savePath)
{
ini_set('session.serialize_handler', 'php_serialize');
$this->savePath = $savePath;
session_set_save_handler(
array($this, 'open'),
array($this, 'close'),
array($this, 'read'),
array($this, 'write'),
array($this, 'destroy'),
array($this, 'gc')
);
}
function open($savePath, $sessionName)
{
echo __METHOD__."<br/>";
return true;
}
function close()
{
echo __METHOD__."<br/>";
return true;
}
function read($id)
{
echo __METHOD__."<br/>";
foreach (glob("$this->savePath/sess_{$id}_*") as $file) {
return (string)@file_get_contents($file);
}
}
function write($id, $data)
{
echo __METHOD__."<br/>";
$arr = unserialize($data);
if(array_key_exists('user', $arr))
{
$user = $arr['user'];
foreach (glob("$this->savePath/sess_*_$user") as $file) {
unlink($file);
}
return file_put_contents("$this->savePath/sess_{$id}_$user", $data) === false ? false : true;
}
else
{
return file_put_contents("$this->savePath/sess_{$id}_", $data) === false ? false : true;
}
}
function destroy($id)
{
echo __METHOD__."<br/>";
$file = "$this->savePath/sess_$id";
if (file_exists($file)) {
unlink($file);
}
return true;
}
function gc($maxlifetime)
{
echo __METHOD__."<br/>";
foreach (glob("$this->savePath/sess_*") as $file) {
if (filemtime($file) + $maxlifetime < time() && file_exists($file)) {
unlink($file);
}
}
return true;
}
function get($key=null)
{
if($key === null) return $_SESSION;
else return isset($_SESSION[$key])? $_SESSION[$key] : '';
}
function set($key, $data)
{
return $_SESSION[$key] = $data;
}
}
$handler = new FileSessionHandler('E:\localhost\sessions');
session_start();
print_r($handler->get());
// $handler->set('user', 1);
// print_r($handler->get());
// echo '*********************<br/>';
/*$handler->set('user', 1);
print_r($handler->get());*/
class login {
private $sessionHandler;
public function __construct(FileSessionHandler $sessionHandler)
{
$this->sessionHandler = $sessionHandler;
}
public function login()
{
if($this->sessionHandler->get())
{
$this->index();
}
else
{
$user = $_GET['user'];
$this->sessionHandler->set('user', $user);
}
}
public function index()
{
echo '您已登录!';
}
}
/*$arr['a'] = 1;
var_dump(serialize($arr));*/
session 顺序
![]()