PHP Session expire/close detection

I need a way to detect session close/expire and run a task when this happens. Here's the the situation:

I have a custom shopping cart. When people add x of an item to the cart, the system "locks" x items. Meaning it takes them temporarly from the inventory. After 20 min or inactivity it will unlock the items. Each time the cart loads it will attempt to relock the items reseting the time.

This all works perfectly. My problem is this:

Say someone puts 10 items in the cart. 10 items are locked. Now the user closes the browser. The cart session goes away, but the 10 items are still locked. They will remain locked for 20 min.  I would like to just remove the locks when this happens. But i don't know how to detect this.

I need a way to be able to tell when my $_SESSION["order_id"]  is closed or expired. And when it does it gets even more complex. In order to remove the locks, i need to know what the order_id was.

So in summary, i need to know when $_SESSION["order_id"] goes away, and what it was so i can then delete the locks associated with the order.

Of course if you have another idea of how to do this, i'm all ears.
Who is Participating?
Sorry - I'm confused - so the user keeps their browser open - does not do anything for 20 min and then you want to keep track of what they had reserved beforehand.

Well - all I'd do is have a $_SESSION["lastActivityTime"] which is equal to the system time on each page.

I'd then say - if this is > 20 min ago then re-reserve the items.

Additionally - if you are locking these records in the database - surley you would have a list of orders that were selected, the session id - the user and the time - and then another record if they were purchased.

how is your database working?
Try to use isset($_SESSION["order_id"]) to detect variable in session
  do smt....

You can not tell when the session goes away - without them logging out the session is still open on the web server.  Which is why you wait 20min because there is no difference to the server if they are active or not.

If they close the browser you can not tell.  You potentially could build something in ajax that is constantly sending messages back to your server - a keep alive if you will, then have something on your back end to clean up everything that has not sent a keep alive for a certain period.  But I'm not sure how reliable that would be.
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

My best recommendation to you is to use AJAX (Asynchronous JavaScript and XML) to send a quick signal to your server when the user closes their browser or leaves your web page. Under normal circumstances, your server has no idea whether or not the user is still looking at your website. That's because PHP is a server-side language and not a client-side language: it executes all of its code, sends everything to the browser, and then it's done.

By using a client-side language like JavaScript, you can trigger certain events (such as sending a signal to your server) the instant certain events happen, such as the client closing his or her web browser, or navigating away to another page. To do this, you will need a couple of things. First, you'll have to create a PHP script to receive and process this "signal" that will be sent, and second you'll need JavaScript code to actually send this signal.

The JS part would look something like this:

    <script type="text/javascript">
    /* <![CDATA[ */
    //  use PHP to output the value here
    var user_id = 12;
    //  this tells it to send this request when the browser closes
    //  or when the user navigates away to a different page
    window.onunload = do_logoff;
    function do_logoff()
        var ro = createRequestObject();'post', '/path/to/signal.php');
        var data = 'user_id=' + encodeURIComponent(user_id);
        ro.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        ro.setRequestHeader('Content-length', data.length);
        ro.setRequestHeader('Connection', 'close');
    function createRequestObject()
        if ( window.XMLHttpRequest ) {
            try { var ro = new XMLHttpRequest(); }
            catch(e) { var ro = null; }
        else if ( window.ActiveXObject ) {
            try { var ro = new ActiveXObject('Msxml2.XMLHTTP'); }
            catch(e) {
                try { var ro = new ActiveXObject('Microsoft.XMLHTTP'); }
                catch(e) { var ro = null; }
        return ro;
    /* ]]> */

In that particular example I made, a request would be sent to /path/to/signal.php, and the $_POST['user_id'] would have a value of 12. It's not totally reliable, since it only works when users have JavaScript enabled, and are using a modern browser that supports AJAX, but it's probably safe to say that at least 95% of all internet users fit into that category. I hope my answer didn't confuse you *too* thoroughly, but in any case it would probably work.

Also, all of the $_SESSION data would still be present in the PHP page at the time the signal is sent (assuming it's sent before that 20 minute mark). You would want to not only check the $_POST data, but *also* verify the $_SESSION data, because without doing so it would be a security risk.
The basic problem is that, by the nature of walking away from the browser, the user is no longer interacting with your site, so you can't expect THAT user to invoke any PHP code at all.  You can trick 'em into it with JavaScript, but I wouldn't bank on that.

I'd prefer to keep a list of (order_id INT, last_active TIMESTAMP, PRIMARY KEY (order_id)) in the database, so you've got your own separate copy of what's been open, and how long.

Then when OTHER users access the site, you've got an easy mechanism to detect orders that haven't been active for a while, and at that time can release items back to inventory.  It adds processing to each page load, but potentially not that much, and there's no risk of it failing (well, there's no risk of it failing in a way databases and PHP pages can't usually fail (-:  ).
> You can trick 'em into it with JavaScript, but I wouldn't bank on that.

No, it's never good to rely on JavaScript (an example of which is the solution I posted), but it's still worth a shot. The vast majority of internet users have no idea what JavaScript is, and have it turned on (by default), and even among experienced users, very few would have it disabled. JavaScript is one of the only mechanisms we have to see when a user quits their browser, since by definition as a server-side language, PHP (and likewise ASP.NET or any other server-side script) has no way of knowing exactly when a user closes their browser. In PHP, we can only make estimates and guesses.

>'ve got an easy mechanism to detect orders that haven't been active for a while...

Detecting orders that "haven't been active" is ultimately guesswork. You're assuming that because it's been 10 minutes, that the user gave up and left, when in fact we have no way of knowing if they're still looking at the page and they're just slow. micamedia already has a 20 minute time-out set in his existing system--but it sounded like he was looking for something more. I still contend that the AJAX solution is better than nothing, realizing that it has its flaws.
I think there should be a split between soapergem and myself
I agree.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.