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

How to Upload Files Using cURL in PHP?

Barbara Streisand
Release: 2024-12-31 20:07:10
Original
1011 people have browsed it

How to Upload Files Using cURL in PHP?

Uploading Files with cURL in PHP

To upload a file in PHP using cURL, follow these steps:

1. Create a cURL File Object

For PHP 5.5 and above, use curl_file_create to create a cURL file object:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
}
Copy after login

For earlier PHP versions, use:

$cFile = '@' . realpath($file_name_with_full_path);
Copy after login

2. Prepare the POST Data

Package the file object and any additional form data in a POST array:

$post = array('extra_info' => '123456', 'file_contents' => $cFile);
Copy after login

3. Initialize the cURL Session

$ch = curl_init();
Copy after login

4. Set the cURL Options

Configure the cURL session options:

curl_setopt($ch, CURLOPT_URL, $target_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
Copy after login

5. Execute the Request

Send the file using cURL:

$result = curl_exec ($ch);
Copy after login

6. Close the cURL Session

curl_close ($ch);
Copy after login

Important Note for PHP 5.5 and Above:

Deprecated file handling methods are used in the provided example. For current practices, refer to the PHP documentation: https://wiki.php.net/rfc/curl-file-upload

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