PHP Curl数组post字段包括一个文件上传



我需要使用PHP curl执行以下操作:

curl "https://the.url.com/upload"
-F file="@path/to/the/file"
-F colours[]="red"
-F colours[]="yellow"
-F colours[]="blue"

我尝试过的代码:

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
'file' => curl_file_create($file),
'colours' = ['red','yellow','blue']
]);
$response = curl_exec($ch);

但我只得到一个错误"数组到字符串的转换…(颜色行)"。如果我完全去除了颜色,那么它是有效的,但我需要包括它们。

我尝试将post字段数组放入http_build_query()中,但服务器返回"415不支持的媒体类型"。我猜是因为它缺少一个mime类型(该文件是一个自定义二进制文件)。

我也试过。。。

'colours[1]' = 'red'
'colours[2]' = 'yellow'
'colours[2]' = 'blue'

但是服务器返回一个错误,说颜色必须是一个数组。就好像我需要创建一个关联数组,但有重复的键。。。我知道我做不到。

有人能帮忙吗?

来自CURLOPT_POSTFIELDS的文档。

此参数可以像'para1=val1&para2=val2&...'一样作为url编码的字符串传递,也可以作为字段名为键、字段数据为值的数组传递。如果值为数组,则Content-Type标头将设置为multipart/form-data

函数http_build_query()将使该值变为'para1=val1&para2=val2&...'

所以,我使用这个作为数组的后字段值,它就可以工作了。

$postFields['hidden-input[0]'] = 'hidden value (from cURL).';

在你的情况下,应该是。

curl_setopt($ch, CURLOPT_POSTFIELDS, [
'file' => curl_file_create($file),
'colours[0]' => 'red',
'colours[1]' => 'yellow',
'colours[2]' => 'blue',
]);

相关回答:1.
示例#2 CURLFile::__construct()中的PHP文档复制的手动数组(name[0])上载多个文件示例

虽然@vee的答案应该有效,但这归结为对该特定服务器应用程序的验证。在与供应商协商后,我最终不得不这样做:

$headers = ['Content-type: multipart/form-data'];
$postFields = [
// NEEDED TO INCLUDE THE MIME TYPE
'file' => curl_file_create($file, mime_content_type($file)),
'colours[]' => ['red', 'yellow', 'blue'],
];

// NEEDED TO REMOVE THE NUMBERS BETWEEN SQUARE BRACKETS
$postFieldString = preg_replace('/%5B[0-9]+%5D/simU', '', http_build_query($postFields));
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFieldString);
$response = curl_exec($ch);