这是我发送到服务器的原始POST调用(我使用的是Postman REST Client
):
POST / HTTP/1.1
Host: ******
Content-Type: application/x-www-form-urlencoded
Content-Length: 9
key=value
在服务器端,我想从我的原始POST调用中读取$_POST中的键、值,PHP源代码如下:
<?php
header('Access-Control-Allow-Origin: *');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
header('Pragma: no-cache');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Content-Type: application/x-www-form-urlencoded');
print_r($_POST);
echo file_get_contents('php://input');
?>
这是我从服务器上得到的输出:
Array
(
)
POST / HTTP/1.1
Host: ******
Content-Type: application/x-www-form-urlencoded
Content-Length: 9
key=value
更新:也对posttestserver.com进行了同样的调用,得到了相同的结果
为什么$_POST数组为空,我做错了什么
只是猜测,但我认为您使用的客户端没有正确发送数据。我认为它没有在请求中使用正确的CRLF和/或是因为它没有发送Connection: close
。它也可能是您的网络服务器中的错误配置。
我自己使用以下PHP脚本进行了测试:
<?php
$host = 'www.example.com';
if ($fp = fsockopen('ssl://'. $host, 443, $errno, $errstr, 30)) {
$data = 'key=value';
$msg = "POST /test.php HTTP/1.1rn";
$msg .= "Host: ".$host."rn";
$msg .= "Content-Type: application/x-www-form-urlencodedrn";
$msg .= "Connection: closern";
$msg .= "Content-Length: ".strlen($data)."rnrn";
$msg .= $data."rnrn";
$response = '';
if ( fwrite($fp, $msg) ) {
echo 'Request:'.PHP_EOL;
echo $msg;
while ( !feof($fp) ) {
$response .= fgets($fp, 4096);
}
echo 'Response:'.PHP_EOL;
echo $response;
}
fclose($fp);
}
我从你发布的完全相同的PHP脚本中得到了预期的响应:
Request:
POST /test.php HTTP/1.1
Host: www.example.com
Content-Type: application/x-www-form-urlencoded
Connection: close
Content-Length: 9
key=value
Response:
HTTP/1.1 200 OK
Server: nginx
Date: Thu, 05 Mar 2015 05:06:53 GMT
Content-Type: application/x-www-form-urlencoded
Transfer-Encoding: chunked
Connection: close
X-Powered-By: PHP/5.6.6
Access-Control-Allow-Origin: *
Expires: Mon, 26 Jul 1997 05:00:00 GMT
Last-Modified: Thu, 05 Mar 2015 05:06:53 GMT
Pragma: no-cache
Cache-Control: no-store, no-cache, must-revalidate
26
Array
(
[key] => value
)
key=value
0