Konr Ness Konr Ness
PHP Session Locks – How to Prevent Blocking Requests

Many people are aware that modern browsers limit the number of concurrent connections to a specific domain to between 4 or 6. This means that if your web page loads dozens of asset files (js, images, css) from the same domain they will be queued up to not exceed this limit. This same problem can happen, but even worse, when your page needs to make several requests to PHP scripts that use sessions.


PHP writes its session data to a file by default. When a request is made to a PHP script that starts the session (session_start()), this session file is locked. What this means is that if your web page makes numerous requests to PHP scripts, for instance, for loading content via Ajax, each request could be locking the session and preventing the other requests from completing.

The other requests will hang on session_start() until the session file is unlocked. This is especially bad if one of your Ajax requests is relatively long-running.


The session file remains locked until the script completes or the session is manually closed. To prevent multiple PHP requests (that need $_SESSION data) from blocking, you can start the session and then close the session. This will unlock the session file and allow the remaining requests to continue running, even before the initial request has completed.

To close the session, call:


This technique works great if you do not need to write to the session after your long-running process is complete. Fortunately, the $_SESSION data is still available to be read, but since the session is closed you may not write to it.


// start the session

// I can read/write to session
$_SESSION['latestRequestTime'] = time();

// close the session

// now do my long-running code.

// still able to read from session, but not write
$twitterId = $_SESSION['twitterId'];

// dang Twitter can be slow, good thing my other Ajax calls
// aren't waiting for this to complete
$twitterFeed = fetchTwitterFeed($twitterId);

echo json_encode($twitterFeed);

