using imgur api v3 to upload images anonymously using php

只愿长相守 提交于 2019-11-29 21:53:26

Sending the client_id in a post variable is the problem. It needs to be sent in the request header. Also, you're requesting a JSON response, but trying to parse it as XML.

<?php

$client_id = "FILLMEIN";
$image = file_get_contents("img/cool.jpg");

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.imgur.com/3/image.json');
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Client-ID ' . $client_id));
curl_setopt($ch, CURLOPT_POSTFIELDS, array('image' => base64_encode($image)));

$reply = curl_exec($ch);
curl_close($ch);

$reply = json_decode($reply);
printf('<img height="180" src="%s" >', $reply->data->link);

update 1

Live functional example with and source based on this code with debug output.

found the error, I need to send authorization details as header, eg code

<?php
$client_id = 'xxxxxxxx';

$file = file_get_contents("test-image.png");

$url = 'https://api.imgur.com/3/image.json';
$headers = array("Authorization: Client-ID $client_id");
$pvars  = array('image' => base64_encode($file));

$curl = curl_init();

curl_setopt_array($curl, array(
   CURLOPT_URL=> $url,
   CURLOPT_TIMEOUT => 30,
   CURLOPT_POST => 1,
   CURLOPT_RETURNTRANSFER => 1,
   CURLOPT_HTTPHEADER => $headers,
   CURLOPT_POSTFIELDS => $pvars
));

$json_returned = curl_exec($curl); // blank response
echo "Result: " . $json_returned ;

curl_close ($curl); 

?>

If you have problem with above script, try the curl skip verified SSL like this:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!