note 77548 added to function.fread
| From: | BlagovestBuyukliev at osu1 dot php dot net | Date: | Mon, 03 Sep 2007 11:45:08 +0000 |
| Subject: | note 77548 added to function.fread | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-130121@lists.php.net to get a copy of this message | ||
Having tried to reliably transfer large amounts of binary data over a latent network, I found out
that fread()/fwrite() should never be trusted to read/write the whole block with the exact length
specified, even in blocking mode, even for small block lengths.
I came up with these two functions, fully-replaceable and reliable alternatives of fread()/fwrite()
in a socket context:
<?php
function fullwrite ($sd, $buf) {
$total = 0;
$len = strlen($buf);
while ($total < $len && ($written = fwrite($sd, $buf))) {
$total += $written;
$buf = substr($buf, $written);
}
return $total;
}
function fullread ($sd, $len) {
$ret = '';
$read = 0;
while ($read < $len && ($buf = fread($sd, $len - $read))) {
$read += strlen($buf);
$ret .= $buf;
}
return $ret;
}
?>
The functions are "greedy", i.e. trying to read/write as much data as possible at once. If
the call to fread()/fwrite() reads/writes less than expected, then the next iteration eats up the
remainder. Very smart as only the largest possible chunks are read/written.
Only in case of a broken pipe fullread()/fullwrite() return less than the specified length.
Otherwise it is guaranteed that upon termination
strlen(fullread($sd, $len)) == $len
and
fullwrite($sd, $buf) == strlen($buf)
Works perfectly with a socket descriptor returned from stream_socket_client() or fsockopen().
Greetings from Rousse, Bulgaria.
----
Server IP: 217.75.128.29
Probable Submitter: 212.25.59.124
----
Manual Page -- http://www.php.net/manual/en/function.fread.php
Edit -- https://master.php.net/note/edit/77548
Del: integrated -- https://master.php.net/note/delete/77548/integrated
Del: useless -- https://master.php.net/note/delete/77548/useless
Del: bad code -- https://master.php.net/note/delete/77548/bad+code
Del: spam -- https://master.php.net/note/delete/77548/spam
Del: non-english -- https://master.php.net/note/delete/77548/non-english
Del: in docs -- https://master.php.net/note/delete/77548/in+docs
Del: other reasons-- https://master.php.net/note/delete/77548
Reject -- https://master.php.net/note/reject/77548
Search -- https://master.php.net/manage/user-notes.php