PHP comes with a session hidden Danger (session file exclusive lock causes blocking)
PHP Default Session processor is Session.save_handler = files (that is, file). If the same client concurrently sends multiple requests (such as Ajax sending multiple requests at the same time on the page), and the script executes longer, it can cause the session file to block and affect performance. Because PHP executes session_start () for each request, the file exclusive lock is taken, and the exclusive lock is released only after the request processing has ended. In this way, multiple requests can cause blocking at the same time. The solution is as follows:
(1) After modifying the session variable, use Session_write_close () immediately to save the session data and release the file lock.
[PHP]View Plaincopy
- Session_Start ();
- $_session[' Test ' = ' test ';
- Session_write_close ();
- Do something
(2) using the Session_set_save_handler () function is the implementation of 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 ();
- The 2nd parameter registers the function Session_write_close () as a register_shutdown_function () function.
- Session_set_save_handler ($handler, true);
You can implement and encapsulate the code above, using MySQL or other in-memory databases to manage session data. It can also solve the problem of session data sharing when using cluster.
Reference Source:
PHP comes with a session hidden Danger (session file exclusive lock causes blocking)
Http://www.lai18.com/content/407206.html
PHP comes with a session hidden Danger (session file exclusive lock causes blocking)