How can I stop PHP sleep() affecting my whole PHP code?

So, on my arcade, howlingdoggames.com. I have a points system that gives you a point every time you visit a page with a game on. To reduce abuse of this, I would like to make some sort of delay, so its only awarded after 45 seconds. Here's what I've tried:

if ($_SESSION['lastgame'] != $gameid) {
    sleep(45);
    $points = $points + $game_points;
    $_SESSION['lastgame'] = $gameid;
}

But this just seems to halt my whole website for 45 seconds, because this is in index.php, along with a lot of other code for my site.

Is there anyway I can isolate that bit of code, so it only makes the statement

$points = $points + $game_points;

wait for 45 seconds?


Solution 1:

There is (mostly) no multithreading in PHP. You can sort of do this with forking processes on Unix systems but that's irrelevant because multithreading isn't really what you're after. You just want simple logic like this:

$now = time();
session_start();
$last = $_SESSION['lastvisit'];
if (!isset($last) || $now - $last > 45) {
    $points = $_SESSION['points'] ?? 0;
    $_SESSION['points'] = $points + 10;
    $_SESSION['lastvisit'] = $now;
}

Basically only give the points if the increment between the last time you gave points is greater than 45 seconds.

Solution 2:

It is session block your script. not "There is no multithreading in PHP". session_write_close() before sleep() will solve block your whole script. but may not fit in your problem.

so you had to save the bonus using settimeout of js and AJAX.

from comment of sleep() in php.net: http://www.php.net/manual/en/function.sleep.php#96592

Notice that sleep() delays execution for the current session, not just the script. Consider the following sample, where two computers invoke the same script from a browser, which doesn't do anything but sleep.