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
Linda HamiltonOriginal
2024-11-09 17:08:02903browse

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']
);
  1. Initialize cURL:

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

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

    curl_exec($ch);
  4. Close cURL:

    curl_close($ch);

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

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>

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);
}

Receiver Script (curl_receiver.php):

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

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!

Statement:
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