Solved

PHP Session expire/close detection

Posted on 2006-10-29
11
9,338 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
11 Comments
 
LVL 17

Expert Comment

by:HuyBD
ID: 17831964
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
ID: 17831971
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
ID: 17831975
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 6

Expert Comment

by:soapergem
ID: 17832123
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
 
LVL 19

Expert Comment

by:VoteyDisciple
ID: 17832912
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
ID: 17833415
> 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
ID: 18057887
I think there should be a split between soapergem and myself
0
 
LVL 6

Expert Comment

by:soapergem
ID: 18058131
I agree.
0

Featured Post

Enroll in June's Course of the Month

June's Course of the Month is now available! Every 10 seconds, a consumer gets hit with ransomware. Refresh your knowledge of ransomware best practices by enrolling in this month's complimentary course for Premium Members, Team Accounts, and Qualified Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
This article discusses four methods for overlaying images in a container on a web page
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.

707 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