Home >Backend Development >PHP Tutorial >How to Upload Files Using cURL from a HTML Form POST in PHP?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-10 14:09:02442browse

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

Uploading Files via cURL from a Form POST in PHP

Overview

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">

Handling File Uploads on the Server

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

Sending the File via cURL

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

Receiving File on Server

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!

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