php - 如何将 HTTP header /正文与 PHP 套接字请求隔离开来

标签 php apache http http-headers

我在 PHP 中使用套接字连接将数据发布到 Apache 网络服务器。我对这项技术有点陌生,我不确定如何将 header 与响应正文隔离开来。

发送代码:

<?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>

正如预期的那样。不过,我想去掉标题,只读“你好,这是服务器……”的正文。 我如何可靠地检测 header 的结尾并将正文读入变量?

此外,我测试过的另一台服务器回复如下:

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 之前,不幸的是我不能 :-(

最佳答案

您可以通过双换行符将标题与正文分开。应该是<CRLF><CRLF>所以这将正常工作:

list($header, $body) = explode("\r\n\r\n", $response, 2);

更可靠的是,您应该使用正则表达式来捕获换行符变化(极不可能发生):

list($header, $body) = preg_split("/\R\R/", $response, 2);

关于 4d 的事情和 0称为 chunked encoding . (它是用另一个换行符分隔的十六进制数字,表示以下原始内容 block 的长度)。

要清除它,您必须先查看 header ,看看是否有相应的 Transfer-Encoding:入口。如果它变得复杂,并且建议使用无数现有的 HTTP 用户空间处理类之一。梨has one .

关于php - 如何将 HTTP header /正文与 PHP 套接字请求隔离开来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8756185/

相关文章:

php - jQuery(或任何网络工具)嵌套表达式生成器

同一台服务器上的 apache 和 Node 保留 ips?

java - 截击请求太慢

python - 触摸 django wsgi 文件来重新加载效果不佳

apache - Apache Hive与法线贴图减少

java - 安卓 HTTP : Make more than 1 asynctask request

http - Apache HttpClient 仅在同一 HttpContext 中重用连接

php - 为什么此点击处理程序 fadeToggle 代码不起作用?

php - 在缓存中找不到 Paypal 沙盒访问 token

php - 标签时在文本字段表中从上到下而不是从左到右聚焦