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?

5
  • 2
    can you specify "but it doesn't work"? Commented Apr 30, 2018 at 23:28
  • 3
    Possible duplicate of how to upload file using curl with php Commented Apr 30, 2018 at 23:29
  • the 'Content-Type: application/json' seems strange to me (for sending a file) Commented Apr 30, 2018 at 23:30
  • Did you do any research? I found many posts about this, just searching for "php curl send file" on google Commented Apr 30, 2018 at 23:30
  • @Jeff yes it was the problem using that Content-Type, thanks for your help :) Commented May 1, 2018 at 16:58

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.