Get Images from Instagram with PHP
In this tutorial I will show you how you can interact with Instagram API in PHP and not only that – we’re also going to create and configure an app in “Meta for Developers”.

If you need any help with developing your custom web application which is going to interact with Instagram API, feel free to contact me and the team.
1. Create and Configure an Application
Creating an app
First of all visit this link developers.facebook.com/apps and hit a “Create App” button.
Select “Other”:

When selecting app type, choose “Consumer”:

Facebook will also ask you some details like contact email and application name and that’s pretty much it, the app is created!
Add platform
We are going to display photos from Instagram on a website, right? So let’s add this information to the app.
Go to App Settings > Basic, scroll to the very bottom of the page and hit “Add platform” button.

Don’t forget to provide a website URL and then hit “Save changes”.
Set up “Instagram Basic Display” product
It is kind of a child app to our parent app 😁
All right, from the dashboard select “Instagtam Basic Display”:

Once you created this “child app”, you will have the access to “Instagram App ID”, “Instagram App Secret” and “Valid OAuth Redirect URIs” setting. We are going to use all of those in our API interaction in the examples below.

In “Valid OAuth Redirect URIs” please provide exact URL of the page where we are going to display images from Instagram. If you don’t do that, in this step you will get “Invalid redirect_uri” error.
Add a test user and accept invitation from Instagram
Go to App roles > Roles and hit “App people” button.

Now it is time to confirm it in your Instagram account, in order to do so please go to instagram.com/accounts/manage_access then “Tester Invitations” tab and accept the invitation.

If you skip this step or do it incorrectly, you will get an error “Insufficient developer role” in the next step.
2. OAuth Authentication
Finally we’re done with the app and it is time to code something. And in this first OAuth step all we need to do is just to redirect users to the following URL:
https://api.instagram.com/oauth/authorize?client_id={Instagram APP ID}&redirect_uri={Redirect URI}&scope=user_profile,user_media&response_type=code
Let’s create a HTML link for that. I am also going to use a handy WordPress function add_query_arg()
which will help me to add query parameters to the URL.
<?php
$redirect = add_query_arg(
array(
'client_id' => '0000000012345678',
'redirect_uri' => 'https://rudrastyh.com/instagram',
'scope' => 'user_profile,user_media',
'response_type' => 'code',
),
'https://api.instagram.com/oauth/authorize'
);
?>
<a href="<?php echo $redirect ?>">Show Instagram Photos</a>
If you’ve done everything correctly, when you click the link, you should be redirected to Instagram website and the following OAuth dialog should appear:

When you hit “Allow” button, you’re going to be redirected to the URL provided in redirect_uri
parameter. Also ?code
URL parameter will be added at the end. In our case it is going to be something like https://rudrastyh.com/instagram?code=AQvhrlcor...#_
. We are about to use code
in the following step to get an access token.
3. Get Instagram Access Token
Now it is time to get an Instagram access token. The request structure is going to be like this:
curl -X POST \
https://api.instagram.com/oauth/access_token \
-F client_id={Instagram App ID} \
-F client_secret={Instagram App Secret} \
-F grant_type=authorization_code \
-F redirect_uri={Redirect URI} \
-F code={Code}
Since I am using PHP and this blog is pretty much about WordPress, for convenience I am going to use WordPress HTTP API functions, in this case – wp_remote_post()
.
if( isset( $_GET[ 'code' ] ) && $_GET[ 'code' ] ) {
$response = wp_remote_post(
'https://api.instagram.com/oauth/access_token',
array(
'body' => array(
'client_id' => '0000000012345678',
'client_secret' => '0000000000000000',
'grant_type' => 'authorization_code',
'redirect_uri' => 'https://rudrastyh.com/instagram',
'code' => $_GET[ 'code' ],
),
)
);
if( 'OK' === wp_remote_retrieve_response_message( $response ) ) {
$response = json_decode( wp_remote_retrieve_body( $response ), true );
$access_token = $response[ 'access_token' ];
}
}
Please note, that the authorization code we get from $_GET[ 'code' ]
can be used only once to get an access token, if you try to use it one more time, you will get an error “This authorization code has been used”.
Generate long-term access tokens
Please note, that the access token we generated above is a short-term one. It can be used only for 1 hour, after that it is getting expired. But, using the short-term token, you can generate a long-term (valid for 60 days) one with an additional API request.
curl -i -X GET 'https://graph.instagram.com/access_token?grant_type=ig_exchange_token&client_secret={Instagram App Secret}&access_token={Access Token}'
Or in a WordPress-way:
$response = wp_remote_get(
add_query_arg(
array(
'grant_type' => 'ig_exchange_token',
'client_secret' => '0000000000000000',
'access_token' => $access_token,
),
'https://graph.instagram.com/access_token'
)
);
if( 'OK' === wp_remote_retrieve_response_message( $response ) ) {
$response = json_decode( wp_remote_retrieve_body( $response ), true );
$access_token = $response[ 'access_token' ];
}
4. Get Images from Instagram
Finally, it is time to print some images from our Instagram feed!
curl -X GET 'https://graph.instagram.com/me/media?fields=media_url&access_token={Access Token}'
$response = wp_remote_get(
add_query_arg(
array(
'fields' => 'media_url',
'access_token' => $access_token,
),
'https://graph.instagram.com/me/media'
)
);
if( 'OK' === wp_remote_retrieve_response_message( $response ) ) {
$response = json_decode( wp_remote_retrieve_body( $response ), true );
foreach( $response[ 'data' ] as $media ) {
echo '<img src="' . $media[ 'media_url' ] . '" />';
}
}

