By no means do I consider myself a PHP expert, but I have been using it for quite a few years to build various websites.
If you are doing any websites with a login, you probably need to use PHP sessions to keep track of the user’s login status, preferences or who knows what.
Anytime I need to track a session, I toss this into the PHP code:
That initiates user session tracking in PHP. Looks OK to me, been working great for years.
This past week I was developing some PHP/SQL scripts that take a long time to run. It was like if I was running the script, the website would not respond in another browser window.
I assumed the problem was related to mySQL, assumed there was a lock on the database until the first request was done.
After a couple of hours of researching I determined it was not mySQL, or my framework…
So I started from the ground up, the hello world code. That works, I can hammer it hundreds of times per second and there was no performance problem.
Yet running that single script that took maybe 30 seconds to run would bring the site down, no other page would respond.
Finally adding code back into my test environment I found it. session_start()
The default session handler drops the session information to disk. To prevent corruption the same user (same session) can’t access the same session data. Essentially meaning that PHP becomes single threaded on a per user basis. Normally this is not an issue for a couple of reasons 1) webpages are normally very quick 2) users don’t often execute many pages on the same site at the same time.
In my case the script tooks a considerable amount of time, I was unable to get results from a second page. To get around this problem you could use a different session handler (like storing sessions in Memcache).
Another way to fix it, do not leave the session open all day. When you need the session, open the session, access your variable and close it.
Now other threads that may be called by the same user don’t get hung up waiting until the first script ends. PHP will automatically close the session and release the lock when the script ends…. but don’t wait. Close it with session_write_close(); when you are done with it.