Releasing session locks in PHP.

The other day, I was working on a sluggish PHP web application that uses multiple frames and Ajax requests. If you opened one frame, two or three more frames were loaded. From what I can tell, this application was built before Ajax requests became popular.


If you have ever used a web application that uses multiple frames or Ajax requests, then you will know that PHP’s session locking mechanism can slow down their response times. This is especially true in applications that have a lot of database queries and / or processing going on.

This behavior occurs because the parent frame must finish processing before it releases the session lock. The PHP code inside the “child” frames will wait until all of the other session locks have been released before it executes.

Essentially, the frames will open one-by-one because they are all waiting in line to access the session data.


The session_write_close function allows us to tell PHP that we are done making any changes to the session data. By calling this function, we manually release the session lock and allow other scripts to access it.

In most cases, you will never need to use this function, as the session lock is automatically released as soon as the script in question is finished executing.

However, in cases where there are multiple parallel HTTP requests, you may need to call the session_write_close function so that your scripts can quickly access the session data and proceed.

Here is an example of the function being used:


//Start the session.

//Create / modify your session variables.
$_SESSION['test'] = 123;

//End the session.

//You can still access the session data
echo $_SESSION['test'];

As you can see, you can still read the session data after session_write_close has been called. However, you will not be able to create or modify session data.

Note that you will still be able to save data to the $_SESSION superglobal array. However, this data will not persist and it will not be present if you navigate to another page.



//Start the session.

//var_dump out our $_SESSION array.

//End the session.

//Try to create / modify our session data.
$_SESSION['example'] = "test";

echo $_SESSION['example'];

If you run the code above, you will notice two things:

  1. The $_SESSION superglobal array is always empty whenever the page is reloaded.
  2. We can still add values to the $_SESSION array.

Basically, we can add data to the $_SESSION array but that data is not being saved anywhere because session_write_close has been called.

Hopefully, you found this short guide to be somewhat useful!