PHP使用session_set_save_handler陷阱
陷阱如下
当脚本使用了session_set_save_handler 来重定向 session后,使用session_destroy后再使用session_start()重新开启session会报错
代码如下,
<?php function open() { echo 'session start'; echo "\n"; } function close() { echo 'session close'; echo "\n"; } function read($sessionId) { echo 'read'.$sessionId; echo "\n"; } function write($sessionId, $data) { echo 'write'.$sessionId.$data; echo "\n"; } function destroy($sessionId) { echo 'destroy '.$sessionId; echo "\n"; } function gc($lifetime) { echo 'gcccc'; echo "\n"; } session_set_save_handler('open', 'close', 'read', 'write', 'destroy', 'gc'); session_start(); echo session_id(); echo "\n"; session_destroy(); session_start(); $id = 'h06vgdfdfve6b8f66sva6basf8'; session_id($id); echo session_id();
运行后报错
1 Fatal error: session_start() [<a href='function.session-start'>function.session-start</a>]: Failed to initialize storage module: user (path: /var/lib/php/session) in /home/user/site/session.php on line 39
屏蔽session_set_save_handler('open', 'close', 'read', 'write', 'destroy', 'gc');
正常流程下(使用原生session)错误不会再出现。
so..
如果网站要使用自定义session建议自己封装和直接使用相关函数, 绕开session_set_save_handler