I want to prevent users (different clients) from posting data at the "same" time, I need them to wait n seconds after the last POST. Would some sort of server-side delay achieve this?
How does a PHP server attend clients? Is it one by one or at the same time?
You can store a timestamp in the session, plant a cookie, or store a timestamp in a database.
Session is probably the easiest, fastest and least invasive.
// 3600 seconds is 1 hour.
if ($_SESSION['last_post'] < time() + 3600)
{
//cannot post
return false;
}
// post comment.
$_SESSION['last_post'] = time();
return true
To apply to all users as a global effect use an apc cache entry or a database flag.
// 3600 seconds is 1 hour.
if (apc_fetch('comment_timeout' < time() + 3600)
{
//cannot post
return false;
}
// post comment.
apc_add('comment_timeout' , time());
return true
session_start();
if ((time() - $_SESSION['last_post_time']) < 60)
{
// user posted within 60 seconds
}
else
{
//process data as normal
// reset last post time
$_SESSION['last_post_time'] = time();
}
However, a user could get around this by closing down their browser, so are you using a database? If so, store the last post time in the database linked to IP and perform the same check as above.
I don't really deal with PHP, so I can't give you a "real" answer. But I think it might be better to dispatch to a worker.
So with Python/Celery, which is generally what I work with (NOTE: I am not slighting PHP; no flamewar), I would use apply_async(<some function>, delay=<N seconds>)
. Celery is a worker queue that here is just accepting a job, to complete the post in this case.
That pattern would let you send the job on its way, delayed in the appropriate way, and won't necessarily block your server processes.
If the delay applies to all users, you would need to store a timestamp of the last post using some form of persistence, then check that value before each new post to see if the appropriate amount of time has elapsed. Options would be storing the value in a database, in a cache (like memcached), or simply in a file.
Since you already have a database (presumably), adding a table in which you store the timestamp (and any other config-type variables that you might need) is probably the simplest option.
A cache would be overkill if it's only used for storing one value.
If you don't want to use a database for this, then it's simple enough to store the timestamp in a file, using file_put_contents
, and retrieve it with file_get_contents
. (PHP's session information is stored in files in much the same way.)