php cache

Posted: April 16th, 2008 | Author: | Filed under: Developers | No Comments »


<pre lang="php">
<?php

$url = "http://www.site.com/file.php";
$dest_file = "footercache.txt"; //be sure it is chmod-ed to 0666 !!

$pagesource = request_cache($url, $dest_file, 3600*24*7);
echo $pagesource;

function request_cache($url, $dest_file, $timeout=7200) {

  if(strlen($dest_file) > 100) $dest_file = substr($dest_file, 20, 60) . substr($dest_file, strlen($dest_file) - 4);//keep some chars and the probable extension

  if(!file_exists($dest_file) || filemtime($dest_file) < (time()-$timeout)) {

    $data = @file_get_contents($url);
    if ($data !== false) {

      $tmpf = tempnam("/tmp","YWS");
      $fp = @fopen($tmpf,"w");
      @fwrite($fp, $data);
      @fclose($fp);
      if(file_exists($dest_file)) @unlink($dest_file);
      rename($tmpf, $dest_file);

    }else{

      touch($dest_file);//update its date only

    }

  } else {

    $data = file_get_contents($dest_file);

  }
  return($data);

}

?>
</pre>



Leave a Reply