Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image upload CURL command to PHP Curl

I am pretty new to PHP CURL and was trying to call an API to do image upload (multiple files at a time). API documentation has given the below example in CURL. I have tested and it is working.

curl -H "Authorization: Bearer 123456789" -i -X POST -F "whitespace=1" \
 -F "imageData[]=@/path/to/images/milk.jpg" \
 -F "imageData[]=@/path/to/images/peas.jpg" \
 https://mytestapi.com/1.0/uploadimages

Now I need to convert it to PHP Curl. For some reason, I am always getting error "imageData" param invalid. Can someone please help

$token = '123456789';
$imgUrl = 'https://mytestapi.com/1.0/uploadimages';


$data_to_post = array();
$data_to_post['whitespace'] = '1';
$data_to_post['imageData[]'] = '@/path/to/images/milk.jpg';
$data_to_post['imageData[]'] = '@/path/to/images/peas.jpg';


$curl = curl_init($imgUrl);
curl_setopt($curl, CURLOPT_HTTPHEADER, ['Authorization: Bearer '.$token]);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl,CURLOPT_POST, 1);
curl_setopt($curl,CURLOPT_POSTFIELDS, $data_to_post);
$data = json_decode(curl_exec($curl));
$responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);

var_dump($data);
like image 730
user1263019 Avatar asked Dec 25 '15 04:12

user1263019


1 Answers

Try to give full path of image instead of '@/path/to/images/milk.jpg';

Here is Updated code :

$token = '123456789';
$imgUrl = 'https://mytestapi.com/1.0/uploadimages';


$data_to_post = array();
$data_to_post['whitespace'] = '1';
$data_to_post['imageData'][] = "@".$imgUrl.'/path/to/images/milk.jpg';
$data_to_post['imageData'][] = "@".$imgUrl.'/path/to/images/peas.jpg';


$curl = curl_init($imgUrl);
curl_setopt($curl, CURLOPT_HTTPHEADER, ['Authorization: Bearer '.$token]);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl,CURLOPT_POST, 1);
curl_setopt($curl,CURLOPT_POSTFIELDS, $data_to_post);
$data = json_decode(curl_exec($curl));
$responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);

var_dump($data);

Please let me know if this not work.

like image 167
Bhavin Solanki Avatar answered Sep 27 '22 21:09

Bhavin Solanki