有关fsockopen相关随笔

测试环境,从本机(windows)访问内外一台linux服务器(此服务器装的是nginx)

服务器上的index.php如下:

<?php
    echo 1;

?> 


1.使用Http1.1协议请求

 

function asyn_sendmail() {
    $ip = '192.168.1.45';
    $url = '/index.php';
    $fp = fsockopen($ip, 80, $errno$errstr, 5);
    if (!$fp) {
        echo "$errstr ($errno)<br />\n";
    }

    $end = "\r\n";
    $input = "GET $url HTTP/1.1$end";
    //如果不加下面这一句,会返回一个http400错误   

    //$input.="Host: $ip$end";

    //如果不加下面这一句,请求会阻塞很久  

    //$input.="Connection: Close$end"; 

    $input.="$end";
    fputs($fp$input);
    $html = '';
    while (!feof($fp)) {
        $html.=fgets($fp);
    }
    fclose($fp);
    writelog($html);
    echo $html;
}

function writelog($message) {
    $path = 'D:\log.txt';
    $handler = fopen($path, 'w+b');
    if ($handler) {
        $success = fwrite($handler$message);
        fclose($handler);
    }
}

asyn_sendmail();  

 

 如果注释了$input.="Host: $ip$end";这一句,则会得到一个404错误,D:\log.txt内容如下:

HTTP/1.1 400 Bad Request
Server: nginx/0.8.46
Date: Fri, 30 Dec 2011 02:11:45 GMT
Content-Type: text/html
Content-Length: 173
Connection: close

<html>
<head><title>400 Bad Request</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<hr><center>nginx/0.8.46</center>
</body>
</html> 

说明使用http1.1连接,则必须加上Host请求表头

如果加上了没有注释$input.="Host: $ip$end";这一句 ,则请求成功,D:\log.txt内容如下:

HTTP/1.1 200 OK 

Server: nginx/0.8.46
Date: Fri, 30 Dec 2011 02:20:49 GMT
Content-Type: text/html
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
X-Powered-By: PHP/5.3.8

1
0
0

 返回成功,但是不明白为什么服务器返回内容多了2个0(后来网上查询资料发现,这是因为服务器使用了chunked输出所致,用Wireshark抓包可清晰看到其细节)。如果不加$input.="Connection: Close$end";这一句 ,则Http请求会阻塞很久(在这一句fgets($fp)阻塞)

 

 

2.不指定Http版本

<?php
function asyn_sendmail() {
    $ip = '192.168.1.45';
    $url = '/servertimmer/inserttopicshow/13990/AA8AB76B-7280-578F-12F2-F423685FBD26';
    $fp = fsockopen($ip, 80, $errno, $errstr, 5);
    if (!$fp) {
        echo "$errstr ($errno)<br />\n";
    }
    $end = "\r\n";
    $input = "GET $url$end";   
    $input.="$end";
    fputs($fp, $input);
    $html = '';
    while (!feof($fp)) {
        $html.=fgets($fp);
    }
    fclose($fp);
    writelog($html);
    echo $html;
}
function writelog($message) {
    $path = 'D:\log.txt';
    $handler = fopen($path, 'w+b');
    if ($handler) {
        $success = fwrite($handler, $message);
        fclose($handler);
    }
}
asyn_sendmail();
?>  

 

 请求立刻返回,没有阻塞,返回内容如下:

 1

 注意,返回内容中没有http标头,且没有被阻塞。

 

 

posted @ 2011-12-30 10:11  再快一点  阅读(2225)  评论(0编辑  收藏  举报