note 49478 deleted from function.fopen by sniper
| From: | sniper@php.net | Date: | Wed, 28 Dec 2005 11:01:20 +0000 |
| Subject: | note 49478 deleted from function.fopen by sniper | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-100839@lists.php.net to get a copy of this message | ||
Note Submitter: conner_bw
----
An improved version of zwiskle's cached_fopen_url(). This accounts for the fact that the
destination website might not respond or time out thereby stalling the source server.
<?php
/*******************************************
* Function cached_fopen_url():
* Caches data from a HTTP resource/url to a
* local file (HTTP headers are stipped)
* @returns a file resoruce / or FALSE if failure.
**/
function cached_fopen_url($url, $file_mode, $timeout_seconds = 90, $cache_path =
"/yourpath/tmp", $fsocket_timeout = 10)
{
$debug = true;
clearstatcache();
$cache_filename=$cache_path . "/" . urlencode($url) .".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 ($url) to local ($cache_filename)<p>";}
$urlParts = parse_url($url);
$host = $urlParts['host'];
$port = (isset($urlParts['port'])) ? $urlParts['port'] : 80;
if( !$fp = @fsockopen( $host, $port, $errno, $errstr, $fsocket_timeout )) {
// Server not responding
} else {
if( !fputs( $fp, "GET $url HTTP/1.0\r\nHost:$host\r\n\r\n" )) {
die( "unable to send get request" );
}
$data = null;
stream_set_timeout($fp, $fsocket_timeout);
$status = socket_get_status($fp);
while( !feof($fp) && !$status['timed_out'])
{
$data .= fgets ($fp,8192);
$status = socket_get_status($fp);
}
fclose ($fp);
// strip headers
$sData = split("\r\n\r\n", $data, 2);
$data = $sData[1];
// save to cache file
$f2 = fopen($cache_filename,"w+");
fwrite($f2,$data);
fclose($f2);
}
}
// ok, point to (fresh) cached file
if ( @file_exists($cache_filename )) {
$handle = fopen($cache_filename, $file_mode);
return $handle;
}
return false;
}
?>