You are here:  » Updated simple cache mechanism using PHP only


Updated simple cache mechanism using PHP only

Submitted by support on Mon, 2011-12-12 19:11 in

Hi everyone,

This is an update to the technique i've suggested in the past for applications that need to cache remote URLs but this time by using built in PHP functions rather than shelling out to wget etc.

As before, you need to create a cache directory in the same folder as your script that has write access to the PHP process. The easiest way to do this is normally via your FTP program. In the remote window, first create a new folder with the name "cache" (without the quotes). Next, in the remote window right-click on the new folder and then look for Permissions, or possibly Properties and then Permissions, and give WRITE access to all users (Owner / Group / World).

Then, add the following function to your script that returns a cached filename (constructed from the MD5 hash of the URL) that conditionally re-fetches the file based on the timestamp of the current cached copy compared to an age value (given in seconds)

  function cacheFetch($url,$age)
  {
    // directory in which to store cached files
    $cacheDir = "cache/";
    // cache filename constructed from MD5 hash of URL
    $filename = $cacheDir.md5($url);
    // default to fetch the file
    $fetch = true;
    // but if the file exists, don't fetch if it is recent enough
    if (file_exists($filename))
    {
      $fetch = (filemtime($filename) < (time()-$age));
    }
    // fetch the file if required
    if ($fetch)
    {
      copy($url,$filename);
    }
    // return the cache filename
    return $filename;
  }

To combine that with a script using Magic Parser; you would then do something like this:

  // fetch (if required)
  $filename = cacheFetch("http://www.example.com/rss.xml",86400);
  // parse
  MagicParser_parse($filename,"myRecordHandler","xml|RSS/CHANNEL/ITEM/");

(using a value of 86400 for the $age parameter will mean that the URL is only retrieved once a day)

Cheers,
David.