How to detect stream_copy_to_stream errors?
<p>I've got a bit of code which, simplified, looks something like:</p>

<pre>
$fout = fsockopen($host, 80);
stream_set_timeout($fout, 10*3600); // 10 hours
$fin = fopen($file, 'rb'); // not really a file stream, but good enough proxy here
$readbytes = stream_copy_to_stream($fin, $fout);
if(!$readbytes) die('copy failed');
</pre>

<p>However, I'm sometimes getting the following type of error:</p>

<pre>
Notice: stream_copy_to_stream(): send of 952 bytes failed with errno=104 Connection reset by peer in ...
Notice: stream_copy_to_stream(): send of 952 bytes failed with errno=32 Broken pipe in ...
</pre>

<p>And the check on $readbytes there won't pick up the error.
I'm aware that it may be possible to check the total length of the file with the number of bytes copied, but this only works if the total length of the stream can be determined in advance.</p>

<p>As this happens randomly, I presume that the connection is just being dropped for some weird reason (but if anyone has any suggestions to reduce the likeliness of this happening, I'm all ears).  But it'd be nice to be able to know whether the transfer fully succeeded or not.
Is there anyway to detect a problem without:</p>

<ul>
<li>having to know the length of the stream in advance</li>
<li>hook into the PHP error handler to pick up the error</li>
</ul>

<p>...or perhaps using a buffered fread/fwrite loop, checking the length of bytes written, the best solution here?</p>

<p>Thanks.</p>
