September 17, 2004
[PHP] Cached fopen();
Here's a great one, cached fopen.
This is based off of some code I found in a comment on php.net under the fopen function. I modified it a little bit. I've gotta find a better way to do this code section.
function cached_fopen($file, $file_mode, $timeout_seconds = 600, $cache_path = "/tmp", $error_report = false){
clearstatcache();
$cache_filename=$cache_path . "/" . urlencode($file) .".cached";
if (!( @file_exists($cache_filename ) and ( ( @filemtime($cache_filename) + $timeout_seconds) > ( time() ) ) ) ){
if($error_report) echo 'Caching new file '.$file .' in '.$cache_path;
if(!$f = fopen($file,"r")){
if($error_report) echo 'ERROR: Unable to open remote file: '.$file;
return false;
}
if(!$f2 = fopen($cache_filename,"w+")){
if($error_report) echo 'ERROR: Unable to open local cache file: '.$cache_filename;
return false;
}
while ($r=fread($f,8192) ) {
fwrite($f2,$r);
}
fclose($f2);
fclose($f);
} else {
if($error_report) echo 'Using cached file: '.$cache_filename;
}
$handle = fopen($cache_filename, $file_mode);
return $handle;
}
This is based off of some code I found in a comment on php.net under the fopen function. I modified it a little bit. I've gotta find a better way to do this code section.