Your browser (Internet Explorer 6) is out of date. It has known security flaws and may not display all features of this and other websites. Learn how to update your browser.

[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 = '';

// 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); 

Hope this helps someone!

comments powered by Disqus