Link to home
Start Free TrialLog in
Avatar of WarriorPoet42
WarriorPoet42

asked on

Cron Jobs To Create Pseudo-Static Pages With PHP

I have a php page that is query intensive.  I would like to create a cron job that runs every 5 minutes or so that takes the PHP file as input, and outputs a static HTML file to decrease server load.  I have NO idea how to do this.
Avatar of Tintin
Tintin

Create a cronjob  along the lines of

*/5 * * * * /path/to/script.php >/path/to/static.html
In fact I would not use the cron job for that purpose.
I would incorporate caching mechanizm in the php script itself.
On run, it could check the cache when it was generated last time. If too long time ago, regenrate the cache. After the check, serve the webpage from the cache.
The cache itself may be in another file (like script.php.html) or shared memory or even database.
Avatar of WarriorPoet42

ASKER

How would that be coded, ravenpl?
example for file based

<?php
$filename = "??";
$now = time();
$fnow = filemtime($filename);
if ($now === false || $fnow < ($now - 300)) #300 second
{
  require("lib/regerate_filename.php");
};
readfile($filename);
?>
For to avoid regerating from two requests at same time
http://pl.php.net/manual/en/function.flock.php

Also, it does not have to be file, You can store the current pageView in the database (separate table with just one entry pair<lastModified, content>)
I'm not sure I understand what your script is doing.  If the file I want to cache is called players.php would that go $filename = "players.php"; ?

What would regenerate_filename.php be?
ASKER CERTIFIED SOLUTION
Avatar of ravenpl
ravenpl
Flag of Poland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
How would I make the php file output into a text file?
open the file and print to file instead of stdout, but
to not mess with the original players.php You could use folowing wrapper(give feedback if it works, as I haven't tested that)

<?php
function ob__callback($buffer)
{
 fwrite($_GLOBALS["fp"], $buffer);
 return $buffer;
};

$filename = "cache/players.txt";
$now = time();
$fp = 0;
$fnow = filemtime($filename);
if ($now === false || $fnow < ($now - 300)) { #300 second
  $fp = fopen($filename, 'w'); #truncates as well
  flock($fp, LOCK_EX); #ignore errors, we already truncated the filename
  ob_start("ob__callback");
  require("lib/players.php");
  ob_end_flush();
  fclose($fp);
} else {
  readfile($filename);
}
?>