服务器不接受我的原始POST HTTP协议调用中的参数

时间:2015-03-04 23:19:41

标签: php post

这是我发送到服务器的原始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

result进行了同样的调用

为什么$ _POST数组为空,我做错了什么?

1 个答案:

答案 0 :(得分:0)

只是一个猜测,但我说你使用的客户并没有正确发送数据。我认为它没有在请求中使用正确的CRLF和/或因为它没有发送Connection: close。它也可能是您的Web服务器中的配置错误。

我自己使用以下PHP脚本测试了它:

<?php

$host = 'www.example.com';
if ($fp = fsockopen('ssl://'. $host, 443, $errno, $errstr, 30)) {
    $data = 'key=value';

    $msg = "POST /test.php HTTP/1.1\r\n";
    $msg .= "Host: ".$host."\r\n";
    $msg .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $msg .= "Connection: close\r\n";
    $msg .= "Content-Length: ".strlen($data)."\r\n\r\n";
    $msg .= $data."\r\n\r\n";

    $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