Search code examples
laravelcurlphp-curlphp-7.2

How to send multiple files under the same name using CURL in php7+


Hi am trying to send multiple files in a php Curl operation. I am using PHP7.2 and trying to send 15 images under the same key. If I am trying to send just 1 file its working just fine.

$post["image"] = new \CurlFile('image_full_path.png', 'image/png', 'file.png');

But when I am trying to put multiple files its not working anymore.

Already tried $post["image[0]"] = new \CurlFile('image_full_path.png', 'image/png', 'file.png');

And

$post["image_0"] = new \CurlFile('image_full_path.png', 'image/png', 'file.png');

Does not work

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,"url");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: multipart/form-data"));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    $response = curl_exec($ch);
    $path = '/var/www/download/download.pdf';
    file_put_contents($path, $response);
    echo $response;

Solution

  • It seems like the issue is with my destination of the request. The end point of the curl is written on Python Flask and it seems like if we send it like we do in php, flask dont understand it.

    So in php

    image[0] => 'image1.png'
    image[1] => 'image2.png'
    

    Can be valid and we will get both the files under image key in the request,

    in python they are coming in different keys like

    image[0] and image[1].

    If we are tring to look for image in the request it will give an error, but image[0] and image[1] as a string are working fine.

    The solution was to send the files as base 64encoded url in an associative array.

    P.S. I am not an expert in Python, so my explanation can be wrong. If some one knows python and is aware if this issue please comment here.

    Thank you.