PHP默认的会话处理器是session.save_handler = files(即文件)。如果同一个客户端同时并发发送多个请求(如ajax在页面同时发送多个请求),且脚本执行时间较长,就会导致session文件阻塞,影响性能。因为对于每个请求,PHP执行session_start(),就会取得文件独占锁,只有在该请求处理结束后,才会释放独占锁。这样,同时多个请求就会引起阻塞。解决方案如下:
(1)修改会话变量后,立即使用session_write_close()来保存会话数据并释放文件锁。
//author http://www.lai18.com session_start(); $_SESSION['test'] = 'test';session_write_close(); //do something
(2)利用session_set_save_handler()函数是实现自定义会话处理。
//author http://www.lai18.comfunction open($savePath, $sessionName){ echo 'open is called'; return true;} function close(){ echo 'close is called'; return true;} function read($sessionId){ echo 'read is called'; return '';} function write($sessionId, $data){ echo 'write is called'; return true;} function destroy($sessionId){ echo 'destroy is called'; return true;} function gc($lifetime){ echo 'gc is called'; return true;} session_set_save_handler("open", "close", "read", "write", "destroy", "gc");register_shutdown_function ( 'session_write_close' ); session_start(); $_SESSION['foo'] = "bar";
当然,在 php 5.4.0之后,你可以通过实现 SessionHandlerInterface 接口或继承 SessionHandler 类来使用。
//author http://www.lai18.comhtml' target='_blank'>class MySessionHandler extends SessionHandler { public function __construct() { } public function open($save_path, $session_id) { } public function close() { } public function create_sid() { } public function read($id) { } public function write($id, $data) { } public function destroy($id) { }} $handler = new MySessionHandler(); //第2个参数将函数 session_write_close() 注册为 register_shutdown_function() 函数。session_set_save_handler($handler, true);
转载请注明: http://blog.csdn.net/hello_katty
PHP编程郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。
新闻热点
疑难解答