The power of session_write_close()

If you’re anything like me, you’ve probably created an infinite loop or two in your day. One misconception that I had however, was that a single script that entered an infinite loop was causing my entire server to get locked up, because I couldn’t reload the page or load any other page. I always just restarted my web server (Doh!)

Recently, I learned that the cause for this behaviour was completely different then what I thought. PHP employs session locking, so if you have a script that uses sessions, only one script can run at a time for a single user, since that script locks the session file and the other script has to wait for the file to be unlocked. This is another reason why I experience slow loading times when I utilize PHP scripts to load images or other files.

This problem can be solved however. Once you are past the point in your application in which you need to modify the session, you can call the function session_write_close(). This frees up the session file for the next script, and is an invaluable function once you know about it.

4 Replies to “The power of session_write_close()”

  1. Here’s my code:

    ob_end_clean();
    var_dump( ob_get_level() );
    session_write_close();
    sleep( 5 );
    die( ‘Done’ );

  2. Hi,

    I was just researching this and on my laptop I found that if I run this script in two tabs the first one finishes in five seconds but the second one finishes five seconds after the first one finishes. I would have expected that if I loaded them at T+0 seconds and T+1 seconds then the tabs would finish at T+5 and T+6 seconds. Apparently not.

    I suspected output buffering but closing the output buffer (which was open for some reason) still made no difference.

    Any ideas?

  3. Very Handy thanks

    – Bob

    1. Glad you found it useful

Leave a Reply