note 93250 added to function.fread
| From: | edgarinvillegas at hotmail dot com | Date: | Sun, 30 Aug 2009 19:16:55 +0000 |
| Subject: | note 93250 added to function.fread | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-160060@lists.php.net to get a copy of this message | ||
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)) { //This looped forever
$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); //Added line
if($stream_meta_data['unread_bytes'] <= 0) break; //Added line
}
fclose($fp);
echo $content;
}
?>
Hope this will save a lot of headaches to someone.
(Greetings, from La Paz-Bolivia)
----
Server IP: 69.147.83.197
Probable Submitter: 186.2.51.30
----
Manual Page -- http://www.php.net/manual/en/function.fread.php
Edit -- https://master.php.net/note/edit/93250
Del: integrated -- https://master.php.net/note/delete/93250/integrated
Del: useless -- https://master.php.net/note/delete/93250/useless
Del: bad code -- https://master.php.net/note/delete/93250/bad+code
Del: spam -- https://master.php.net/note/delete/93250/spam
Del: non-english -- https://master.php.net/note/delete/93250/non-english
Del: in docs -- https://master.php.net/note/delete/93250/in+docs
Del: other reasons-- https://master.php.net/note/delete/93250
Reject -- https://master.php.net/note/reject/93250
Search -- https://master.php.net/manage/user-notes.php