note 75063 modified in function.fread by danbrown

From: Date: Fri, 06 Jan 2012 21:08:54 +0000
Subject: note 75063 modified in function.fread by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-185432@lists.php.net to get a copy of this message
reading from a socket stream can be different to the behaviour expected, since you have not set stream_set_blocking to 1. sample source: <?php $fp = fsockopen ($server, $port, $errno, $errstr, $socket_timeout); $header = ''; do { $header.=fread($fp,1); $i++; } while (!preg_match('/\\r\\n\\r\\n$/', $header) && $i < $maxheaderlenth); preg_match('/Content\\-Length:\\s+([0-9]*)\\r\\n/', $header,$matches); $buffer = fread($this->_fp, $matches[1]); ?> if i.e. the content length is 50000 and the responding server is to slow (means 50000 are not completely sent when fread is called) you'll only receive the number of bytes sent by the responding server at the time fread is called. fread will not wait for any data to complete the given size. as described in user notes on stream_set_blocking there seems to be a bug using stream_set_blocking. a workaround - well, not the best way - is to read the response split to 1 byte instead of <?php $buffer = fread($this->_fp, $matches[1]); ?> you'd write <?php $buffer = ''; for($i = 0; $i < $matches[1]; $i++){ $buffer .= fread($this->_fp, 1); } ?> it several tests this seems like it works. --was-- reading from a socket stream can be different to the behaviour expected, since you have not set stream_set_blocking to 1. sample source: $fp = fsockopen ($server, $port, $errno, $errstr, $socket_timeout); $header = ''; do { $header.=fread($fp,1); $i++; } while (!preg_match('/\\r\\n\\r\\n$/', $header) && $i < $maxheaderlenth); preg_match('/Content\\-Length:\\s+([0-9]*)\\r\\n/', $header,$matches); $buffer = fread($this->_fp, $matches[1]); if i.e. the content length is 50000 and the responding server is to slow (means 50000 are not completely sent when fread is called) you'll only receive the number of bytes sent by the responding server at the time fread is called. fread will not wait for any data to complete the given size. as described in user notes on stream_set_blocking there seems to be a bug using stream_set_blocking. a workaround - well, not the best way - is to read the response split to 1 byte instead of $buffer = fread($this->_fp, $matches[1]); you'd write $buffer = ''; for($i = 0; $i < $matches[1]; $i++){ $buffer .= fread($this->_fp, 1); } it several tests this seems like it works. http://php.net/manual/en/function.fread.php

« previous php.notes (#185432) next »