Implement Non-Blocking Session in PHP

As we all know Session is the most important component in the web application. Before describing the non-blocking session, I would like too little introduce about PHP Session. The session is the way to store data for each user against a unique session ID. By default, session usages file to storing the session data. When session_start() is called then PHP creates a unique identifier number for that particular session. And sent that number to users browser to save that number. Contiguous create a new file with the same name of the unique identification number. And browser will use that unique identification number to communicate with that server. To know more about How Does PHP Session Works read this article.

Non-Blocking Session

What Does Session Locking:

When web server getting the concurrent request which involves with PHP Session. Then the first request will engage the Session file to work with it and locked that Session file. And rest of the request who also have to engage with Session, they will be blocked (waiting for the unlock of the Session file). When the first request did its activities then release the Session file and then the second request will engage with The session. And this happened until the last request is served. This is actually called Session Looking. To understand more about Session Locking read this article.

Non-Blocking Session:

To improve the application performance we need to avoid this problem. To avoid the PHP Session blocking we can start the session and then close the session. This will unlock the session file and allow the remaining requests to engage with Session, even before the previous request has served.

session_write_close(); function need to call to close the session.

This trick works great if you do not need to read anything in session while your another process is engaged with the session. With this technique, you still able to read the $_SESSION data while the session is engaged with another request.

Example Script:

// start the session
session_start();
// read/write to session
$_SESSION['login_time'] = time();
// close the session
session_write_close();
// now do my long-running code.
// still able to read from session, but not write
$twitterId = $_SESSION['userId'];

Published by

Sohel Rana

PHP Programmer, Software Engineer & Technology lover

Leave a Reply

Your email address will not be published. Required fields are marked *