I had a fread script that hanged forever (from php manual):
<?php
$fp = fsockopen("example.host.com", 80);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
fwrite($fp, "Data sent by socket");
$content = "";
while (!feof($fp)) { $content .= fread($fp, 1024);
}
fclose($fp);
echo $content;
}
?>
The problem is that sometimes end of streaming is not marked by EOF nor a fixed mark, that's why this looped forever. This caused me a lot of headaches...
I solved it using the stream_get_meta_data function and a break statement as the following shows:
<?php
$fp = fsockopen("example.host.com", 80);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
fwrite($fp, "Data sent by socket");
$content = "";
while (!feof($fp)) {
$content .= fread($fp, 1024);
$stream_meta_data = stream_get_meta_data($fp); if($stream_meta_data['unread_bytes'] <= 0) break; }
fclose($fp);
echo $content;
}
?>
Hope this will save a lot of headaches to someone.
(Greetings, from La Paz-Bolivia)