【发布时间】:2012-02-04 02:02:31
【问题描述】:
我在 PHP 中使用套接字连接将数据发布到 Apache 网络服务器。我对这种技术有点陌生,我不确定如何将标头与响应正文隔离开来。
发送代码:
<?php
// collect data to post
$postdata = array(
'hello' => 'world'
);
$postdata = http_build_query($postdata);
// open socket, send request
$fp = fsockopen('127.0.0.1', 80);
fwrite($fp, "POST /server.php HTTP/1.1\r\n");
fwrite($fp, "Host: fm1\r\n");
fwrite($fp, "Content-Type: application/x-www-form-urlencoded\r\n");
fwrite($fp, "Content-Length: ".strlen($postdata)."\r\n");
fwrite($fp, "Connection: close\r\n");
fwrite($fp, "\r\n");
fwrite($fp, $postdata);
// go through result
$result = "";
while(!feof($fp)){
$result .= fgets($fp);
}
// close
fclose($fp);
// display result
echo $result;
?>
服务器代码:
Hello this is server. You posted:
<pre>
<?php print_r($_POST); ?>
</pre>
当发布到一台服务器时,我得到:
HTTP/1.1 200 OK
Date: Fri, 06 Jan 2012 09:55:27 GMT
Server: Apache/2.2.15 (Win32) mod_ssl/2.2.15 OpenSSL/0.9.8m PHP/5.3.2
X-Powered-By: PHP/5.3.2
Content-Length: 79
Connection: close
Content-Type: text/html
Hello this is server. You posted:
<pre>
Array
(
[hello] => world
)
</pre>
正如预期的那样。不过,我想去掉标题,然后从“你好,这是服务器.....”开始阅读正文。 我怎样才能可靠地检测到标题的结尾并将正文读入变量?
另外,我测试过的另一台服务器的回复是这样的:
HTTP/1.1 200 OK
Date: Fri, 06 Jan 2012 10:02:04 GMT
Server: Apache/2
X-Powered-By: PHP/5.2.17
Connection: close
Transfer-Encoding: chunked
Content-Type: text/html
4d
Hello this is server. You posted:
<pre>
Array
(
[hello] => world
)
</pre>
0
正文周围的“4d”和“0”是什么??
谢谢!
PS 在有人说使用 CURL 之前,不幸的是我不能 :-(
【问题讨论】:
-
不确定
4d和0,但您可以非常可靠地使用explode('\r\n\r\n', $result)。
标签: php apache http http-headers