How to upload a file to a remote server using cURL in PHP?

To upload a file to a remote server using cURL in PHP, you can follow these steps:

  1. Create a cURL resource using the curl_init function:
$curl = curl_init();
  1. Set the destination URL to the remote server using the curl_setopt function:
$uploadUrl = "http://example.com/upload.php"; curl_setopt($curl, CURLOPT_URL, $uploadUrl);
  1. Set the CURLOPT_RETURNTRANSFER option to true to return the response as a string:
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  1. Set the CURLOPT_POST option to true to specify that you want to upload a file using the POST method:
curl_setopt($curl, CURLOPT_POST, true);
  1. Set the file to upload using the CURLOPT_POSTFIELDS option, which takes an array in the form ['fileFieldName' => '@file/path']:
$fileField = 'file'; // Name of the file field in the upload form $filePath = '/path/to/file'; // Path to the file you want to upload $postFields = [ $fileField => '@' . $filePath ]; curl_setopt($curl, CURLOPT_POSTFIELDS, $postFields);
  1. Execute the cURL request using the curl_exec function:
$response = curl_exec($curl);
  1. Check for any cURL errors using the curl_errno function and handle them accordingly:
if(curl_errno($curl)){ $error = curl_error($curl); // Handle the error }
  1. Close the cURL resource using the curl_close function:
curl_close($curl);

That's it! You have uploaded a file to a remote server using cURL in PHP.