Home >Backend Development >PHP Tutorial >How Can I Upload Files Using PHP and cURL?

How Can I Upload Files Using PHP and cURL?

DDD
DDDOriginal
2024-12-29 01:58:11926browse

How Can I Upload Files Using PHP and cURL?

Uploading Files using PHP and cURL

This question explores how to upload files using PHP, specifically using cURL. The user posts a file through a form to a PHP script, which then needs to forward it to another script. The PHP code provided for receiving and uploading the file is as follows:

echo"".$_FILES['userfile']."";
$uploaddir = './';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
if ( isset($_FILES["userfile"]) ) {
  echo '<p><font color=&quot;#00FF00&quot; size=&quot;7&quot;>Uploaded</font></p>';
  if (move_uploaded_file
($_FILES[&quot;userfile&quot;][&quot;tmp_name&quot;], $uploadfile))
echo $uploadfile;
else echo '<p><font color=&quot;#FF0000&quot; size=&quot;7&quot;>Failed</font></p>';
}

To send the file to the receiver server using cURL:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
} else { // 
  $cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

Additional Resources:

  • http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

Note for PHP 5.5 :

In PHP 5.5 , it's recommended to use the newer curl_file_upload RFC for file uploads. However, if using the deprecated approach, ensure curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false); is set.

The above is the detailed content of How Can I Upload Files Using PHP and cURL?. 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