从表单 POST 上传 PHP Curl 文件
使用 POST 表单上传文件可能具有挑战性,尤其是在服务器端使用 cURL 时。要解决这个问题,请考虑以下方法:
服务器端 cURL 实现
要处理文件上传并通过 cURL 发送它们,您可以利用 PHP 的 $_FILES 超全局,它提供有关上传文件的信息。下面是演示该过程的代码片段:
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); }
接收脚本 (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']); } ?>
以上是如何使用 PHP cURL 从表单 POST 上传文件?的详细内容。更多信息请关注PHP中文网其他相关文章!