PHP: Upload Files(s) Using Curl

Here I share a code snippet that will show how can we use PHP curl to upload file to remote server as HTTP POST request. We can upload multiple files using this code. It handles PHP versions to prior to 5.6 as well as PHP versions 5.5 and later.

<?php

// URL to which files to be uploaded.
$url = "http://example.com/upload";

// Puts files to be uploaded in this array
$files = array(
  '/path/to/file/one.png',
  '/path/to/file/two.jpg',
);

$postfields = array();

foreach ($files as $index => $file) {
  if (function_exists('curl_file_create')) { // For PHP 5.5+
    $file = curl_file_create($file);
  } else {
    $file = '@' . realpath($file);
  }
  $postfields["file_$index"] = $file;
}

// Add other post data as well.
$postfields['name'] = 'Name';
// Need to set this head for uploading file.
$headers = array("Content-Type" => "multipart/form-data");

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

$response = curl_exec($ch);

if(!curl_errno($ch))
{
    $info = curl_getinfo($ch);
    if ($info['http_code'] == 200) {
      // Files uploaded successfully.
    }
}
else
{
  // Error happened
  $error_message = curl_error($ch);
}
curl_close($ch);