Fix for apache serving multiple php pages during a long running php script

PROBLEM

Sometimes if you have a long running PHP script in your browser, you will find that if you browse the other pages of the same website, they dont show up till the script finishes running.

For eg.if you are running a page which fetches a large amount of data from another website, and while its running , you try to open the homepage. Most likely you will find that it wont show up till the other page finishes running.

A lot of people would wonder that since Apache is multi-threaded why is one request blocking up all the other requests. As you will see this is not to do with threads at all.

This happens when you are using sessions. If a php file has session_start() enabled then what Apache does is that it locks the session file to prevent other php pages from writing into it while this php page is still running. Allowing that to happen would cause the session file to go corrupt.

So what happens is that  multiple requests from the same session id will not be executed concurrently. Rather they will be queued and will run in serial fashion.

SOLUTION

Since this is caused due to the enabling of sessions in the long running page, simply turn off sessions for that page. Use session_write_close() before you send any output or execute any code. This will tell Apache that there is no need to lock the session file and you will be able to easily execute other pages while your long-running script is executing.

2 Comments

  1. Thank you for your useful article! I had some troubles with a cURL application I was writing in PHP. Using session_write_close() right before curl_exec() drastically increased its performance and responsiveness.

Leave a Reply

Your email address will not be published.


*