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="#00FF00" size="7">Uploaded</font></p>'; if (move_uploaded_file ($_FILES["userfile"]["tmp_name"], $uploadfile)) echo $uploadfile; else echo '<p><font color="#FF0000" size="7">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:
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!