我正在尝试通过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:
答案 0 :(得分:0)
file_get_contents('php://input')
或POST
请求, 这当然假设脚本是Web应用程序的一部分。 但是您从终端运行脚本(,当我从评论中读取),在这种情况下 您的脚本中发生了什么: 您通过 您收到的响应位于PUT
是您的脚本在由网络服务器调用时作为输入数据获取的内容。< / p>
php://input
始终为空。$data_string
请求(已成功)发送数据(http://httpbin.org/post
中的内容)至POST
。$result
,并且您发布的输出是一些JSON编码数据。