The very quick registration gives you many users to your web project, we already published login with Facebook, Twitter and Google Plus now time to think about very popular photo sharing portal Instagram. This post explains you how to login with instagram Oauth API and importing user data. Create an instagram account and take a quick look at this demo thanks!
Download Script Live Demo
Database Table
Sample database users table columns id, username, name, bio, website, instragram_id and instagram_access_token.
CREATE TABLE users
(
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(70),
name VARCHAR(100),
bio TEXT,
website VARCHAR(200),
instagram_id INT,
instagram_access_token VARCHAR(200)
);
(
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(70),
name VARCHAR(100),
bio TEXT,
website VARCHAR(200),
instagram_id INT,
instagram_access_token VARCHAR(200)
);
Getting Started
First you have to register your application at instagr.am/developer
Instagram Register new OAuth Client
Give your domain details and redirection callback page URL
The tutorial contains few PHP files with Instagram Oauth class file.
instagram.class.php // Instagram Class
instagram.config.php // Instagram Key Configuration
index.php
home.php
success.php // Redirection page
popular_media.php // Instagram popular images
db.php // Database Config
instagram.config.php // Instagram Key Configuration
index.php
home.php
success.php // Redirection page
popular_media.php // Instagram popular images
db.php // Database Config
Application Key Details
Instagram will provide you client id and secret details.
instagram.config.php
Here you have to give your application key details.
<?php
$instagram = new Instagram(array(
'apiKey' => 'Client_ID',
'apiSecret' => 'Client_Secret',
'apiCallback' => 'http://www.yourdomain.com/success.php' // Callback URL
));
?>
$instagram = new Instagram(array(
'apiKey' => 'Client_ID',
'apiSecret' => 'Client_Secret',
'apiCallback' => 'http://www.yourdomain.com/success.php' // Callback URL
));
?>
index.php
Instagram login link page.
<?php
session_start();
// User session data availability check
if (!empty($_SESSION['userdetails']))
{
// Redirecting to home.php
header('Location: home.php');
}
require 'instagram.class.php';
require 'instagram.config.php';
// Login URL
$loginUrl = $instagram->getLoginUrl();
echo "<a href='$loginUrl'>Sign in with Instagram </a>";
?>
session_start();
// User session data availability check
if (!empty($_SESSION['userdetails']))
{
// Redirecting to home.php
header('Location: home.php');
}
require 'instagram.class.php';
require 'instagram.config.php';
// Login URL
$loginUrl = $instagram->getLoginUrl();
echo "<a href='$loginUrl'>Sign in with Instagram </a>";
?>
success.php
Redirection page after login authentication success instagram API will send the user details object in a array data format. Here the system will insert data into USERS table, read the comments.
<?php
require 'db.php';
require 'instagram.class.php';
require 'instagram.config.php';
// Receive OAuth code parameter
$code = $_GET['code'];
// Check whether the user has granted access
if (true === isset($code))
{
// Receive OAuth token object
$data = $instagram->getOAuthToken($code);
if(empty($data->user->username))
{
header('Location: index.php');
}
else
{
session_start();
// Storing instagram user data into session
$_SESSION['userdetails']=$data;
$user=$data->user->username;
$fullname=$data->user->full_name;
$bio=$data->user->bio;
$website=$data->user->website;
$id=$data->user->id;
$token=$data->access_token;
// Verify user details in USERS table
$id=mysqli_query("select instagram_id from instagram_users where instagram_id='$id'");
if(mysqli_num_rows($id) == 0)
{
// Inserting values into USERS table
mysqli_query("insert into instagram_users(username,Name,Bio,Website,instagram_id,instagram_access_token) values('$user','$fullname','$bio','$website','$id','$token')");
}
// Redirecting you home.php
header('Location: home.php');
}
}
else
{
// Check whether an error occurred
if (true === isset($_GET['error']))
{
echo 'An error occurred: '.$_GET['error_description'];
}
}
?>
require 'db.php';
require 'instagram.class.php';
require 'instagram.config.php';
// Receive OAuth code parameter
$code = $_GET['code'];
// Check whether the user has granted access
if (true === isset($code))
{
// Receive OAuth token object
$data = $instagram->getOAuthToken($code);
if(empty($data->user->username))
{
header('Location: index.php');
}
else
{
session_start();
// Storing instagram user data into session
$_SESSION['userdetails']=$data;
$user=$data->user->username;
$fullname=$data->user->full_name;
$bio=$data->user->bio;
$website=$data->user->website;
$id=$data->user->id;
$token=$data->access_token;
// Verify user details in USERS table
$id=mysqli_query("select instagram_id from instagram_users where instagram_id='$id'");
if(mysqli_num_rows($id) == 0)
{
// Inserting values into USERS table
mysqli_query("insert into instagram_users(username,Name,Bio,Website,instagram_id,instagram_access_token) values('$user','$fullname','$bio','$website','$id','$token')");
}
// Redirecting you home.php
header('Location: home.php');
}
}
else
{
// Check whether an error occurred
if (true === isset($_GET['error']))
{
echo 'An error occurred: '.$_GET['error_description'];
}
}
?>
home.php
Welcome page here you can display user data accessing session userdetails value.
<?php
session_start();
if($_GET['id']=='logout')
{
unset($_SESSION['userdetails']);
session_destroy();
}
require 'instagram.class.php';
require 'instagram.config.php';
if (!empty($_SESSION['userdetails']))
{
$data=$_SESSION['userdetails'];
echo '<img src='.$data->user->profile_picture.' >';
echo 'Name:'.$data->user->full_name;
echo 'Username:'.$data->user->username;
echo 'User ID:'.$data->user->id;
echo 'Bio:'.$data->user->bio;
echo 'Website:'.$data->user->website;
echo 'Profile Pic:'.$data->user->profile_picture;
echo 'Access Token: '.$data->access_token;
// Store user access token
$instagram->setAccessToken($data);
// Your uploaded images
$popular = $instagram->getUserMedia($data->user->id);
foreach ($popular->data as $data) {
echo '<img src='.$data->images->thumbnail->url.'>';
}
// Instagram Data Array
print_r($data);
}
else
{
header('Location: index.php');
}
?>
session_start();
if($_GET['id']=='logout')
{
unset($_SESSION['userdetails']);
session_destroy();
}
require 'instagram.class.php';
require 'instagram.config.php';
if (!empty($_SESSION['userdetails']))
{
$data=$_SESSION['userdetails'];
echo '<img src='.$data->user->profile_picture.' >';
echo 'Name:'.$data->user->full_name;
echo 'Username:'.$data->user->username;
echo 'User ID:'.$data->user->id;
echo 'Bio:'.$data->user->bio;
echo 'Website:'.$data->user->website;
echo 'Profile Pic:'.$data->user->profile_picture;
echo 'Access Token: '.$data->access_token;
// Store user access token
$instagram->setAccessToken($data);
// Your uploaded images
$popular = $instagram->getUserMedia($data->user->id);
foreach ($popular->data as $data) {
echo '<img src='.$data->images->thumbnail->url.'>';
}
// Instagram Data Array
print_r($data);
}
else
{
header('Location: index.php');
}
?>
popular_media.php
Get Instagram popular media.
<?php
require 'instagram.class.php';
// Initialize class for public requests
$instagram = new Instagram('Client_ID');
// Get popular instagram media
$popular = $instagram->getPopularMedia();
// Display results
foreach ($popular->data as $data)
{
echo "<img src="\"{$data->images->thumbnail->url}\">";
}
?>
require 'instagram.class.php';
// Initialize class for public requests
$instagram = new Instagram('Client_ID');
// Get popular instagram media
$popular = $instagram->getPopularMedia();
// Display results
foreach ($popular->data as $data)
{
echo "<img src="\"{$data->images->thumbnail->url}\">";
}
?>
db.php
Database configuration file, modify username, password, database and base url values.
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
$connection = @mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
$base_url='http://www.youwebsite.com/email_activation/';
?>
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
$connection = @mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
$base_url='http://www.youwebsite.com/email_activation/';
?>
Next post I will explain how to use instagram access token to access friend relations. If any queries please comment here.
Great article, thanks!
ReplyDeletea nice one!!!
ReplyDeletethis is wonderful!!!
ReplyDeleteNice work buddy! but i think you should think about yahoo oauth sys.
ReplyDeleteasslm..mau coba dl mas bro..thanks ya
ReplyDeletenice!
ReplyDeleteNice
ReplyDeleteey...
ReplyDeletebookmark!
Super! Super Great Article. Nice! Thanks!!!
ReplyDeleteGood Tutorial ,
ReplyDeletethanks a lot
Hi,
ReplyDeleteI just saw that you used my Instagram class in your tutorial. It's great that you found it helpful, because as a developer your are always glad to see that your work is apprecited. Thanks too, for your other tutorials wich are very useful for me. Keep up with your really good work.
All the best,
Christian
in the script success.php
ReplyDelete$ id = $ data-> user-> id;
Writes a value into the database - "Resource id # 7"
Why is it so?
Nice one. And let's hope my full_name is not "'); DROP instagram_users; ( "
ReplyDeleteI changed
ReplyDelete$popular = $instagram->getPopularMedia();
to
$popular = $instagram->getUserLikes();
and
$popular = $instagram->getUserLikes('MY_ID');
but not shown anything.
How to???? whats wrong?
Heya, I'm having a real hard time with authentication. I need to dynamically call the access token and I can't seem to get it right. I have:
ReplyDelete$api = 'https://api.instagram.com/v1/users/self/media/recent?access_token=[CODE];.
I tried:
$api = 'https://api.instagram.com/v1/users/self/media/recent?access_token=.'$token;
and that didn't work.
I even tried:
$api = 'https://api.instagram.com/v1/users/self/media/recent?access_token='.$data->access_token;
and that also didn't work. Any suggestions? Thanks!
Hello .. I'm getting this error:
ReplyDeleteWarning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /instagram/index.php:7) in /instagram/index.php on line 56
On the index.php ... the a load of errors after it's authenticated.
Any ideas??
Thanks
Great tutorial, I'm hoping you show how to grab posts using certain user keys. That would be useful.
ReplyDeletewow... Great tutorial, thank you very much!!!
ReplyDeletegreat tutorial..
ReplyDeletenice tutorial i liked it.
ReplyDeletethanks for this.
Great tutorial, The demo doesn't have an error condition for checking if user has denied the request - would be a complete demo with that :)
ReplyDeleteAwesome, is it possible to use with scopes?
ReplyDeletescope=likes+comments
I'm having some issues and would love if any of you could help me!
ReplyDeleteI've managed to get up to the step of when the user allowes the auth. , and then the url is redirected to the 'success.php' page, which should then redirect them to 'home.php'? however this doesn't happen, i am just presented with a webpage displaying the source code of 'success.php',
it would be great if anyone could let me know where I've gone wrong, or what can i do to fix this!?
Please email me at [email protected]
Thanks!
NICE ONE DUDE! It helps me a lot integrating API's..:D
ReplyDeleteHow can I write to a txt or xml file instead of inserting into a DB? I'm not provided a DB with my service, but would like to show my instagram photos on my site.
ReplyDeleteHi, where is the instagram.class.php??
ReplyDeleteThanks for showing step by step process of using instagram in PHP. It's really useful and I should say every PHP programmer must know about this.
ReplyDeleteVery nice tutorial, and realy very helpfull!
ReplyDeletethanks a lot!
But I have a question!
How to show, all user's photos on the "home.php" page?
I know that should be used pagination... but I don't understand, how to do it...
Can you help me?
Great article, but why would you store the user bio and website, when these things can change. Won't you have stale data on your db?
ReplyDeleteThis helped me alot! Thanks! :)
ReplyDeleteGreat, but how to log out of it?
ReplyDeletesave my time, thanks
ReplyDeleteHello thanks for this tutorial !! I want to give the possibility to the user to select one or many picture (in the high Res) from his instagram pictures and send the selectionned picture attach to a php form. has someone an id to help me to make that ? Matthieu
ReplyDeletewhat is instagram.class.php?
ReplyDeleteAwesome tut!!!
ReplyDeleteBut i've question! how i can show images with different size and pagination?
{"code": 400, "error_type": "OAuthException", "error_message": "Redirect URI does not match registered redirect URI"}
ReplyDeleteI did everything but get this error when i want to auth my app
when i am trying to login it redirects to the same index page with login button. Please help me to solve this issue
ReplyDeletethats what I was searching. thanks
ReplyDeleteNice!
ReplyDeleteYou should change the database name on this page to "instagram_users" instead of "users", otherwise it doesn't work. Thanks for the tut! Regards.
ReplyDeleteWhere is the instagram.class.php code?
ReplyDeleteWarning: session_start(): Cannot send session cache limiter - headers already sent (output started at /home/amaleroh/public_html/instagram/index.php:37) in /home/amaleroh/public_html/instagram/index.php on line 38
ReplyDeleteWarning: Cannot modify header information - headers already sent by (output started at /home/amaleroh/public_html/instagram/index.php:37) in /home/amaleroh/public_html/instagram/index.php on line 43
Hello,
ReplyDeleteIt is possible to write for us a nice tutorial on how to get pictures from user instagram account instead of uploading pictures ?
Let me know what do you thing about this idea on my email office@ + domain
Now. Is it possible to do the same, but without the user input? If I've got an account, and I just want to do a headless login?
ReplyDeleteHello, Thanks for the nice tutorial.
ReplyDeleteI have added few lines of code on the class file to add comment. But when calling the "addComment($id,$text)" function then nothing is happening. Can you please tell me why it's happening.
public function addComment($id,$text) {
return $this->_makeCall('media/'.$id.'/comments', true, array('text' => $text));
}
Thanks,
great article. A big thank
ReplyDeleteHow can we register to istagram.
ReplyDeleteHi sir
ReplyDeletecan you tell me how to add scope for relations.Currently i'm unable to follow/unfollow from this api.
Though there is a scope for 'basic', 'likes', 'comments', 'relationships' in class file,i'm failed to achive this.Please help me
Thank you.
Good article.
ReplyDeleteWhen user log in, can we get user's email ?
https://github.com/cosenary/Instagram-PHP-API
ReplyDeleteHello,
ReplyDeleteI'm new for this instagram and after register and creating clientID and clientsecret and then what process to performs no idea about this..
please gives me a suggestions...
After the authorization, I am being redirected to the index page again. Any solution to this error?
ReplyDeleteJust wanted to say that I read your blog quite frequently and I’m always amazed at some of the stuff people post here. But keep up the good work, it’s always interesting .
ReplyDeleteVery helpful.... You saved a lot time for me. Thanks for sharing code
ReplyDeleteAwesome comment
ReplyDeleteHi, thank you for your kind sharing your knowledge.
ReplyDeleteI have an football club web site, i m using php dolphin (some kind of social network software)
I tried to add your instagram log-in system into my entry page, but i cant handle it.
Could you please help me?
I also send you friendship from Facebook.
Best regards.
ufuk
Hi, thank you for you kind sharing your knowedge.
ReplyDeleteI have a question. how do i logout from site through social login?
Hi, Thanks for article. How to get access token using ajax request on modal box?
ReplyDeletehow to get follower list.?..please reply...
ReplyDeleteThere is this new thing called Sandbox by Instagram which came into existence from November 17,2015. Those who are new to this cannot authenticate with the current tutorial. Kindly change the tutorial with respective Sandbox implementation and help other developers notify. For details about Sandbox visit https://www.instagram.com/developer/sandbox
ReplyDeleteThank you.
Thanks for the update, soon I will modify this
Deleteyeah .. . this is helpful. please make an update for newbie like me is not working this tutorial. thank you
DeleteHello Sir,
ReplyDeleteIt's a great tutorial. But I am facing an error unable to add records to the database. I really appreciate your help.
"Fatal error: Class 'Exeption' not found in /home/puneetjain/public_html/s/insta/instagram.class.php on line 253"
Hello Sir,
ReplyDeleteIt's a great tutorial. But I am facing a issue "Fatal error: Class 'Exeption' not found in /home/puneetjain/public_html/s/insta/instagram.class.php on line 253".
Please Help me on this.
Thank you Sir.
Now it is not working blank page is showing after login. Please check may be auth code code changed.
ReplyDeletein demo, after login its dipslay the blank page. can you please let me know what is issue ?
ReplyDeleteIs there some document how to login with Instagram without refreshing the page.
ReplyDelete{"code": 403, "error_type": "OAuthForbiddenException", "error_message": "You are not a sandbox user of this client"}
ReplyDeletethat is the respons now in the demo, can you update this tutorial ?
Dear sir.
ReplyDeleteHow can work with scopes.please reply soon with code.
run the code ,but showing this error message:
ReplyDelete{"code": 403, "error_type": "OAuthForbiddenException", "error_message": "You are not a sandbox user of this client"}
not getting the posted pics.how can i access the sers pics to my webiste?
ReplyDeleteThanks a lot.This is working.Thank you so much
ReplyDeleterun the code ,but showing this error message:
ReplyDelete{"code": 403, "error_type": "OAuthForbiddenException", "error_message": "You are not a sandbox user of this client"}
can you update to new api 2016
Its not working,
ReplyDeleteAfter redirecting when code fetch data as
$data = $instagram->getOAuthToken($code);
its blank.
I checked on localhost as well on server.
Please advise
not getting data from instagram and redirect directly to that page only.
ReplyDeletehelp me for getting data from instagram.
{"code": 403, "error_type": "OAuthForbiddenException", "error_message": "You are not a sandbox user of this client"}
ReplyDeleteGr8 Article:).....But also need an update on how to upload images on Instagram with publishing likes and comments.
ReplyDeletethank for you :)
ReplyDelete{"error_type": "OAuthException", "code": 400, "error_message": "Invalid scope field(s): basic,likes"}
ReplyDeleteThis comment has been removed by a blog administrator.
ReplyDelete