Uploading Files with Ease: A Guide to Sending Files via POST with cURL in PHP

Sending files through POST with cURL and PHP is a vital skill in web development. Whether you’re managing user-generated content or transferring data between applications, understanding file uploads is crucial.

Creating the HTML Form

Let’s start with a user-friendly HTML form. This form allows users to select the file they want to upload. Here’s how it looks:

<!DOCTYPE html>
<html>
    <head>
        <title>File Upload Demo</title>
    </head>
    <body>
        <h1>File Upload Demo</h1>

        <form action="upload.php" method="POST" enctype="multipart/form-data">
            <input type="file" name="fileToUpload" id="fileToUpload">
            <input type="submit" value="Upload File" name="submit">
        </form>
    </body>
</html>

Handle the File Upload in PHP

Now, let’s dive into the PHP script to handle the file upload. We’ll create a file called upload.php. First, we check if a file was selected and if any errors occurred during the upload process. Then, we handle the upload:

<?php
if(isset($_FILES['fileToUpload']) && $_FILES['fileToUpload']['error'] === UPLOAD_ERR_OK) {
  $file = $_FILES['fileToUpload']['tmp_name'];
  $filename = $_FILES['fileToUpload']['name'];
  $targetPath = 'uploads/' . $filename;

  if(move_uploaded_file($file, $targetPath)) {
    echo "File uploaded successfully!";
  } else {
    echo "Error uploading the file.";
  }
} else {
  echo "No file selected or an error occurred.";
}
?>

Sending Files via POST with cURL

Finally, let’s send the file to a remote server using cURL. We create a new cURL request, set the necessary options, and execute it:

<?php
$file = 'path/to/your/file.jpg';
$url = 'http://example.com/upload.php';

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, [
  'fileToUpload' => new CURLFile($file)
]);

$response = curl_exec($curl);
curl_close($curl);

echo $response;
?>

In conclusion, this tutorial has equipped you with the knowledge to upload files using cURL. The HTML form allows file selection, and the PHP script manages the upload process. With cURL, sending files to a remote server becomes seamless. Feel free to adapt these examples to suit your needs and explore additional cURL features.