How to Use PHP cURL to Upload Files: A Complete Guide

How to Use PHP cURL to Upload Files: A Complete Guide

Introduction

Uploading files via PHP is a common requirement when working with APIs, cloud storage, or remote servers. cURL (Client URL) is a powerful tool that allows developers to send HTTP requests, including file uploads, to external services.

Using cURL for file uploads ensures flexibility, compatibility with API endpoints, and better control over the upload process compared to traditional HTML forms.

In this guide, you’ll learn how to:

Upload a single file using cURL
Upload multiple files in a single request
Handle API authentication during file uploads
Optimize file uploads for better performance
Debug and handle errors properly

1. Setting Up PHP cURL for File Uploads

Before proceeding, ensure that cURL is enabled in your PHP installation. Run the following command to check:

php -m | grep curl

If cURL is not installed, enable it in php.ini by uncommenting:

extension=curl

Restart your web server to apply the changes.

2. Uploading a Single File Using PHP cURL

The most common use case for cURL is uploading a single file to a remote server or API.

Example: Uploading a Single File via cURL

$url = "https://example.com/upload";  // Replace with your API endpoint
$filePath = "path/to/your/file.jpg";  

$curlFile = new CURLFile($filePath, mime_content_type($filePath), basename($filePath));

$data = ['file' => $curlFile];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Content-Type: multipart/form-data"
]);

$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo "cURL Error: " . curl_error($ch);
}

curl_close($ch);

echo $response;

Explanation:

CURLFile is used to prepare the file for upload.
CURLOPT_POSTFIELDS sends the file data.
CURLOPT_HTTPHEADER ensures the correct content type.

Always use mime_content_type() to detect the correct MIME type dynamically.

3. Uploading Multiple Files Using PHP cURL

Some APIs support batch uploads, allowing multiple files in a single request.

Example: Uploading Multiple Files

$url = "https://example.com/upload";  
$file1 = "path/to/file1.jpg";  
$file2 = "path/to/file2.png";  

$data = [
    'file1' => new CURLFile($file1, mime_content_type($file1), basename($file1)),
    'file2' => new CURLFile($file2, mime_content_type($file2), basename($file2))
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Content-Type: multipart/form-data"
]);

$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo "cURL Error: " . curl_error($ch);
}

curl_close($ch);

echo $response;

Key Differences from Single File Upload:

✅ Multiple CURLFile objects are added to the $data array.
✅ The API should support multiple files under different field names (e.g., file1, file2).

Best Practice: When sending a large number of files, compress them into a ZIP before uploading to reduce request size.

4. Uploading Files with Authentication (API Key or Bearer Token)

Many APIs require authentication (e.g., API keys, tokens) before allowing file uploads.

Example: Uploading a File with a Bearer Token

$url = "https://example.com/upload";  
$filePath = "path/to/your/file.jpg";  
$apiToken = "your_api_token_here";

$curlFile = new CURLFile($filePath, mime_content_type($filePath), basename($filePath));

$data = ['file' => $curlFile];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Content-Type: multipart/form-data",
    "Authorization: Bearer $apiToken"
]);

$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo "cURL Error: " . curl_error($ch);
}

curl_close($ch);

echo $response;

Always use secure authentication methods such as API tokens instead of passing credentials in the URL.

5. Handling File Upload Errors in cURL

When uploading files, handle errors properly to prevent silent failures.

Example: Handling Upload Errors

$response = curl_exec($ch);

if ($response === false) {
    echo "cURL Error: " . curl_error($ch);
    curl_close($ch);
    exit();
}

$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode != 200) {
    echo "Error: Upload failed with HTTP code " . $httpCode;
} else {
    echo "File uploaded successfully!";
}

Always check HTTP status codes to confirm if the upload was successful.

6. Optimizing File Upload Performance with cURL

Large file uploads can cause performance issues. Follow these optimizations:

Use chunked uploads if the API supports it.
Compress large files before uploading.
Set a timeout to prevent infinite requests:

curl_setopt($ch, CURLOPT_TIMEOUT, 60);

Use efficient error handling to retry failed uploads.

Best Practices for cURL File Uploads in PHP

Use CURLFile instead of older @ notation for security.
Verify the response to confirm successful uploads.
Authenticate API requests with Bearer tokens or API keys.
Handle large file uploads efficiently with compression or chunking.
Monitor request timeouts to avoid hanging uploads.

Conclusion

Using PHP cURL to upload files is a powerful and flexible way to interact with APIs and remote servers. Whether handling single or multiple files, authentication, or error handling, understanding cURL optimizations ensures faster and more reliable file uploads.

By following best practices, you can make secure, efficient, and scalable file upload implementations in your PHP applications. 🚀

Leave a Reply