I'm trying to implement a "poor man's cron" to run my PHP script only every 10 minutes (if no one visits the page it doesn't run until someone does)
Here is what I have:
$current_time = time();
if($current_time >= $last_run + (60 * 10)) {
echo 'foo';
$last_run = time();
} else {
echo 'bar';
}
Variables don't hold their value after execution finishes. All memory is cleared when the PHP script finishes, meaning the next time the script is run, PHP will not know what $last_run
was. You need to store $last_run
somehow, possibly using the filesystem or database.
Using the filesystem, you could do:
$last_run = file_get_contents('lastrun.txt');
if (!$last_run || $current_time >= $last_run + (60 * 10)) {
echo 'foo';
file_put_contents('lastrun.txt', time());
} else {
echo 'bar';
}