Solved

PHP Session expire/close detection

Posted on 2006-10-29
11
9,331 Views
Last Modified: 2009-05-18
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.
0
Comment
Question by:micamedia
11 Comments
 
LVL 17

Expert Comment

by:HuyBD
Comment Utility
Try to use isset($_SESSION["order_id"]) to detect variable in session
if(!isset($_SESSION["order_id"]))
  do smt....
0
 
LVL 35

Expert Comment

by:Raynard7
Comment Utility
Hi,

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.
0
 
LVL 35

Accepted Solution

by:
Raynard7 earned 125 total points
Comment Utility
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?
0
 
LVL 6

Expert Comment

by:soapergem
Comment Utility
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:

    <head>
        ...
    <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();
        ro.open('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');
        ro.send(data);
        return;
    }
    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;
    }
   
    /* ]]> */
    </script>
    </head>

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.
0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
LVL 19

Expert Comment

by:VoteyDisciple
Comment Utility
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 (-:  ).
0
 
LVL 6

Assisted Solution

by:soapergem
soapergem earned 125 total points
Comment Utility
> 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.

> ...you'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.
0
 
LVL 35

Expert Comment

by:Raynard7
Comment Utility
I think there should be a split between soapergem and myself
0
 
LVL 6

Expert Comment

by:soapergem
Comment Utility
I agree.
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Consider the following scenario: You are working on a website and make something great - something that lets the server work with information submitted by your users. This could be anything, from a simple guestbook to a e-Money solution. But what…
These days socially coordinated efforts have turned into a critical requirement for enterprises.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now