[Solved] Uploading image via API in PHP
I was very busy working on a terrible bug that would not allow merchants filter their transactions while my colleague was hitting his head on the wall fixing image upload for an API that already works with our mobile apps.
I got distracted different times attempting to help him out but the persistent calls from our merchants would not let me give it a thought. After getting my bug fixed, I jumped on the issue like a lion deprived of food. Below is my solution and it works.
$url = 'http://uload-url.com/upload';
# http://php.net/manual/en/curlfile.construct.php
// Create a CURLFile object / procedural method
$cfile = curl_file_create('test.jpg','image/png','testpic'); // try adding
// Create a CURLFile object / oop method
#$cfile = new CURLFile('resource/test.png','image/png','testpic'); // uncomment and use if the upper procedural method is not working.
// Assign POST data
$imgdata = array('image' => $cfile);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_USERAGENT,'Opera/9.80 (Windows NT 6.2; Win64; x64) Presto/2.12.388 Version/12.15');
curl_setopt($curl, CURLOPT_HTTPHEADER,array('User-Agent: Opera/9.80 (Windows NT 6.2; Win64; x64) Presto/2.12.388 Version/12.15','Referer: http://someaddress.tld','Content-Type: multipart/form-data'));
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // stop verifying certificate
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true); // enable posting
curl_setopt($curl, CURLOPT_POSTFIELDS, $imgdata); // post images
$r = curl_exec($curl);
curl_close($curl);
Hope this helps someone!