I searched a way to send a post request with multiple files using curl.
But all code examples did not do the same as a browser does.
The $_FILES global did not contain the usual array as documented by PHP.
Now i found out why: the offsets where missing the [i]
see http://php.net/manual/de/class.curlfile.php#121971
Without the "trick" you would get a different result in $_FILES
[
'foo_bar' => [
'name' => 'path/to/my_file_1.png',
'type' => 'application/octet-stream',
'tmp_name' => '/tmp/phpim24ij',
'error' => 0,
'size' => 123,
],
]
or
[
'foo_bar_1' => [
'name' => 'path/to/my_file_1.png',
'type' => 'application/octet-stream',
'tmp_name' => '/tmp/phpim24ij',
'error' => 0,
'size' => 123,
],
'foo_bar_2' => [
'name' => 'path/to/my_file_1.png',
'type' => 'application/octet-stream',
'tmp_name' => '/tmp/phpim24ij',
'error' => 0,
'size' => 123,
],
]
But this is not what we want.
What we want is the usual $_FILES array like
[
'foo_bar' => [
'name' => [
0 => 'path/to/my_file_1.png',
1 => 'path/to/my_file_2.png',
],
'type' => [
0 => 'application/octet-stream',
1 => 'application/octet-stream',
],
'tmp_name' => [
0 => '/tmp/phpSPAjHW',
1 => '/tmp/php0fOmK4',
],
'error' => [
0 => 0,
1 => 0,
],
'size' => [
0 => 123,
1 => 234,
],
],
]
Here the code:
Example:
$url = "http://api-foo.com/bar/baz";
$uploadFormInputFieldName = 'foo_bar';
$files = [
'path/to/my_file_1.png',
'path/to/my_file_2.png',
// ...
];
$postData = [];
$i = 0;
foreach ($files as $file) {
if (function_exists('curl_file_create')) {
$file = curl_file_create($file);
} else {
$file = '@' . realpath($file);
}
// here is the thing: post data needs to be $posData["foo_bar[0]"], $posData["foo_bar[1]"], ...
$postData["{$uploadFormInputFieldName}[{$i}]"] = $file;
$i++;
}
$httpClient = $this->getHttpClient($url); // get your client
$httpClient->setHeader('Content-Type', 'multipart/form-data');
$response = $httpClient->post($postData); // send post request