Wednesday, March 15, 2017

How to get latest images from an instagram account easily

In a web project i've recently been involved in, i needed to get latest images from the instagram account of website owner. As i haven't made this before i've searched and visited many web pages and seen many examples mostly using the instagram api to get latest images of a given instagram account. However i didn't need users login using their own instagram account and show their own images on the website so i thought there must be another way to get publicly shared images from an instagram account. Finally i've seen that despite its not mentioned in instagram api docs there is another simple way without using any api and external code to get latest images from an instagram account.

I've found that you can get latest media of an instagram account as json by getting content of an url in this format:[user_id]/media/

Instead of [user_id] you must use the user id of instagram account. The result is a json data which includes many information about latest media from that user on instagram. As i see this url returns latest 20 media publicly shared from the instagram account.

You can use CURL to get contents of this url and parse using json_decode() function in php easily and get information you need from latest images. In my case i only needed image and links so i parsed only these information. Below is the php code i used to show latest instagram images on a web page:

$instagram = new Plugin_Instagram('instagram_account_user_id');
$images = $instagram->getMedia(3); // get only latest 3 images
foreach($images as $p){
// some html code here }

And here is the content of the class Plugin_Instagram i've written to get latest images from an instagram account:

class Plugin_Instagram {
public $user_id = '';
public function __construct($user_id) {
$this->user_id = $user_id;
public function getMedia($count=20){
$url = ''.$this->user_id.'/media/';
$json = $this->fetchData($url);
$data = json_decode($json);
return array();
$return = array(); $i=0;
foreach($data->items as $post){
$return[] = array(
'type'=>$post->type, 'img'=>$post->images->thumbnail->url,
return $return;
private function fetchData($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20); $result = curl_exec($ch);
return $result;

You can change the return array if you need more information about the latest images from instagram account.

No comments:

Post a Comment