PHP built-in Session risks (blocking caused by session file exclusive lock)
The default session processor of PHP is session. save_handler = files ). If the same client sends multiple requests concurrently (for example, ajax sends multiple requests simultaneously on the page) and the script execution takes a long time, the session file will be blocked and the performance will be affected. For each request, PHP executes session_start () to obtain the exclusive file lock. the exclusive lock is released only after the request is processed. In this way, multiple requests at the same time will cause blocking. The solution is as follows:
(1) after modifying the session variable, use session_write_close () to save the session data and release the filelock.
[Php]View plaincopy
Session_start ();
$ _ SESSION ['test'] = 'test ';
Session_write_close ();
// Do something
(2) use the session_set_save_handler () function to implement custom session processing.
[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 ";
Of course, after php 5.4.0, you can use it by implementing the SessionHandlerInterface interface or inheriting the SessionHandler class.
[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 ();
// Register the session_write_close () function as the register_shutdown_function () function with the 2nd parameters.
Session_set_save_handler ($ handler, true );
You can implement and encapsulate the above code and use mysql or other memory databases to manage session data. It also solves the problem of session data sharing when using clusters.
Reference Source:
PHP built-in Session risks (blocking caused by session file exclusive lock)
Http://www.lai18.com/content/407206.html