Session Locking

suggest change

As we all are aware that PHP writes session data into a file at server side. When a request is made to php script which starts the session via session_start(), PHP locks this session file resulting to block/wait other incoming requests for same session_id to complete, because of which the other requests will get stuck on session_start() until or unless the session file locked is not released

The session file remains locked until the script is completed or session is manually closed. To avoid this situation i.e. to prevent multiple requests getting blocked, we can start the session and close the session which will release the lock from session file and allow to continue the remaining requests.

// php < 7.0 
// start session 
session_start();

// write data to session
$_SESSION['id'] = 123; // session file is locked, so other requests are blocked

// close the session, release lock
session_write_close();

Now one will think if session is closed how we will read the session values, beautify even after session is closed, session is still available. So, we can still read the session data.

echo $_SESSION['id'];    // will output  123

In php >= 7.0, we can have read_only session, read_write session and lazy_write session, so it may not required to use session_write_close()

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents