0

I am programming a website that use jQuery's asynchrony to call php scripts. To avoid double script calling I would like to do two things:

  • disable the buttons that will trigger the script call, which I have successfully done
  • set a timer in the php script that is called that will check whether it was called by the same user less than one second ago, and if so, exits

First I thought this would be relatively easy, and came up with the following code:

if(!isset($_SESSION['time'])) $_SESSION['time']=time();
else if(time()-$_SESSION['time']<=1){
    //If less than one second ago, timer reset
    $_SESSION['time']=time();
    exit;
}

It works fine the first time, but then afterwards, when it should check again, of course a very old time has been saved in the session and is still in there, so the script can be called as often as the user wishes.

Do you have any ideas how to solve this? Thank you!

Charles

EDIT

My question could possibly be a duplicate of this - do you see any value in the second answer maybe?

SOLUTION FOUND

This is the solution:

if(!isset($_SESSION['time']) || ($_SESSION['time'] + 1 < time())){
    $_SESSION['time'] = time();
}else if(time()-$_SESSION['time']<=1){
    //Timer reset
    $_SESSION['time']=time();
    exit;
}
Community
  • 1
  • 1
Dennis Hackethal
  • 13,662
  • 12
  • 66
  • 115

2 Answers2

1

The simplest fix would be to overwrite the time value if it is set but is older than X seconds:

if(!isset($_SESSION['time']) || ($_SESSION['time'] + 30 < time())) {
    $_SESSION['time'] = time();
}

change the 30 value to the timeout you want.

Tim Fountain
  • 33,093
  • 5
  • 41
  • 69
  • Hi Tim, thanks so far! But that would also mean that in the course of these X seconds the user would be able to send as many requests to that script as he likes, am I right? – Dennis Hackethal Jul 02 '12 at 23:13
0

I'd probably attack the problem slightly differently and abort any AJAX calls that are no longer valid.

Say for example your user clicks your button twice somehow, then the second click can simply abort the ajax request of the first click.

Dealing with the problem at the client end will help keep the overheads on your server lower while making the client mop up any loose ends that the user is making.

This other question should help with the finer details of that.

Community
  • 1
  • 1
Rob Forrest
  • 7,329
  • 7
  • 52
  • 69