Home >Backend Development >PHP Tutorial >How to Send a File via cURL from a PHP Form POST?
Send File via cURL from Form POST in PHP
Handling file uploads from form posts is a common task in API development. This question explores how to send a file via cURL using a PHP script.
The HTML form includes a file upload input field:
<form action="script.php" method="post" enctype="multipart/form-data"> <input type="file" name="image"> <input type="submit" name="upload" value="Upload"> </form>
The server-side PHP script (script.php) first checks if the "upload" button was clicked:
if (isset($_POST['upload'])) { // Handle file upload with cURL }
To send the file with cURL, we need to set the following parameters:
Here's a sample cURL code snippet that sends the file:
$localFile = $_FILES['image']['tmp_name']; $url = "https://example.com/file_upload.php"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, array('file' => '@' . $localFile); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($ch); curl_close($ch);
On the receiving end, the script should handle the file upload and store it accordingly. Here's an example:
$file = $_FILES['file']; $fileName = $file['name']; $fileTmpName = $file['tmp_name']; move_uploaded_file($fileTmpName, '/path/to/uploads/' . $fileName);
The above is the detailed content of How to Send a File via cURL from a PHP Form POST?. For more information, please follow other related articles on the PHP Chinese website!