PHP自带Session隐患(session文件独占锁引起阻塞)

WBOY
Release: 2016-06-23 13:37:09
Original
841 people have browsed it

PHP自带Session隐患(session文件独占锁引起阻塞)

PHP默认的会话处理器是session.save_handler = files(即文件)。如果同一个客户端同时并发发送多个请求(如ajax在页面同时发送多个请求),且脚本执行时间较长,就会导致session文件阻塞,影响性能。因为对于每个请求,PHP执行session_start(),就会取得文件独占锁,只有在该请求处理结束后,才会释放独占锁。这样,同时多个请求就会引起阻塞。解决方案如下:

(1)修改会话变量后,立即使用session_write_close()来保存会话数据并释放文件锁。

[php] view plaincopy

session_start();  

   

$_SESSION['test'] = 'test';  

session_write_close();  

   

//do something  



(2)利用session_set_save_handler()函数是实现自定义会话处理。

[php] view plaincopy

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 类来使用。

[php] view plaincopy

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);  



你可以对上面的代码进行具体实现和封装,利用mysql或其它内存数据库来管理会话数据。还能解决使用集群时,session数据共享问题。



参考来源: 
PHP自带Session隐患(session文件独占锁引起阻塞)
http://www.lai18.com/content/407206.html

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!