This question deals with handling file uploads from a form POST request via cURL. The markup for the form is straightforward:
<form action="" method="post" enctype="multipart/form-data"> <input type="file" name="image">
To handle file uploads on the server-side, you need to use PHP's $_FILES global variable. This variable will contain an array of information about the uploaded files, including their temporary file names and original file names.
The following code snippet shows how to use $_FILES to get information about the uploaded image:
if (isset($_POST['upload'])) { $tmpFileName = $_FILES['image']['tmp_name']; $originalFileName = $_FILES['image']['name']; }
To send the file via cURL, you need to specify the CURLOPT_INFILE option and set it to the temporary file name. You also need to set the CURLOPT_UPLOAD option to 1. For example:
$curl = curl_init(); curl_setopt($curl, CURLOPT_URL, "http://example.com/upload.php"); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_INFILE, $tmpFileName); curl_setopt($curl, CURLOPT_UPLOAD, 1); $curlResult = curl_exec($curl); curl_close($curl);
On the receiving server, you can use the following code to receive the uploaded file:
<?php // Get the file from the request $file = file_get_contents('php://input'); // Save the file to a temporary location $tmpFileName = tempnam(sys_get_temp_dir(), 'phpexec'); file_put_contents($tmpFileName, $file); // You can now process the file as needed // Delete the temporary file unlink($tmpFileName); ?>
The above is the detailed content of How to Upload Files Using cURL from a HTML Form POST in PHP?. For more information, please follow other related articles on the PHP Chinese website!