原型:
1.session_set_save_handler ( callable $open , callable $close , callable $read , callable $write , callable $destroy , callable $gc [, callable $create_sid [, callable $validate_sid [, callable $update_timestamp ]]] ) : bool
2.session_set_save_handler ( object $sessionhandler [, bool $register_shutdown = TRUE ] ) : bool
实践:
1.调用session_start()之后,就会执行open → read → write → close
2.write是PHP脚本执行完毕之后调用的,就是保存当前Session的数据
3.read就是相当于恢复Session数据,一次性读入到$_SESSION变量中
笔记:
read()函数返回的一个字符串,包含了session数据,其中有固定的格式:
age|i:18;name|s:5:"Jerry";
age和name是两个session变量,通过$_SESSION["age"]和$_SESSION["name"]访问。
write()函数的第二个参数,就是上面格式的字符串,包含了所有session数据,自己按照需要存储session数据。
例子:
<?php //ini_set("session.save_handler", "user"); class FileSessionHandler { private $savePath; function open($savePath, $sessionName) { echo __FUNCTION__."<br>"; return true; } function close() { echo __FUNCTION__."<br>"; return true; } function read($id) { echo __FUNCTION__."<br>"; return ""; } function write($id, $data) { echo __FUNCTION__."<br>"; return true; } function destroy($id) { echo __FUNCTION__."<br>"; return true; } function gc($maxlifetime) { echo __FUNCTION__."<br>"; return true; } function end(){ echo '脚本执行结束'."<br>"; } } $handler = new FileSessionHandler(); session_set_save_handler( array($handler, 'open'), array($handler, 'close'), array($handler, 'read'), array($handler, 'write'), array($handler, 'destroy'), array($handler, 'gc') ); // 下面这行代码可以防止使用对象作为会话保存管理器时可能引发的非预期行为 register_shutdown_function(array($handler, "end")); session_start();