Acquiring images using Imgur API and PHP
I am new to php and I am trying to use the imgur API (my code is based on several tutorials). What I am trying to do is get an image from imgur displaying it on a webpage. So I am using this code
<?php
$client_id = '<ID>';
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,'https://api.imgur.com/3/image/rnXusiA');
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch,CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Client-ID ' . $client_id));
$result = curl_exec($ch);
curl_close($ch);
$json = json_decode($result, true);
?>
After converting $result
to an associative array, I am trying to access the data
$data = $json->data->link;
But there is $data
nothing in it and I get the error Trying to get property of non-object
. I'm guessing imgur didn't return any data. So what am I doing wrong?
source to share
I read more about curl
and rewrote the code.
<?php
$client_id = "<ID>";
$c_url = curl_init();
curl_setopt($c_url, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($c_url, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c_url, CURLOPT_URL,"https://api.imgur.com/3/image/rnXusiA");
curl_setopt($c_url, CURLOPT_HTTPHEADER, array('Authorization: Client-ID ' . $client_id));
$result=curl_exec($c_url);
curl_close($c_url);
$json_array = json_decode($result, true);
var_dump($json_array);
?>
This wokred and var_dump($json_array);
displayed the contents of the array.
$json_array['data']['link'];
gives a direct link to the image.
For the album, I changed the url to https://api.imgur.com/3/album/y1dZJ
and used a loop to get the image links
$image_array = $json_array["data"]["images"];
foreach ($image_array as $key => $value) {
echo $value["link"];
}
Hope this helps anyone familiar with the imgur API.
source to share