CURLOPT_POSTFIELDS 不接受数组

问题描述 投票:0回答:1

为什么 CURLOPT_POSTFIELDs 不接受数组?使用 PHP 8.2.15

我有两个文件:

// temp.php

exit(file_get_contents('php://input'));
// test.php

$fields = ['foo' => 'bar'];

$config = [
    \CURLOPT_RETURNTRANSFER => true,
    \CURLOPT_ENCODING => '',
    \CURLOPT_MAXREDIRS => 10,
    \CURLOPT_TIMEOUT => 10,
    \CURLOPT_FOLLOWLOCATION => true,
    \CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
];

$with_array_handle = \curl_init('http://localhost/temp.php');
\curl_setopt_array($with_array_handle, $config + [\CURLOPT_POSTFIELDS => $fields]);


$with_string_handle = \curl_init('http://localhost/temp.php');
\curl_setopt_array($with_string_handle, $config + [\CURLOPT_POSTFIELDS => http_build_query($fields)]);

echo '<pre>' . curl_exec($with_array_handle) . '</pre>';
echo '<pre>' . curl_exec($with_string_handle) . '</pre>';

temp.php
回显请求正文。
test.php
请求
temp.php
两次并回显两个响应,因此
test.php
应该将两个请求的正文输出到
temp.php

但我实际得到的是


foo=bar

如果我使用

CURLOPT_POSTFIELDS
,第一个请求的正文为空。为什么? PHP 文档 特别指出
CURLOPT_POSTFIELDS
接受数组作为输入,但这与我观察到的行为不匹配。

此参数可以作为 urlencoded 字符串(如

para1=val1&para2=val2&...
)传递,也可以作为以字段名称作为键、字段数据作为值的数组传递。

php curl php-8 php-8.2
1个回答
0
投票

当您给它一个数组时,请求将通过

Content-type: multipart/form-data
发送。显然,这会导致 PHP 处理器读取主体本身,而
php://input
无法使用它。我怀疑这是因为这种格式通常用于文件上传,因此需要将上传的文件读取到临时文件中,并构建
$_FILES
数组;很难让它可供输入流重新读取。

无论哪种情况,参数都可以在

$_POST
数组中使用。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.