Forwarding File Uploads with cURL in PHP
When a user uploads a file to your application, the data arrives in $_FILES as a temporary upload entry. Your initial script often handles storage logic safely using move_uploaded_file, but you may need to forward that same payload to another endpointâperhaps for archival, processing by a third-party service, or distribution across servers. The core challenge is reconstructing the multipart form data exactly so the receiving server accepts it as a fresh upload.
PHP's cURL extension provides the tools needed to re-post files without requiring the original client's HTML form. You must configure a POST request with CURLOPT_POST enabled and set CURLOPT_POSTFIELDS to a string that mimics the browser's multipart encoding. Simply passing the file path or raw binary data will fail; the boundary markers and headers are critical.
To construct the payload, you have two primary approaches depending on your PHP version and specific needs. The modern, recommended method involves using stream_context_create with CURLOPT_POSTFIELDS set to a string containing the form fields and the file attachment. Alternatively, older patterns used raw string concatenation, but this is error-prone because manual boundary generation can introduce subtle bugs.
Here is a practical implementation using the curl_file class introduced in PHP 5.5. This approach abstracts away the need to manually manage boundaries:
$upload_file = './uploads/remote_upload.bin'; // The file you just moved or received
$ch = curl_init('https://receiver-server.com/upload');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
'userfile' => [
'name' => basename($_FILES['userfile']['name']),
'type' => $_FILES['userfile']['type'],
'contents' => file_get_contents($_FILES['userfile']['tmp_name'])
]
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode === 200) {
echo "File forwarded successfully.";
} else {
echo "Forwarding failed with HTTP code: $httpCode";
}
curl_close($ch);
This example reads the file contents into memory and attaches them to the userfile field. While this works, it consumes RAM proportional to the file size. For large files, consider using a temporary stream or leveraging CURLOPT_INFILE if your receiving server accepts raw streams, though most standard APIs expect multipart boundaries.
A critical pitfall is authentication. If the original upload required cookies or a session token, you must include them in the cURL request. Use CURLOPT_COOKIEJAR to persist cookies from previous requests or explicitly set headers with CURLOPT_HTTPHEADER. Without these, the receiver server will reject the request as unauthenticated, even if the file data is valid.
Another consideration is error handling. Always check curl_errno() and curl_error() after execution. Network timeouts, SSL certificate issues on the receiving end, or strict Content-Type validation on the target server are common failure points. For example, some gateways reject requests where the Content-Type header does not match the file extension, even if the body is correct.
If you are building this within a Laravel application, the underlying cURL logic remains the same, but you might prefer using HTTP clients provided by the framework or leveraging queue jobs to handle heavy uploads asynchronously. For more complex scenarios involving chunked uploads or streaming large datasets, libraries like reactphp/http or Guzzle offer higher-level abstractions that manage boundaries and retries automatically.
Ultimately, success depends on mirroring the original upload request's structure. Ensure headers, content types, and authentication mechanisms match exactly what the receiver expects to avoid silent failures or data corruption.
