如何在php上使用curl发出文件的多部分/表单-数据请求和重复键


How to issue a multipart/form-data request of a file and a duplicate key with curl on php

我想知道是否有可能通过依赖PHPcurl自动主体创建从CURLOPT_POSTFIELDS选项发出以下multipart/form-data请求。我想避免自己构建主体字符串。

POST / HTTP/1.0
Host: example.com
Content-type: multipart/form-data, boundary=AaB03x
Content-Length: ...
--AaB03x
Content-Disposition: form-data; name="field"
foo
--AaB03x
Content-Disposition: form-data; name="field"
bar
--AaB03x
content-disposition: form-data; name="file"; filename="filename"
Content-Type: text/plain
Content-Transfer-Encoding: binary
...

注意"field"如何出现两次。我正在处理的API要求数组被指定为重复的(例如field=foo&field=bar),并且不接受PHP序列化这种结构的方式(例如field[0]=foo&field[1]=bar)。

根据我的理解,POSTPHP上使用curl的正确方法是使用CurlFile:

$ch = curl_init();
...
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt(
    $ch, CURLOPT_POSTFIELDS,
    array('file' => new CurlFile('file.txt', 'text/plain', 'file.txt'))
);

问题是我不能用这种方式指定一个重复的POST字段。我试着提供一个值数组,但它失败了一个Array to string conversion异常。

$ch = curl_init();
...
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt(
    $ch, CURLOPT_POSTFIELDS, array(
        'fields' => array('foo', 'bar'),
        'file' => new CurlFile('file.txt', 'text/plain', 'file.txt'),
    )
);
...
Array to string conversion

是否有任何方法可以实现我所追求的,或者我必须自己构建我的multipart请求?

看起来这是一个PHP bug