Brendan Murty

Home > Posts > Cache an online file

When connecting to a third-party web service, it's a good idea to keep a cached version of the required files in case the third-party service is having issues. This way your website will at least show old data instead of no data at all.

cache - Downloads a file to a certain folder (if required), returns the local path

local_folder should start and end with a forward slash
max_age_minutes is the number of minutes before a new file should be downloaded

function cache($media_url,$local_folder,$local_filename,$max_age_minutes=5){
	if($media_url && $local_folder && $local_filename){
		$local_folder='/cache'.$local_folder;//Convert to a real path on the server
		$make_new_file='1';//Default to creating a new cached file

		//Check if there is already a local version of this file
				$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 download

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

				//Create the local file

		//Convert the local path to a URL
		return $local_folder.$local_filename;