PHP CURL multiple files upload with same key

Viewed 535

I have a rest API that accepts multiple files in the same key (written in some other language [Not in PHP for sure]).

Image from postman

I consumed the API via postman and I can able to see both files are uploaded properly.

Generated code from the postman and tried sending multiple files.

// PHP Version 7.3 +
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => $url,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS => array(
  'file'=> new CurlFile('C:/Users/Username/Pictures/Image.png','image/png','Image.png'),
  'file'=> new CurlFile('C:/Users/Username/Pictures/Image2.png','image/png','Image2.png'),
  )
));

echo $response = curl_exec($curl);

I am unable to see both files uploaded successfully.

I know PHP won't support duplicate keys in the array. It will be sent as one single key which is file.

But I am no control over the rest API. It works well in Postman properly. But, PHP doesn't.

Is there any way to solve the problem?

like below,

CURLOPT_POSTFIELDS => array(
   'file'=> new CurlFile(['Image.png','Image2.png'],'image/png', ['Image.png','Image2.png'])
);

Tried sending with index values, But only works in PHP to PHP communication (Not to other languages)

CURLOPT_POSTFIELDS => array(
   'file[0]'=> new CurlFile(['Image.png','Image2.png'],'image/png', ['Image.png','Image2.png']),
   'file[1]'=> new CurlFile(['Image.png','Image2.png'],'image/png', ['Image.png','Image2.png'])
);

Tried indexed array, didn't work.

[
    new \CurlFile('image_full_path1.png', 'image/png', 'file1.png'),
    new \CurlFile('image_full_path2.png', 'image/png', 'file2.png'),
]
1 Answers

"Tried sending with index values" acutally you are using a string, not a value of an array.

Try it with a real array:

CURLOPT_POSTFIELDS => [
    'file' => [
        new CURLFile('Image.png','image/png', 'Image.png'),
        new CURLFile('Image2.png','image/png', 'Image2.png'),
    ]
];

The classname is CURLFile not CURLFILE or CurlFile.

The constructor signature doesn't allow arrays in the parameters:

public __construct ( string $filename , string|null $mime_type = null , string|null $posted_filename = null )

https://www.php.net/curlfile

Your code should give you quite some errors, you should look them up in the logs or enable printing them in the browser (set display_errors to true)

Related