PHP自带Session隐患(session文件独占锁引起阻塞)
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.com function 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.com 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);
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: thinkphp5 系统登录的实现
- 下一篇: C/C++二进制读写png文件