How to upload a file from one server to another server using PHP cURL POST method.
The cURL functions in PHP can be used to make HTTP requests to remote servers.
The curl_setopt method allows us a wide range of options to be set, but no one of them directly related to send files.
But we can send files using cURL with special format for POST parameter values.
Following script is usefull in sending a binary file via cURL.
This code will make a request to http://demo.phpmysqlquery.com/, uploads the file demo.txt, and return the output as response.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?php //send-file-using-curl.php $destination_url = 'demo.phpmysqlquery.com/get-file-using-curl.php'; //This needs to be the full path to the file you want to send. $file_name_with_full_path = realpath('demo.txt'); /* curl will accept parameters in array * Take note that the 'key' in the array will be the key that shows up in the post values * Add an “at” sign (@) before the file path makes sure that cURL sends the file as part of a “multipart/form-data” post. * Exactly what we needed. */ $post = array('file_info' => 'Test File','fileToUpload'=>'@'.$file_name_with_full_path); // initialise the curl request $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$destination_url); curl_setopt($ch, CURLOPT_POST,1); curl_setopt($ch, CURLOPT_POSTFIELDS, $post); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); $result=curl_exec($ch); curl_close ($ch); echo $result; ?> |
And now here is the corresponding script on destination server to accept the file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php $upload_dir = realpath('./') . '/'; $upload_file_path = $upload_dir . basename($_FILES['fileToUpload']['name']); if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $upload_file_path)) { echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded successfully."; } else { echo "Sorry, there was an error uploading your file."; } //echo '<pre>'; //echo 'Try for the debugging purpose :'; //print_r($_FILES); //print_r($_POST); ?> |
Note :We can transfer any type of files like photo(.png,.jpg), .xls and .csv files from one server to another server using this script.