0

I want to upload file from one server to another without using the file control and using Curl Request..

curl -X POST --header 'Content-Type: multipart/form-data' --header 'Accept: application/json' --header 'api-token: 6a53bcbe222c490196e4b9f87ba9148c' --header 'api-secret: 6a53bcbe222c490196e4b9f87ba9148c' -F "document[]=@C:/xampp/htdocs/project/image_name.ext" -F "document[]=@C:/xampp/htdocs/project/image_name.ext" -F "document[]=@C:/xampp/htdocs/project/image_name.ext" 'https://server_api_url.com

' The above curl works fine...

But i dont know how to post the file in php ... Below is sample code how i am sending post data using php curl

    <?php

       $doc_file_path_string = ' -F document[]=@image_name';
       array_push($doc_data_array, $doc_file_path_string);    


       $url = 'https://server_url.com'; 
       $ch = curl_init();
       curl_setopt($ch, CURLOPT_URL,$url);
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
       curl_setopt($ch, CURLOPT_POST, 1);
       curl_setopt($ch, CURLOPT_POSTFIELDS, implode(' ',$doc_data_array));
       $headers = array();
       $headers[] = "Content-Type: multipart/form-data";
       $headers[] = "Accept: application/json";
       $headers[] = "Api-Token: api_key";
       $headers[] = "Api-Secret: api_key ";
       curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
       echo $result = curl_exec($ch); 
    ?> 

1 Answers1

0

Here is how i did it

$url = <some url>;
$ch = curl_init();
$headers = ["Content-Type:multipart/form-data"];

// Define curl options
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);

// Here we make base64 encode for file content and push it into curl           
$base64 = base64_encode(file_get_contents(<path to file>));
curl_setopt($ch, CURLOPT_POSTFIELDS, ['file' => $base64]);

// Make request
$response = curl_exec($ch);
curl_close($ch);
Den Kison
  • 1,074
  • 2
  • 13
  • 28