0

I have a string that representing a file path like this: D:/folder/another_folder/image_name.png.

I want to send this as a file using PHP curl I've doing this but it doesn't work

$ch = curl_init();   
if (function_exists('curl_file_create')) { // php 5.5+  
    $cFile = curl_file_create('D:/folder/another_folder/image_name.png');  
}else{  
    $cFile = '@' . realpath('D:/folder/another_folder/image_name.png');  
} 

$fields['userPhoto'] = $cFile;  
$fields['uploadedfrom'] = 'web';  

curl_setopt($ch, CURLOPT_URL, 'http://some_url.com');  
curl_setopt($ch, CURLOPT_POST, true);  
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));  
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);   
curl_setopt($ch, CURLOPT_HTTPHEADER, array(  
    'Content-Type: application/json'  
));  
$result = curl_exec($ch);  

curl_close($ch);  

the issue is I'm getting the file path from a csv file not browsing it
Can anyone help with this and tell me how to send a file through PHP CURL from a string?

Mohamed Salah
  • 156
  • 1
  • 15

1 Answers1

2

your problem here is that you're using json_encode. json_encode cannot encode CURLFile objects. also, JSON is not binary safe, so you can't send PNG files with json (PNG files contain binary data, for example including the FF/255 byte, which is illegal in json. that said, a common workaround is to encode binary data in base64, and send the base64 in json). stop using json, just give CURLOPT_POSTFIELD the array, and curl will encode it in the multipart/form-data-format, which is the de-facto standard for uploading files over the http protocol. going that route, you must also get rid of the Content-Type: application/json header, and curl will automatically insert Content-Type: multipart/form-data for you.

hanshenrik
  • 19,904
  • 4
  • 43
  • 89