Media fields
In the example above the only thing we get from Instagram API is the media URL. But sometimes when you get Instagram posts, you need more than that.
caption
,id
,media_type
– can beIMAGE
,VIDEO
andCAROUSEL_ALBUM
,media_url
,permalink
– link on Instagram,thumbnail_url
– thumbnail forVIDEO
type,timestamp
– date of the publication,username
– username of the author.
You can provide multiple fields comma separated like this:
$response = wp_remote_get(
add_query_arg(
array(
'fields' => 'media_url,permalink,timestamp',

Misha Rudrastyh
Hey guys and welcome to my website. For more than 10 years I've been doing my best to share with you some superb WordPress guides and tips for free.
Need some developer help? Contact me
This is the simplest script I’ve found to get photos via the Instagram API, and your instructions were the clearest. Thank you!!
Awesome post, the better one I have found that explain and help to get the Access token and without the need of other libraries.
Do you know if Is it necessary to submit the instagram app for review if you are only using it to grab the most recent photos from the instagram account to show them in the company website?
Thanks.
It is not necessary if you need to display no more than 20 recent photos.
Hi
It’s possible to send a Image and hashtag to the user timeline?
thanks
Hi,
I’m afraid this is not possible even with approved Instagram app.
Ok. Thanks!!
Hi,
When I follow the instructions and attempt to get an access token I receive this error:
“code”: 400,
“error_type”: “OAuthException”,
“error_message”: “Invalid Client ID
Why is this happening?
Thanks!
Hello,
this means that you input incorrect Client ID.
Great tutorial. I really enjoyed it. :)
I was wondering if you had the ability for a search function to populate images via hashtag?
Very nice..
Thanks!
Hey! Great post :)
I encountered a problem when trying to access the pictures posted with a tag from a specific account. I got back an OAuthPermissionException that I’m not sure how to fix. I thought it might have something to do with the security settings in the client management on instagram.com/developer but even after unchecking “Disable implicit OAuth” I still get the exception.
Any idea about what I’m missing? My URL looks like this https://api.instagram.com/v1/tags/MY_TAG/media/recent?access_token=MY_ACCESS_TOKEN
Thanks either way :)
Hello Misha! Nice Blog!
I have a question:
Is it possible to obtain the photos that I give “Like” from my Instagram account with the Instagram API in PHP?
Thank you Misha!
Hugs!
Hello! Thank you! :)
Yes, just use this
/users/self/media/liked
API endpoint. But I’m afraid you should approve your Instagram app forpublic_content
scope first.Thank you for the answer!
I’m waiting for the Instagram verification for
public_content
.Can you show me any example with
/users/self/media/liked
to see this photos?Thank you very much Misha!
Hugs!
Thanks for the post, it was really useful for me!
I have been dealing with an issue that could be helpful for someone: I just want to display my last posts, so I don’t need my app to be reviewed and approved (you can get last 20 posts without that).
The point is that I was getting the error “This client has not been approved to access this resource.” when making this call: https://api.instagram.com/v1/users/search?q=[user_name]&access_token=[token], so I couldn’t get my user ID.
Then I discovered that I don’t need my user id since I can use this call: https://api.instagram.com/v1/users/self/media/recent?access_token=[token]
Hope it’s useful sometime!
Hi Javier,
thanks for sharing this info!
code is working nice….
{“error_type”: “OAuthException”, “code”: 400, “error_message”: “Redirect URI does not match registered redirect URI”}
Thanks!! Its work great !!
Hi,
Thanks for this great code! Something strange is happening in my case. I put everything as indicated and it works. After a few minutes, I stopped being able to see the photos, going blank.
Any idea what that might be?
Hi Filipe,
No ideas :) I need more information at least.
This was perfect. Exactly what I needed as the way I was getting media before (scraping) was not working anymore in my slider. It wasn’t getting the recent images.
I was shocked that it worked the first time, using the slider and everything. All I had to do was change the key and the code worked straight off. Thanks! You saved me both time and money.
You’re welcome :)
Hello, it;s possibile to limit numbers od feeds to i.e 3?
I found it – just add
&count=3
at the end of instagram request, i.e.$return = rudr_instagram_api_curl_connect("https://api.instagram.com/v1/users/" . $user_id . "/media/recent?access_token=" . $access_token . "&count=6");
Hello, ok, great :)
Hello Misha
Thanks for the great code.
Can you please share the code to get photos from combination of hashtag+ specific location
Thanks
Hello Max,
Currently I have no ready code for this, sorry.
Hi Misha,
Thanks for your post. I didn’t get what I was willing but I am a little bit closer.
I would like to display some user information (behind a autorization) like: account details, number of like of each post, average of likes…
It is possible with the information you shared in this post?
Thank you
Very nice, thank you! I wanted to link the photo to the original Instagram post instead of a picture file, so I used $post->link for href instead. Worked perfectly.
great work!
How I can limit photos. I jus need 4 images.
Thanks
So what do you do with this snippet? Can you please show it in the context of your by_username sample?
Ok, in the context of a username it will be like this:
The snippet is not working on my end. :(
Where did you use it?
So what the heck does a person set the redirect uri to? I am developing on my local machine.
NEvermind, I figured out you have to set the callback uri to the one provided by your token generator.
good job thank!
Hi dev,
i am using this and it works great, but i have one small problem, i dont get all photos tagged with some tag. For example i have 6 photos on my instgram tagged with “example-tag”, but i only get one, or in some other cases 3,4,6, but in most cases not all.
Is there any solution for this?
Thank you very much.
not work for me..
Warning: Invalid argument supplied for foreach()
print_r($return);
Hello, I have the same problem:
What may be the solution?
Thanks,
Gergo
Here is the solution:
1.
$user_id = $user_search->data[0]->id;
changed toself
2. I’ve got an error, when I’ve try to print the $return:
3. I’ve regenerated the token
4. The new token is different from the old one – it’s interesting, because it worked properly few weeks before.
5. In this case with the new token, pictures are visible on the site :)
Hey Gergo,
Thank you for your comment 😊
I’m glad you’ve figured it out!
Thanks Misha – this article was exactly what I was looking for. Bloody life saver!
I’m glad to help! 🙃
Add this line for localhost!
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
It shows an error for me but it’s because the path isn’t ok , is someone else have the same problem try to change the path, the corect paths are here:
https://www.instagram.com/developer/endpoints/users/
I am getting an error when using the curl connect. The $user_search returns:
Instagram doesn’t work anymore.
D’oh! Well that sucks. 😕
Thanks
Yes, it is sad 🙁
You can check the new instagram graph api platform https://developers.facebook.com/products/instagram/. Maybe you can do something with it.
Obviously, since I was looking here, I am trying to find a very clean way to show 5 or 6 of the last photos of an Instagram feed on WordPress. Plugins always seem too bulky and try to lock you into a layout or theme. I just want the images and I will handle the layout.
Do you have any suggestions?
Thanks!
IT WORKED LIKE A CHARM !!! you are my hero
Grate code
is it possible any more to get photos by tag ?
https://www.instagram.com/developer/endpoints/
as i dont see that endpoint :(
i can get my own data using this script, but failed to fetch other user’s instagram photos using their userids.
i tried with add diffrent username but failed to get feeds: https://api.instagram.com/v1/users/” . $user_id . “/media/recent?access_token=” . $access_token
actually as per our website work flow, we are fetching other users photos using instagram post URL and then like for each post by unknown users. and they will earn point and then purchase some product from our site.
users purchase plan packages for like,comment & follows
users earn point using activity by liking, commenting & following one by one, and purchase our product using earned point
please help me !
and sorry for my bad english
Hi Raj,
Is your Instagram application approved?
Hashtag endpoint doesn’t work. I get this response error:
error_message: “This endpoint has been retired
Any ideas if they changed the #hashtag endpoint or removed it completely ?
Hey Jon,
I suppose, it has been removed completely..
Thanks for the post :) How would you incorporate error handling if fx. the API is down or the Token has expired?
Hi Sebastian :)
I think the best idea is to cache the last successful response and if API is down, to show old photos, which were available the last time.
I can’t generate my access token, it said :
{“error_type”: “OAuthException”, “code”: 400, “error_message”: “Redirect URI does not match registered redirect URI”}
Hi Orin,
So… are you sure that you configured redirect url in your app?
Hi Misha,
I’ve been reading your previous post on how to add Instagram feed on WordPress. Been looking for the right method to do it for my website. While looking for an answer I ended up more confuse than before.
On my quest to answer, I understood that in order to fetch Instagram’s post on my app or website, I would:
1) Need to have a Facebook Page and connect that page to the Instagram Business Account;
2) Need to register a new Facebook App with a developer account (see https://developers.facebook.com/docs/apps/register);
3) Need to get an access token for user and figure out new App ID using their tool https://developers.facebook.com/tools/explorer/;
But to register my App I need to have an official paper with a company name…
So my question is, how come your method above seems to work without having to do all these steps?
Are your methods are all using Instagram API v1 — that fetches a JSONP from the API Url (from
https://api.instagram.com/v1
/) ? If so, does that mean that all current code will be deprecated in early 2020 according to https://www.instagram.com/developer/ .Hello!
Great work!
But just noticed it doesn’t retrieve video thumbs from IGTV… am I right?
Thanks!