Rasher's Toolbox

Back

cached_file_get_contents

string cached_file_get_contents(string uri [, int ttl [, string path [, string prefix ]]]) -- Load a file from an URI, keeping a cached copy

Description

This function will copy a file from an URI and save it locally. If a local cache newer than ttl seconds exists, that will be used instead. The file will be stored in path, using the md5sum of the uri and a prefix as the filename.

Example

<?php
  $contents 
cached_file_get_contents('http://rasher.dk/index.php'1800'data/''rasherdk-');
?>

Source

Published under the terms of the BSD License

<?php
function cached_file_get_contents($uri$ttl 900$dir '.'$prefix ''$debug false) {
    
$file sprintf("%s/%s%s"$dir$prefixmd5($uri));
    if (!
file_exists($file) || (time() - filemtime($file)) > $ttl) {
        if (
file_exists($file) && $debug !== falseprintf("Getting %s (TTL:%d, Age:%d<br />\n"$uri$ttltime() - filemtime($file));
        elseif (
$debug !== false && !file_exists($file)) printf("Getting %s<br />\n"$uri);
        
$contents file_get_contents($uri);
        if (
$contents === false) return false;
        
file_put_contents($file$contents);
    }
    return 
file_get_contents($file);
}
?>

Last updated: Tue May 18 13:11:58 CEST 2010

Valid XHTML 1.0! Valid HTML 3.2!