file_get_contents('php:// input')始终为空

时间:2018-02-28 18:18:31

标签: php php-curl

我正在尝试通过cURL获取POST请求的数据。我正在使用file_get_contents('php://input'),但它总是空的。我错过了什么?

我的脚本

<?php

$data_string = json_encode([ "foo" => 123 ]);


$ch = curl_init('http://httpbin.org/post');

#
# Debugging
#

# Send traffic through proxy
#curl_setopt($ch, CURLOPT_PROXY, '127.0.0.1:8888');

$stderr = fopen('php://temp', 'w+');
curl_setopt($ch, CURLOPT_STDERR, $stderr);
curl_setopt($ch, CURLOPT_VERBOSE, true);

#
# Send request
#

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string)
]);
$result = curl_exec($ch);

echo "\nRESULT:\n$result";

#
# Output debugging
#

rewind($stderr);
$stderrLog = stream_get_contents($stderr);

echo "\nDEBUG:\n$stderrLog\n";

echo "\nSETTINGS:\nallow_url_fopen: ", ini_get('allow_url_fopen'), "\n";

$body = file_get_contents('php://input');
echo "\nBODY:\n$body\n";

脚本结果

RESULT:
{
  "args": {},
  "data": "{\"foo\":123}",
  "files": {},
  "form": {},
  "headers": {
    "Accept": "*/*",
    "Connection": "close",
    "Content-Length": "11",
    "Content-Type": "application/json",
    "Host": "httpbin.org"
  },
  "json": {
    "foo": 123
  },
  "origin": "65.199.22.138",
  "url": "http://httpbin.org/post"
}

DEBUG:
*   Trying 23.21.55.239...
* TCP_NODELAY set
* Connected to httpbin.org (23.21.55.239) port 80 (#0)
> POST /post HTTP/1.1
Host: httpbin.org
Accept: */*
Content-Type: application/json
Content-Length: 11

* upload completely sent off: 11 out of 11 bytes
< HTTP/1.1 200 OK
< Connection: keep-alive
< Server: meinheld/0.6.1
< Date: Wed, 28 Feb 2018 18:08:13 GMT
< Content-Type: application/json
< Access-Control-Allow-Origin: *
< Access-Control-Allow-Credentials: true
< X-Powered-By: Flask
< X-Processed-Time: 0
< Content-Length: 343
< Via: 1.1 vegur
<
* Connection #0 to host httpbin.org left intact


SETTINGS:
allow_url_fopen: 1

BODY:

其他信息

  • PHP版本:7.2.2
  • PHP错误日志正在接收错误,但此代码中没有任何内容
  • 我已经通过mitmproxy验证了请求正在发送JSON数据
  • allow_url_fopen设置为true(参见脚本)

1 个答案:

答案 0 :(得分:0)

由于您的网站收到file_get_contents('php://input')POST请求,

PUT是您的脚本在由网络服务器调用时作为输入数据获取的内容。< / p>

这当然假设脚本是Web应用程序的一部分。

但是您从终端运行脚本(,当我从评论中读取),在这种情况下php://input 始终为空

您的脚本中发生了什么:

您通过$data_string请求(已成功)发送数据(http://httpbin.org/post中的内容)至POST

您收到的响应位于$result,并且您发布的输出是一些JSON编码数据。