Home > Backend Development > PHP Tutorial > How to Send a File via cURL from a Form POST in PHP?

How to Send a File via cURL from a Form POST in PHP?

Linda Hamilton
Release: 2024-11-09 17:08:02
Original
892 people have browsed it

How to Send a File via cURL from a Form POST in PHP?

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:

  1. Retrieve the file path: Use $_FILES'image' to obtain the temporary file path on the server.
  2. Prepare the cURL parameters: Construct an array with the file details. E.g.:
$post = array(
    'image' => '@' . $_FILES['image']['tmp_name']
);
Copy after login
  1. Initialize cURL:

    $ch = curl_init();
    Copy after login
  2. Set cURL options:

    curl_setopt($ch, CURLOPT_URL, 'http://example.com/curl_receiver.php');
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    Copy after login
  3. Execute the request:

    curl_exec($ch);
    Copy after login
  4. Close cURL:

    curl_close($ch);
    Copy after login

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

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>
Copy after login

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

Receiver Script (curl_receiver.php):

if (isset($_FILES['image'])) {
    move_uploaded_file($_FILES['image']['tmp_name'], 'uploads/'.$_FILES['image']['name']);
}
Copy after login

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template