note 77548 deleted from function.fread by cmb

From: Date: Sun, 12 Jan 2020 08:20:48 +0000
Subject: note 77548 deleted from function.fread by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-213850@lists.php.net to get a copy of this message
Note Submitter: Blagovest Buyukliev ---- 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.

« previous php.notes (#213850) next »