Last Updated: September 09, 2019
·
4.114K
· tschuermans

PHP session locking

By default, PHP stores session data in a file (usually stored in /tmp, depending on OS).
This file gets a lock when PHP starts a session to prevent other processes altering the data and thus preventing race conditions.

This behaviour doesn't cause any problems in most situations, except when async processing is involved.
When you fire an async call to the server (e.g. ajax from jquery client-side), the server locks the session file to allow writing of session data. There's only one problem with this approach, if you have an async call which takes a long time to process you slow down other calls to the server because they have to wait until the request finishes to remove the lock on the session file.

You can easily solve this by using session_write_close() after you're done writing session data.
This makes sure the session data is written to the session file and the lock is removed.