Session locking: Non-blocking read-only sessions in PHP

I ran into an excellent article titled PHP Session Locks – How to Prevent Blocking Requests and it inspired me. Judging by the comments, it seems that not everybody fully understands what session locking is, how it works, and why it is necessary. This post tries to clear these things up and also gives you a dirty way of speeding up your AJAX calls significantly.

What session locking is

To understand this, we first need to know that a web server does not run your PHP code in a single process. Multiple worker processes are running concurrently and they are all handling requests. Normally, visitor requests of your web page are serialized. This is also where HTTP persistent connections (a.k.a. keep-alives) come into play. By keeping the connection open for the requesting of all the assets of the page, the connection overhead is avoided. Browsers are quite smart and will always try to serialize requests for HTML pages. For the assets (images, scripts, etc.) on the page there is another strategy. The browser will download multiple assets in parallel from each unique hostname it sees referred in the HTML. It can do this by opening multiple TCP connections or by pipelining. When a browser thinks it is downloading assets it may download these for a single visitor in parallel. Session locking avoids this parallelism (by blocking) to provide reliable access to the session data in this situation.

How session locking works

This is quite easy: When you call “session_start()” PHP will block (wait) in this call until the previous script has called “session_write_close()”. On Linux it does this by relying on the “flock()” call. This is an advisory locking mechanism that blocks until the lock is released. NB: This locking time is not counted as part of the “max_execution_time” (see: set_time_limit()).

Why session locking is necessary

Session locking prevents race conditions on the shared memory that is used to store session data. Every PHP process reads the entire session storage when starting and writes it back when closing. This means that to reliably store the logging-in of a user (which is typically done in the session data) you must make sure no other process has read the session data and will overwrite your data after you have written it (since the last write wins). This is needed even more when using AJAX or IFrames since the browser considers those loads to be assets and not HTML pages (so they will be parallelized).

Read-only sessions to the rescue

Many websites use AJAX calls to load data. While retrieving this data we would like to know whether the user logged in to deny access if  needed. Moreover, we would not like the loading of this AJAX data to be serialized by the session locking, which slows down the website. This is where the following (arguably dirty) code comes into place. It will allow you to gain read-only access to the session data (call it instead of “session_start()”). This way you can check permissions in your AJAX call, but without locking, thus not blocking and serializing the requests. It may speed up your PHP powered AJAX website significantly!

            function session_readonly()
            {
                    $session_name = preg_replace('/[^\da-z]/i', '', $_COOKIE[session_name()]);
                    $session_data = file_get_contents(session_save_path().'/sess_'.$session_name);

                    $return_data = array();
                    $offset = 0;
                    while ($offset < strlen($session_data)) {
                        if (!strstr(substr($session_data, $offset), "|")) break;
                        $pos = strpos($session_data, "|", $offset);
                        $num = $pos - $offset;
                        $varname = substr($session_data, $offset, $num);
                        $offset += $num + 1;
                        $data = unserialize(substr($session_data, $offset));
                        $return_data[$varname] = $data;
                        $offset += strlen(serialize($data));
                    }
                    $_SESSION = $return_data;
            }

I think this call should be added to the next PHP version. What do you think? Let me know in the comments.

Share

Loading remote data into bootstrap tabs

Many people are using Bootstrap for their website layout nowadays, and we all know that Bootstrap comes with quite a few handy JavaScript tools out-of-the-box. One of those tools is Bootstrap tabs, which lets you quickly create tabs to make your site more accessible. One feature, however, is missing from tabs, which would enhance the user experience even more: loading remote data with Ajax. Let us say you have a page that loads slowly because it is generating some statistics for a user. If you render it in tabs using the default construction, you might end up with a slow landing page.

The user might not always want to view his statistics, and it is extremely inconvenient for a user to open a completely new page just to see a few statistics.
This is where the Bootstrap remote tabs plugin comes in, this easy-to-use and lightweight (only 1.7kb) plugin will allow you to set an external source quickly in your existing tab configuration:

<!-- Nav tabs -->
 <ul>
 <li class="active"><a href="#home">Dashboard</a></li>
 <li><a href="#stats">Statistics</a></li>
 </ul>

<!-- Tab panes -->
 <div>
 <div id="home">
 <p>User dasboard<p>
 </div>
 <div id="stats"></div>
 </div>

The plugin reads the data-tab URL setting inside the ‘anchor’ tag of the tab link. No further configuration is required,
although the plugin allows for several other configuration options described in the README file.

So, how does this plugin accomplish what it does? First, it iterates over all the tab components it finds:

$('[data-toggle=tab]').each(function(k, tab) {
	// rest of code here
}

So, now we have the tab component itself. The next step is to a possible remote data url from the tab.

url = tabObj.attr('data-tab-url');
tabDiv = $(tabObj.attr('href'));
// also retrieve other settings

So now we need to listen to an event to trigger the retrieval of the remote data. In the case of the tabs it’s the show event we want to listen for:

var tabEvent = ‘bs-show’; //listen to the show event of bootstrap v3 tabs
tabObj.on(tabEvent, function(e) {
	// call execute request
}

Now we can do a Ajax call to retrieve data from the URL previously passed to the tab, and inject that content into the container that the tab is connected to.

$.ajax({
            url: url,
            success: function(data) {
                if (data) {
                   // don’t load the data more than once until it’s finished
                   if(!trigger.hasClass("loaded")) {
                      trigger.addClass("loaded");
                   }
                    tabContainer.html(data);
                }
            },
            fail: function(data) {
                // the call failed
            }
        });

The code above does a simple jQuery Ajax request, retrieves the remote content and injects it into the tab container. The actual script does a little bit more than that, but those are only applicable to the expanded feature set. This basic example gets the job done for the basic functionality of this plugin.

You can view a live demo here: http://leaseweb.github.io/bootstrap-tabs-demo/ or clone the repo and try it out for yourself: https://github.com/LeaseWeb/bootstrap-remote-tabs

Share