How to Send Multiple Images in a cURL POST Request?

Mary-Kate Olsen
Release: 2024-11-02 23:21:30
Original
363 people have browsed it

How to Send Multiple Images in a cURL POST Request?

Using Arrays in cURL POST Requests

In an attempt to send an array of images using cURL, users may encounter issues where only the first array value is transmitted. This question explores how to rectify this problem.

The original code appears to have a minor flaw in the array structure. To resolve this, it's recommended to use http_build_query to correctly format the array:

<code class="php">$fields = array(
    'username' => "annonymous",
    'api_key' => urlencode("1234"),
    'images' => array(
        urlencode(base64_encode('image1')),
        urlencode(base64_encode('image2'))
    )
);

$fields_string = http_build_query($fields);</code>
Copy after login

This modification ensures that the array is correctly encoded into a query string. The updated code below incorporates this change:

<code class="php">extract($_POST);

$url = 'http://api.example.com/api';
$fields = array(
    'username' => "annonymous",
    'api_key' => urlencode("1234"),
    'images' => array(
        urlencode(base64_encode('image1')),
        urlencode(base64_encode('image2'))
    )
);

$fields_string = http_build_query($fields);

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);

$result = curl_exec($ch);
echo $result;

curl_close($ch);</code>
Copy after login

With this updated code, the array of images will be correctly sent in the POST request. The API will receive both images as expected.

The above is the detailed content of How to Send Multiple Images in a cURL POST Request?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template