Home >Backend Development >PHP Tutorial >How to Upload Files via cURL in PHP?

How to Upload Files via cURL in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-11-07 13:42:03998browse

How to Upload Files via cURL in PHP?

Uploading Files via cURL in PHP

Problem

Handling file uploads from a form POST in PHP and sending them using cURL can be challenging. The HTML form uses the multipart/form-data encoding, but the exact format for uploading files in a cURL request remains unclear.

Solution

To upload files using cURL in PHP, follow these steps:

Creating the cURL Request

<?php
// Define the file to be uploaded
$fileKey = 'image';
$tmpFile = $_FILES[$fileKey]['tmp_name'];
$fileName = $_FILES[$fileKey]['name'];

// Initialize cURL
$ch = curl_init();

// Set cURL options
curl_setopt_array($ch, [
    CURLOPT_URL => 'https://your-api-endpoint.com', // Replace with your API endpoint
    CURLOPT_USERPWD => 'username:password', // Replace with your API credentials
    CURLOPT_UPLOAD => true,
    CURLOPT_INFILE => fopen($tmpFile, 'r'), // Open the file for reading
    CURLOPT_INFILESIZE => filesize($tmpFile),
]);

**Sending the Request**

// Execute the cURL request
$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'Error sending file: ' . curl_error($ch);
} else {
    // Handle the response
    echo 'File uploaded successfully.';
}

// Close the cURL connection
curl_close($ch);
?>

Receiving the File

For the receiving script (curl_receiver.php), you can use the following code:

<?php
// Get the file data
$file = fopen('php://input', 'rb');

// Save the file to a temporary location
$tempFile = tempnam(sys_get_temp_dir(), 'file');
file_put_contents($tempFile, $file);

// Do something with the file
// ...

// Clean up
fclose($file);
unlink($tempFile);
?>

By using these steps, you can successfully upload files from a form POST in PHP using cURL.

The above is the detailed content of How to Upload Files via cURL 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