开发者

feof blocks on sockets

on Mac OS X the following feof() call never returns.

<?php
$hostname = "localhost";
$fh = fsockopen($hostname, 80, &$errno, &$errstr);
if ($errno) {
    print $errstr;
    exit;
}
$request = <<<request
GET / HTTP/1.0
Host: $hostname
开发者_运维技巧Connection: close

request;
fputs($fh,$request);
while (!feof($fh))
    echo fgets($fh);
fclose($fh);
?>

Are you having the same problem in other platforms? Any idea to solve it?


The problem is not with feof, it's your request that isn't formatted the proper way. As you probably know, Unix-like systems uses \n for newline. However, a new line in HTTP is \r\n. You need to change your request:

$request = <<<request
GET / HTTP/1.1\r
Host: $hostname\r
Connection: close\r
\r\n
request;

Also, note that I've used HTTP/1.1, because the Host header doesn't apply to HTTP 1.0. It was introduced in 1.1. You will also see that I've put \n on the last line. It's because heredoc doesn't end the string with a new line automatically.

One last thing, this:

fsockopen($hostname, 80, &$errno, &$errstr);

... is wrong. It is called a Call-time pass-by-reference, and is deprecated. The good way is:

fsockopen($hostname, 80, $errno, $errstr);

... without the &. You will have the same result, but no errors will be triggered (in 5.3 at least).


Your code generates a 'Bad Request' from Apache on my Ubuntu 10.10.

This, I think, has to do with the line endings in your request. Replacing your heredoc request assignment with the following works:

$request = "GET / HTTP/1.0\r\n"
        . "Hostname: $hostname\r\n"
        . "Connection: close\r\n"
        . "\r\n";

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