Free PHP Script To Connect To Instagram API
Overview #
Last week we helped a client get their Instagram feed back up and running on their website. On some of their web pages they pulled in recent posts from their feed, images of their store, happy customers, recent creations, that sort of thing. This functionality failed once Instagram updated their API's.
So I wrote a PHP script that could get things back on track. No database is needed. No weird libraries, classes or methods. Just a bit of straight PHP code to help you out.
Why? #
In the Summer of 2020 Instagram overhauled its API's. They opted for a secure and modern OAuth architecture. This meant that connections to their API were a bit more complex to implement. An app, whether a mobile app or a widget on a website, needed to obtain an access token and keep that token fresh over time in order to make connections. This can't simply be done with static Javascript the way Instagram had previously allowed. Some server-side processing was needed.
A website might pull in Instagram posts, images, captions, etc from a given Instagram account. These would be displayed on a given web page somewhere on the website. Normally these would be pulled in in real time via an AJAX call and loaded into the page using Javascript.
As a rule of thumb you should not expose access tokens or share them publicly. So you would not want to expose a Javascript AJAX call that included the Instagram access token. (In the case of an Instagram token, the worst that can happen is that someone else can access the publicly available posts of the feed the token is attached to. Not a big deal. But still, if you can do it right, do it right.)
How It Works #
- To use the script, grab it from Github. See below.
- Load it to your web server so that it can be accessed in a web browser.
- Update the variables at the top of the script so that it points to your Instagram account and knows where to save cached data in your file system.
- Hit the script in a web browser. Login to Instagram when prompted and allow the script to access your feed.
- The script will process the short-lived and long-lived access token processes. It will cache your feed and end by returning Instagram's JSON version of your feed.
- Every time a web browser hits the script, a fresh daily copy of the feed will be returned and the appropriate token will be refreshed.
Where Is This Script!!?? #
This free PHP script is available from Solspace's Github account here:
https://github.com/solspace/php-instagram-feed-with-token-refresh