Last Updated: February 25, 2016
·
425
· brendanmurty

Cache a file

Download a file to a certain local folder if it's older than $maxageminutes then return the file's URL.

$local_folder should start and end with a forward slash

<?
function cache($media_url,$local_folder,$local_filename,$max_age_minutes=5){
if($media_url && $local_folder && $local_filename){
    //Convert to a real path on the server
    $local_folder=dirname(__FILE__).'/cache'.$local_folder;

    //Default to make a new cache
    $make_new_file='1';

    //Check if there is already a local version of this file
    if(file_exists($local_folder.$local_filename)){
        $file_mod_time=time_relative(filemtime($local_folder.$local_filename));
        if(strstr($file_mod_time,'minute')){
            $minutes=ereg_replace('[^0-9]','',$file_mod_time);//Remove all but numbers
            if($max_age_minutes-1>$minutes){
                $make_new_file='0';//File isn't old enough to require a recache
            }
        }
    }

    if($make_new_file=='1'){//Create a new local file
        @$file=fopen($media_url,"r");//Open the remote file for reading
        if($file){
            //Create the local directory
            if(!file_exists($local_folder)){ $create_local_path=@mkdir($local_folder,0777); }

            //Create the local file
            $fc=@fopen($local_folder.$local_filename,"w+"); 
            while(!feof($file)){ 
                $line=@fread($file,1028);
                @fwrite($fc,$line);
            }
            fclose($fc);
        }
    }

    //Convert the local path to a URL
    $local_folder=str_replace('/domains/test.com/','http://test.com/',$local_folder);
    return $local_folder.$local_filename;
}
}
?>