Upload multiple files with curl Upload multiple files with curl curl curl

Upload multiple files with curl


PHP 5.5+ has a function to create files without using CURLFile: curl_file_create.

You can upload multiple files like this:

<?php$files = [    '/var/file/something.txt',    '/home/another_file.txt',];// Set postdata array$postData = ['somevar' => 'hello'];// Create array of files to postforeach ($files as $index => $file) {    $postData['file[' . $index . ']'] = curl_file_create(        realpath($file),        mime_content_type($file),        basename($file)    );}$request = curl_init('https://localhost/upload');curl_setopt($request, CURLOPT_POST, true);curl_setopt($request, CURLOPT_POSTFIELDS, $postData);curl_setopt($request, CURLOPT_RETURNTRANSFER, true);$result = curl_exec($request);if ($result === false) {    error_log(curl_error($request));}curl_close($request);

This will be received on the server as an array under file the same as if there was a posted form, this is $_FILES:

Array(    [file] => Array        (            [name] => Array                (                    [0] => 1.txt                    [1] => 2.txt                )            [type] => Array                (                    [0] => text/plain                    [1] => text/plain                )            [tmp_name] => Array                (                    [0] => /private/var/folders/cq/7262ntt15mqdmylblg9p1wf80000gn/T/phpp8SsKD                    [1] => /private/var/folders/cq/7262ntt15mqdmylblg9p1wf80000gn/T/php73ijEP                )            [error] => Array                (                    [0] => 0                    [1] => 0                )            [size] => Array                (                    [0] => 6                    [1] => 6                )        ))

This is $_POST:

Array(    [somevar] => hello)