Easy Web Content Caching with PHP

  • If you want to pull in content from a Drupal site, like the latest blog entry, to a static page, it’s pretty easy to do with file_get_contents.
  • However, the cost of polling the Drupal database every time somebody accesses the static home page might be too high.
  • This code is nothing fancy, but it will reduce the load on the site.
  • The nuthshell is to create a local file with the contents of the remote server. After a specified amount of time, re-acquire the remote site content.
  • Effectively, a poor man’s cache.
$host  = "http://my.web.site";
  $path  = "latest-blog-entry";
  $terms = "20+60+45";

  $full_url   = $host . "/" . $path . "/" . $terms;
  $cache_file = "/tmp/" . $path . $terms;
  $cache_age  = "300"; ### seconds (300=5 minutes)

  if ( (! file_exists($cache_file)) ||
       ( (date("U", filemtime($cache_file)) + 300) < date("U") ) ) {
    $output = file_get_contents($full_url);
    $fh = fopen($cache_file, 'w');
    fputs($fh, $output);
    fclose($fh);
    }
  $output = file_get_contents($cache_file);
categories: php | webcache | linux |