Get Imgur JSON data with URL

1k views Asked by At

I'm looking at the imgur API and I'm trying to get the imgur JSON data through the following API method:

https://api.imgur.com/models/image

I have already registered my client ID, but have no idea how I would get the JSON data from the URL https://api.imgur.com/3/image/{id} (given the ID).

How would I get this data using cURL and PHP?

Here's what I tried, but it obviously doesn't work:

function getImageData() {
    $client_id = "<CLIENT_ID>";

    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,'https://api.imgur.com/3/image/SbBGk');
    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));
    curl_exec($ch);
    $lastUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
    curl_close($ch);

    return $lastUrl;
}
1

There are 1 answers

0
slapyo On BEST ANSWER

This will return the data.

function getImageData() {
    $client_id = "<CLIENT_ID>";

    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,'https://api.imgur.com/3/image/SbBGk');
    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);

    return $result;
}

To get the id of the image or gallery you need to parse the url with regex. I'm not good with regex, but this should help you. I'm certain there is a better solution to this.

preg_match('#(http(s)?:\/\/(www.|i.)?imgur.com)\/(?!a)(gallery\/)?(([-|~_0-9A-Za-z]+)&?.*?)#i', $link, $matches);
$id = $matches[6];