In the previous three examples, there is a piece of code:
while (! feof ($fp)) { // read File/Data //$content. = Fgets ($fp, +); $line = Fread ($fp, 4096); $line = fputs ($fp 2,fgets ($fp, +));}
The PHP feof () function is used to detect if the end of file (EOF) has been reached. Returns an error (including the socket timeout) if the file pointer goes to EOF, or TRUE If an error occurs, otherwise returns FALSE.
while (!feof ($FP)) is when the file pointer does not reach end of file, it loops through the data until it has been read. This is a common usage, we use Fsockopen to open a $fp to send HTTP headers, after the request with feof to determine whether to read the content of the server response.
However, when using feof, it is important to note that the PHP manual on feof has such a description:
Warning: If the server does not close the connection opened by Fsockopen (), feof () waits until it expires and returns TRUE. The default time-out limit is 60 seconds, and you can use Stream_set_timeout () to change the value.
That is, an open socket connection, which is not closed after reading, feof will always return true until it expires.
Look at the following code:
$url= "/test/index.php";$fp=Fsockopen(' www.example.com ', 80,$errno,$errstr, 10);if(!$fp){ die("Network error or invalid stock code\r\n");}ElseIf($error){ die("$error:$errstr\ r \ n ");}Else{ $request= "GET$urlHttp/1.1\r\n "; $request. = "host:www.example.com\r\n"; $request. = "pragma:no-cache\r\n"; $request. = "cache-control:no-cache\r\n\r\n"; fwrite($fp,$request);//Send Request Header while(!feof($fp)) { $tmp.=fgets($fp, 1024);//Get server return information } //fclose ($fp);}
There is a problem running this code, while the while goes into a dead loop until it expires. Therefore, a slight change, the request to the end of the head with Connection:close, to tell the server after the response is broken.
Fsockopen Some problems of reading HTTP response content with feof