note 42980 added to function.fopen
| From: | zwiskle at vol dot at | Date: | Sat, 05 Jun 2004 17:04:58 +0000 |
| Subject: | note 42980 added to function.fopen | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-70545@lists.php.net to get a copy of this message | ||
this smal function can cache local a fopen request. very usefull when you use fopen for http
connections (maybe only then) of (more or less) static data. using a proxy might be a solution, but
they normaly don't support get-url's ( something.php?query=asdf )
I used it original for a webservice-querying webpage, which reads the WSDL file for accurate
parameter-checking...
Speeds up this extremly, and because of the cache-expiration still keep it accurate.
Use at own risk: no error-handling, might also be a security hole, no locking, ...
<?
// cache a (http) fopen - with cache-timeout.
function cached_fopen($file, $file_mode, $timeout_seconds = 600, $cache_path = "/tmp"){
$debug=false;
clearstatcache();
$cache_filename=$cache_path . "/" . urlencode($file) .".cached";
if ($debug) { print "local_cache creation_time =" . @filemtime($cache_filename) . "
actual time = " . time() . " timeout = " . $timeout_seconds ."<p>";}
if ( ( @file_exists($cache_filename ) and ( ( @filemtime($cache_filename) + $timeout_seconds) >
( time() ) ) ) ){
// ok, file is already cached and young enouth
if ($debug) { print "using cached file ($cache_filename) <p>";}
}
else
{
if ($debug) { print "cacheing file ($file) to local ($cache_filename)<p>";}
// cache file from net to local
$f = fopen($file,"r");
$f2 = fopen($cache_filename,"w+");
while ($r=fread($f,8192) ) {
fwrite($f2,$r);
}
fclose($f2);
fclose($f);
}
// ok, point to (fresh) cached file
$handle = fopen($cache_filename, $file_mode);
return $handle;
}
?>
usage:
<?
$handle = cached_fopen("http://example.com/show?xy","r",600)
?>
----
Manual Page -- http://www.php.net/manual/en/function.fopen.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+42980
Delete -- http://master.php.net/manage/user-notes.php?action=delete+42980&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+42980&report=yes
Search -- http://master.php.net/manage/user-notes.php