Search code examples
phpjsoncurlinstagram-api

How to get latest instagram posts using php


I want to get latest posts from my instagram account and I'm using this api url: https://api.instagram.com/v1/users/[USER_ID]/media/recent?access_token=[ACCESS_TOKEN]

When I paste this url in the browser I can see the string JSON but I can not find a way to decode it and use object properties. I'm using PHP and cURL for getting and decoding JSON. It always return NULL. My cURL function is this:

function fetchData($url){
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);     
  curl_setopt($ch, CURLOPT_URL, $url);
  $result = curl_exec($ch);
  curl_close($ch);
  return $result;
}

and at the end:

$url = https://api.instagram.com/v1/users/[USER_ID]/media/recent?access_token=[ACCESS_TOKEN]
$result = fetchData($url);
var_dump(json_decode($result));

what am I doing wrong here? I also tested file_get_contents instead or cURL but it gave me this error:

No connection could be made because the target machine actively refused it

Solution

  • The problem with this endpoint:

    https://api.instagram.com/v1/users/[USER_ID]/media/recent?access_token=[ACCESS_TOKEN]

    is that it is not possible to get public media with your own access token. One can only get self media with generated token. So the correct endpoint should be

    https://api.instagram.com/v1/users/self/media/recent?access_token=[ACCESS_TOKEN]

    this works on server and client, but because instagram access token must be secured I'm using server side script to get latest posts.