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

How to Upload Files Using cURL in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-12-31 20:07:101045browse

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

For earlier PHP versions, use:

$cFile = '@' . realpath($file_name_with_full_path);

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

3. Initialize the cURL Session

$ch = curl_init();

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

5. Execute the Request

Send the file using cURL:

$result = curl_exec ($ch);

6. Close the cURL Session

curl_close ($ch);

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!

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