W3docs

how to upload file using curl with PHP

To upload a file using cURL in PHP, you can use the curl_setopt function to specify the CURLOPT_POSTFIELDS option with the file data.

To upload a file using cURL in PHP, you should use the CURLFile class to properly format the request as multipart/form-data. This ensures the receiving server correctly parses the file metadata (name, MIME type) and stores it in the $_FILES superglobal.

Here's an example of how you can do this:

How to upload a file using curl with PHP?

<?php

// Define the file path
$filePath = "file.txt";

// Create a CURLFile object (handles MIME type and filename automatically)
$file = new CURLFile($filePath);

// Set up cURL
$ch = curl_init();

// Set the URL
curl_setopt($ch, CURLOPT_URL, "http://example.com/upload");

// Set the HTTP method to POST
curl_setopt($ch, CURLOPT_POST, true);

// Set the POST data with the file
curl_setopt($ch, CURLOPT_POSTFIELDS, [
    'file' => $file
]);

// Execute the cURL request
$response = curl_exec($ch);

// Check for errors
if (curl_errno($ch)) {
    echo 'cURL error: ' . curl_error($ch);
}

// Close the cURL handle
curl_close($ch);

?>

<div class="alert alert-info flex not-prose"> <img src="/images/svg/youtube.svg" alt="Watch a course" class="w-5 h-5 mr-2"> <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

This will send a properly formatted multipart/form-data POST request to http://example.com/upload. The server can then access the uploaded file via $_FILES['file'].