PHP Curl File Upload from Form POST
Uploading files with POST forms can be challenging, especially when using cURL on the server-side. To address this, consider the following approach:
Server-Side cURL Implementation
To handle file uploads and send them via cURL, you can utilize PHP's $_FILES superglobal, which provides information about uploaded files. Here's a code snippet that demonstrates the process:
if (isset($_POST['upload'])) { $fileKey = 'image'; // Assuming your file input has 'image' as its name // Retrieve file information $tmpFile = $_FILES[$fileKey]['tmp_name']; $fileName = $_FILES[$fileKey]['name']; // Prepare cURL parameters $postFields = ['file' => '@' . $tmpFile, /* Other post parameters if needed */]; $url = 'https://example.com/curl_receiver.php'; // URL to send the file to // Initialize and configure cURL $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Execute cURL request $result = curl_exec($ch); // Handle cURL response if (curl_errno($ch)) { // Handle error } else { // Success, do further processing with $result } // Close cURL connection curl_close($ch); }
Receiving Script (curl_receiver.php)
<?php // Handle incoming POST data if (!empty($_FILES)) { // Retrieve file information $tmpFile = $_FILES['file']['tmp_name']; $fileName = $_FILES['file']['name']; // Process and save the uploaded file // ... // Send response to the client echo json_encode(['status' => 'success']); } else { // Handle error, no file uploaded echo json_encode(['status' => 'error', 'message' => 'No file uploaded']); } ?>
The above is the detailed content of How to Upload Files Using PHP cURL from a Form POST?. For more information, please follow other related articles on the PHP Chinese website!