Home >Backend Development >PHP Tutorial >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>
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>
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!