arrow52 Responses

  1. Steven
    53 mos, 3 wks ago

    Thanks I honestly in 7 years of PHP never knew this.

  2. 53 mos, 3 wks ago

    I just had one of those “ohhhhhhh” moments. I never understood what was causing pages to lock up and always wrote it off as being Apache. The session file makes so much sense.

  3. Glenda
    52 mos, 4 wks ago

    Thank you, I’ve been trying to figure this out for months since writing my own login system. It’s so simple, yet so helpful!

  4. vdklah
    52 mos, 1 wk ago

    It seems that calling start_session() followed by session_write_close(), each time the PHPSESSID is added to the cookie. Doing this -many- times, your client could crash due to -huge- cookies. I have posted this problem against your solution here: http://bugs.php.net/bug.php?id=38104

  5. Konr Ness
    52 mos, 1 wk ago

    @vdklah – There should be no reason to restart the session after closing it. The proper use-case for this technique would be to session_write_close() when you have no more data to write to the session. Also, I cannot think of a use-case where you’d need to open two different sessions in one request.

  6. vdklah
    52 mos, 1 wk ago

    We have multi-threaded client applications. One thread is requests an export service that keeps running for a few minutes. Another thread is polling for progress information in the meantime to draw a progress bar. Both are running within the same session. One is writing progress info while the other is reading. We need to start- and close the session quickly to avoid blocking each other.

  7. Konr Ness
    52 mos ago

    @vdklah – you should really consider using a non-locking session storage such as a database. Or not use the session for the progress indicator storage.

  8. vdklah
    52 mos ago

    Of-course I can do all the hard work myself and write my own session cache manager. But that would be just because PHP is totally letting me down. Surprisingly, because PHP is dedicated to web technology and so you may have high expectations on session management. Invoking a database to implement caching implies the need for -two- connections to serve -one- client, which is expensive and heavy. I rather use something feather light weighted. Nevertheless, I was already thinking moving away from PHP sessions since it does not support dispatching over multiple application servers. Maybe I’m gonna have a closer look at Memcache, but that complicates installation of our product since we support many DB- and OS flavors. Thanks for sharing your ideas though!

  9. henkka
    50 mos, 2 wks ago

    Can I write to the session in the middle of the long-running operation like this:



    // long-running operation begins

    // need to write to the session
    $_SESSION['variable'] = value;

    // long-running operation continues

  10. Ilian Andreev
    50 mos, 1 wk ago

    I was having the same problem for a FTP file download progress indicator and solved it with session_write_close(). However I was thinking if this session issue does really impose such a big impact on AJAX calls. Do we need to call session_write_close() everytime during AJAX calls when we are finished writing to the session?

  11. Ilian Andreev
    50 mos, 1 wk ago

    It’s because session_start() effectively makes all AJAX requests synchronous if you don’t explicitly close it ….

  12. eel
    49 mos, 2 wks ago


    Are Henkka’s usage of the session_start and session_write_close functions valid???

    henkka :
    Can I write to the session in the middle of the long-running operation like this:

    // long-running operation begins

    // need to write to the session
    $_SESSION['variable'] = value;
    // long-running operation continues

  13. eel
    49 mos, 2 wks ago

    I am trying to do the same thing as Henkka, and it seems to work okay… Is there anything wrong with this method?

  14. 48 mos, 3 wks ago

    Thank you so much.

    Actually I was facing this problem when I wanted to display % of uploading file on server. So uploading request was taking so much time .. and in between I wanted to get size of file through ajax request. In session I was updating file information
    ….but without session_write_close() function I was always getting old request file information in session !!! but this saved my day.

    Thank you so much


  15. 42 mos, 2 wks ago

    Thank you so much! you just saved me!!

  16. 41 mos ago

    Thanks so much. The main problem we were having is that if a long-running script is cancelled or fails for some reason, the session file seems to remain locked indefinitely, causing all pages to be completely inaccessible.

    Now going to do an audit of all session access in our site and close the session as early as possible.

  17. Roger Wyatt
    39 mos, 4 wks ago

    In all of my AJAX applications, I use a database session manager rather than the PHP version for a couple of reasons:
    1) Sending multiple, simultaneous requests use AJAX causes the sessions to lock (as documented here)
    2) If going through a bank of proxy servers (as happened at one client site) caused the session to bounce back and forth.

    It’s pretty simple to write a session class, store the appropriate info in the database and that way you avoid these issue altogether. It would be nice if PHP had a configuration option for session.ajax that we could turn on so it wouldn’t file-lock the session.

    My current project has 40 or so simultaneous ajax requests going out, and while I know the browser parks the bulk, removing the reliance on the phpsession keeps things flowing.

  18. Konr Ness
    39 mos, 4 wks ago

    How does your database session manager handle locking? Does it have any precautions for concurrent writes overwriting each other?

    You may think that database sessions solve the locking problem, but it introduces an even more significant problem. Session locking is actually a feature to prevent concurrent overwrites of session contents. For example, say you have two concurrent requests, each that modify different parts of the session data. If any time passes between reading the session data and writing the modifications you could overwrite a concurrent update.

    I still maintain that closing the session for writing when you don’t need to write to it is the best solution since session locking can prevent some pretty major unintended consequences. Match that with only starting the session when you actually need it and PHP’s default file-based sessions is fail-proof.

  19. 38 mos, 4 wks ago

    Uff, I was not aware of such SESSION behaviour even after 10+ yrs of PHP experience… very nice, thanx!

  20. 38 mos, 2 wks ago

    nice code..

  21. Yihad
    37 mos, 2 wks ago

    I love you and I wanna make you love.

    Not really ^_^ but thanks from the deep of my heart

  22. David
    37 mos ago

    thx a lot. That solved my blocking problems :)

  23. libert
    36 mos ago

    i faced this problem with a comet implementation and your post was helpfull ! thank you :D

  24. lexxsoft
    35 mos ago

    This was really helpful. I am making low latency web application with some heavily blocking pages and couldn’t figure out what was causing it to block other pages much. I thought I might need to check all database interactions and transactions and whatnot, but the problem it seems was a thing you take for granted and never bother to think how it really works.. This info really should be posted on related php.net page. THANKS.

  25. 33 mos ago

    Just wanted to say this saved me a whole headache of frustration!

    I had a download.php?fileid=### to dump binary of a file. I required access to the session variables but not writing them.

  26. Wim
    30 mos, 3 wks ago

    You’re a lifesaver! Or at least a braincell saver, I burned too many of them trying to figure out what the hell was happening with my webapp slowing down to slug pace

    Thank you!

  27. 30 mos ago

    Thank You!
    Great and simple solution for a maddening problem

  28. Kalai Selvan
    27 mos, 1 wk ago

    Thanks !!!. Helped me a lot

  29. 25 mos, 3 wks ago

    Presenting hilarious conversation and graphics, might-ups, and
    dozens of entertaining shape chains of duplicate
    symbols to creation by invading and subjugating China, narrowly averting a time paradox.
    some examples of mobster Game are such can be played on your computing device.

    They Feature dent tickets where you can but what can you
    Require with the downright total of Release game to be played?

    With more than bloon types and more than levels to they oft get into the stocky of things themselves, but all heroes have several powerful ability options.

  30. Vir
    25 mos, 2 wks ago

    Nice article. Thank you so much !!!

  31. OJ
    25 mos, 1 wk ago

    Thank you very much !!!!!

  32. szaman
    22 mos, 1 wk ago

    it help me so much!

  33. ruio
    21 mos, 4 wks ago

    Thanks, a very useful tip :)

  34. Daniel Nilsson
    19 mos, 1 wk ago

    I am writing load balanced FastCGI interface for a Twisted driven webserver. And this has haunted me for 2 days now. I could not understand how multiple requests would queue up execution when they were sent to multiple fast-cgi process instances of PHP. When I finally realized issue exist on IIS and Apache as well I looked elsewere, then I saw that requests that would have different session cookies did not queue and the issue were not in my code in the first place.

    Googled and found this.. Makes perfect sense and allows me to complete my work, GREAT THANKS!!! :)

  35. Great weblog here! Also your web site a lot up very
    fast! What host are you the use of? Can I get your
    associate link for your host? I want my web site loaded up as fast as yours lol

  36. ocoder
    18 mos, 4 wks ago

    I love you man, thanks a lot !

  37. I visit day-to-day some web pages and sites to read content,
    however this web site presents quality based posts.

  38. 15 mos, 3 wks ago

    My developer is trying to convince me to move to .net from PHP.
    I hqve always disliked tthe idea becase of the costs.
    But he’s tryiong none the less. I’ve been using WordPress oon various websites for about a
    year and am anxious about switching tto anothger platform.
    I have heard very good things about blogengine.net.
    Is there a way I can transfer all my wordpress content into it?
    Any help would be really appreciated!

  39. romli
    14 mos, 2 wks ago

    cool thanks…

  40. Eugen
    13 mos, 3 wks ago

    I wrote a WP plugin that has a long running script (like 5min).
    The whole blog was blocked until the script has finished its work. Thanks to your post now everything works like a charm.
    Thanks for sharing.

  41. 13 mos, 2 wks ago

    Even years later this post proves to be incredibly helpful! I hadn’t run into this issue before but this post just saved us a ton of time.

  42. Alex
    13 mos, 1 wk ago


  43. Fer
    11 mos, 2 wks ago

    Thanks manymuch, but I dont know why the code is not working for me:
    I have a page with:

    $_SESSION['latestRequestTime'] = time();
    echo sprintf(“Start Time: %.2f seconds\n”, microtime(true));

    If I call it from two browser tabs, the second one waits 20 seconds (so not in parallel) Am I missing something? php configuration maybe?

  44. 11 mos, 1 wk ago

    If PHP is not handling requests asynchronously even after calling session_write_close, it may just be xdebug.

  45. Johnb704
    11 mos ago

    You are my inspiration , I have few web logs and very sporadically run out from to brand. gdecdcdbdgba

  46. 9 mos, 4 wks ago

    This solved a problem with long running background processes hanging the browser on ajax calls. Good information that saved some grief on my project.

  47. 8 mos, 2 wks ago

    PADI IDC courses are globally recognized; and a ten day plus IDC course
    will certainly put you on the right track to becoming a PADI Open Water Scuba Instructor (OWSI).
    Right after learning the fundamental principles associated with scuba dving, students can immerse themselves to successfully at the most e with a licensed scuba diver.

    The carp is a fish species surrounded in myth, legend, and

  48. 5 mos, 3 wks ago

    Thanks for the post, made an issue i have with opencart finally clear to me!

  49. Tariq Mahmood
    5 mos, 3 wks ago

    I spent almost 8 hours to investigate why my AJAX calls are not working as they were supposed to work and finally this article came to my way. Thank you so much for explaining

  50. shuai
    3 mos, 4 wks ago

    Thanks a lot ,before reading this article ,I had never known that php session will cause a lock

  51. 2 mos, 1 wk ago

    Ryokan-sama had lived a size able part of his life as a hermit, although he was mostly remembered in certain circles for his calligraphy skills,
    and of course poetry, which according to those
    who knew much better than my limited knowledge of the man, presented the
    essence of Zen life. If you want, you can have a talk with some
    of their ex-students to know about the quality
    of their service. It has been observed that the driving training institutes in Galway have done excellent work in securing customer’s confidence and channelizing their
    efforts towards effective driving program.

  52. 1 mo, 3 wks ago

    Fantastic blog! Do you have any tips and hints for aspiring writers?
    I’m planning to start my own site soon but I’m a little lost on everything.
    Would you suggest starting with a free platform like WordPress or go for a paid option? There are so many options
    out there that I’m completely confused .. Any tips? Thanks!

Leave A Comment