Rob*_*Rob 9 php apache http http-headers
我在PHP中使用套接字连接将数据发布到Apache Web服务器.我对这种技术有点新意,我不知道如何将标题与响应主体隔离开来.
发送代码:
<?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;
?>
Run Code Online (Sandbox Code Playgroud)
服务器代码:
Hello this is server. You posted:
<pre>
<?php print_r($_POST); ?>
</pre>
Run Code Online (Sandbox Code Playgroud)
发布到一台服务器时,我得到:
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>
Run Code Online (Sandbox Code Playgroud)
正如所料.我想剥去标题,然后从"Hello this is server ....."开始阅读正文.如何可靠地检测标题的结尾并将正文读入变量?
另外,我在回复测试的另一台服务器:
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
Run Code Online (Sandbox Code Playgroud)
正文周围的"4d"和"0"是什么?
谢谢!
PS之前有人说使用CURL,我不能不幸:-(
mar*_*rio 16
您可以通过拆分双线换行来将标题与正文分开.它应该是<CRLF><CRLF>这样通常会起作用:
list($header, $body) = explode("\r\n\r\n", $response, 2);
Run Code Online (Sandbox Code Playgroud)
更可靠的是你应该使用正则表达式来捕捉换行变化(超级不太可能发生):
list($header, $body) = preg_split("/\R\R/", $response, 2);
Run Code Online (Sandbox Code Playgroud)
带有4d和的东西0叫做分块编码.(它是用另一个换行符分隔的十六进制数字,并且表示以下原始内容块的长度).
要清除它,您必须先查看标题,然后查看是否有相应的Transfer-Encoding:条目.这是复杂的,并且建议使用无数现有的HTTP用户空间处理类之一.梨有一个.
| 归档时间: |
|
| 查看次数: |
9328 次 |
| 最近记录: |