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

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

Linda Hamilton
Release: 2024-11-09 09:16:02
Original
721 people have browsed it

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

Send File via cURL from Form POST in PHP

Handling file uploads from form posts is a common task in API development. This question explores how to send a file via cURL using a PHP script.

The HTML form includes a file upload input field:

<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

The server-side PHP script (script.php) first checks if the "upload" button was clicked:

if (isset($_POST['upload'])) {
  // Handle file upload with cURL
}
Copy after login

To send the file with cURL, we need to set the following parameters:

  • CURLOPT_URL: The URL of the remote file upload destination
  • CURLOPT_UPLOAD: 1 (Indicates that the request contains a file upload)
  • CURLOPT_INFILE: The file pointer of the temporary file uploaded to the server
  • CURLOPT_INFILESIZE: The size of the file in bytes

Here's a sample cURL code snippet that sends the file:

$localFile = $_FILES['image']['tmp_name']; 
$url = "https://example.com/file_upload.php";

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('file' => '@' . $localFile);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
Copy after login

On the receiving end, the script should handle the file upload and store it accordingly. Here's an example:

$file = $_FILES['file'];
$fileName = $file['name'];
$fileTmpName = $file['tmp_name'];
move_uploaded_file($fileTmpName, '/path/to/uploads/' . $fileName);
Copy after login

The above is the detailed content of How to Send a File via cURL from a PHP 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template