Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Created June 25, 2013 14:41
Show Gist options
  • Save xeoncross/5858999 to your computer and use it in GitHub Desktop.
Save xeoncross/5858999 to your computer and use it in GitHub Desktop.
Non-blocking, stream-based file reader with timeouts and max content length
<?php
$context = stream_context_create(array(
'http' => array(
'method' => "GET",
//'timeout' => 10,
//'user_agent' => $this->user_agent,
'max_redirects' => 10,
'header' => "Accept-language: en\r\n"
//. 'If-None-Match: '.$this->etag . "\r\n"
//. 'If-Modified-Since: '.$this->last_modified . "\r\n"
)
));
// Giant, malformed, mess of an XML feed XD
$stream = fopen('http://duga.jp/ror.xml', 'r', false, $context);
// Don't allow our stream to block forever
stream_set_blocking($stream, false);
var_dump(stream_get_meta_data($stream));
$content = '';
$size = 0;
$max_length = 1000000;
$max_time = 5;
$startTime = time();
while($stream AND ! feof($stream)) {
if(($line = fgets($stream, 8192)) === false) {
print "Something failed\n";
break;
}
$size += mb_strlen($line);
$content .= $line;
if($size > $max_length) {
print "too long\n";
break;
}
if(time() - $startTime > $max_time) {
print "Taking too long\n";
break;
}
usleep(500);
}
var_dump($stream);
var_dump(feof($stream));
print mb_strlen($content) . "\n";
fclose($stream);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment