How to Upload Files Using PHP cURL from a Form POST?

DDD
Release: 2024-11-07 09:09:02
Original
199 people have browsed it

How to Upload Files Using PHP cURL from a Form POST?

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);
}
Copy after login

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']);
}
?>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!