Uploading multiple files with PHP cURL

2267 views 7 months ago PHP

Once I was working in the project where I needed to create PHP cURL request with multiple file option. After I have done it, I thought it is good idea to share code with all of you.

In this article, we will create PHP cURL POST request that will include multiple files.

<?php
// request URL
$url = 'http://requesturl.com/api/request';
$data = array();
$data['username'] = 'username';
$data['email'] = '[email protected]';
// create array of files
$i = 0;
foreach ($files as $key => $document) {
    // create a CURLFile object
    $single_file = curl_file_create($file);
    $data['documents'][$i] = $single_file;
    $i++;
}
// create curl POST request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
    'Content-Type: multipart/form-data'
]);
// execute curl request
$response_json = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
    var_dump($err);
} else {
    $response = json_decode($response_json, 1);
}
var_dump($response);

Conclusion

In this way, you can also add files to PHP cURL request. For more options, go to the Documentation.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]