Send File via cURL from Form POST in PHP
When handling file uploads from a form POST in PHP, it's essential to understand how to utilize cURL to send the file. Form markup usually includes a file input field with enctype="multipart/form-data".
To send a file using cURL with a POST request, use the following approach:
$post = array( 'image' => '@' . $_FILES['image']['tmp_name'] );
Initialize cURL:
$ch = curl_init();
Set cURL options:
curl_setopt($ch, CURLOPT_URL, 'http://example.com/curl_receiver.php'); curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
Execute the request:
curl_exec($ch);
Close cURL:
curl_close($ch);
On the receiving end, a script like curl_receiver.php can receive the file:
if (isset($_FILES['image'])) { move_uploaded_file($_FILES['image']['tmp_name'], 'uploads/'.$_FILES['image']['name']); } ?>
Example:
Form:
<form action="script.php" method="post" enctype="multipart/form-data"> <input type="file" name="image" /> <input type="submit" name="upload" value="Upload" /> </form>
Script (script.php):
if (isset($_POST['upload'])) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'http://example.com/curl_receiver.php'); curl_setopt($ch, CURLOPT_POSTFIELDS, array( 'image' => '@' . $_FILES['image']['tmp_name'] )); curl_exec($ch); curl_close($ch); }
Receiver Script (curl_receiver.php):
if (isset($_FILES['image'])) { move_uploaded_file($_FILES['image']['tmp_name'], 'uploads/'.$_FILES['image']['name']); }
The above is the detailed content of How to Send a File via cURL from a Form POST in PHP?. For more information, please follow other related articles on the PHP Chinese website!