PHPKonf 2025 Baku

Voting

: max(three, zero)?
(Example: nine)

The Note You're Voting On

edgarinvillegas at hotmail dot com
16 years ago
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)

<< Back to user notes page

To Top