Login with Instagram OAuth using PHP.
Wall Script
Wall Script
Monday, May 21, 2012

Login with Instagram OAuth using PHP.

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!

Login with Instagram

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)
);

Getting Started
First you have to register your application at instagr.am/developer
Getting started Instagram

Instagram Register new OAuth Client
Give your domain details and redirection callback page URL
Instagram Register new OAuth Client

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

Application Key Details
Instagram will provide you client id and secret details.
Oauth Details Instagram

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
));
?>

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>";
?>

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'];
}
}
?>

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');
}
?>

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}\">";
}
?>

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/';
?>

Next post I will explain how to use instagram access token to access friend relations. If any queries please comment here.
web notification

80 comments:

  1. Nice work buddy! but i think you should think about yahoo oauth sys.

    ReplyDelete
  2. asslm..mau coba dl mas bro..thanks ya

    ReplyDelete
  3. Super! Super Great Article. Nice! Thanks!!!

    ReplyDelete
  4. Good Tutorial ,
    thanks a lot

    ReplyDelete
  5. Hi,

    I 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

    ReplyDelete
  6. in the script success.php
    $ id = $ data-> user-> id;
    Writes a value into the database - "Resource id # 7"

    Why is it so?

    ReplyDelete
  7. Nice one. And let's hope my full_name is not "'); DROP instagram_users; ( "

    ReplyDelete
  8. I changed
    $popular = $instagram->getPopularMedia();
    to
    $popular = $instagram->getUserLikes();
    and
    $popular = $instagram->getUserLikes('MY_ID');

    but not shown anything.

    How to???? whats wrong?

    ReplyDelete
  9. 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:
    $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!

    ReplyDelete
  10. Hello .. I'm getting this error:

    Warning: 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

    ReplyDelete
  11. Great tutorial, I'm hoping you show how to grab posts using certain user keys. That would be useful.

    ReplyDelete
  12. wow... Great tutorial, thank you very much!!!

    ReplyDelete
  13. nice tutorial i liked it.
    thanks for this.

    ReplyDelete
  14. 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 :)

    ReplyDelete
  15. Awesome, is it possible to use with scopes?
    scope=likes+comments

    ReplyDelete
  16. I'm having some issues and would love if any of you could help me!

    I'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!

    ReplyDelete
  17. NICE ONE DUDE! It helps me a lot integrating API's..:D

    ReplyDelete
  18. How 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.

    ReplyDelete
  19. Hi, where is the instagram.class.php??

    ReplyDelete
  20. Thanks 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.

    ReplyDelete
  21. Very nice tutorial, and realy very helpfull!
    thanks 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?

    ReplyDelete
  22. 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?

    ReplyDelete
  23. Great, but how to log out of it?

    ReplyDelete
  24. Hello 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

    ReplyDelete
  25. what is instagram.class.php?

    ReplyDelete
  26. Awesome tut!!!
    But i've question! how i can show images with different size and pagination?

    ReplyDelete
  27. {"code": 400, "error_type": "OAuthException", "error_message": "Redirect URI does not match registered redirect URI"}

    I did everything but get this error when i want to auth my app

    ReplyDelete
  28. when i am trying to login it redirects to the same index page with login button. Please help me to solve this issue

    ReplyDelete
  29. thats what I was searching. thanks

    ReplyDelete
  30. You should change the database name on this page to "instagram_users" instead of "users", otherwise it doesn't work. Thanks for the tut! Regards.

    ReplyDelete
  31. Where is the instagram.class.php code?

    ReplyDelete
  32. Warning: 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

    Warning: 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

    ReplyDelete
  33. Hello,

    It 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

    ReplyDelete
  34. 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?

    ReplyDelete
  35. Hello, Thanks for the nice tutorial.

    I 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,

    ReplyDelete
  36. great article. A big thank

    ReplyDelete
  37. How can we register to istagram.

    ReplyDelete
  38. Hi sir
    can 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.

    ReplyDelete
  39. Good article.

    When user log in, can we get user's email ?

    ReplyDelete
  40. https://github.com/cosenary/Instagram-PHP-API

    ReplyDelete
  41. Hello,
    I'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...

    ReplyDelete
  42. After the authorization, I am being redirected to the index page again. Any solution to this error?

    ReplyDelete
  43. Just 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 .

    ReplyDelete
  44. Very helpful.... You saved a lot time for me. Thanks for sharing code

    ReplyDelete
  45. Hi, thank you for your kind sharing your knowledge.
    I 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

    ReplyDelete
  46. Hi, thank you for you kind sharing your knowedge.
    I have a question. how do i logout from site through social login?

    ReplyDelete
  47. Hi, Thanks for article. How to get access token using ajax request on modal box?

    ReplyDelete
  48. how to get follower list.?..please reply...

    ReplyDelete
  49. There 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
    Thank you.

    ReplyDelete
    Replies
    1. Thanks for the update, soon I will modify this

      Delete
    2. yeah .. . this is helpful. please make an update for newbie like me is not working this tutorial. thank you

      Delete
  50. Hello Sir,
    It'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"

    ReplyDelete
  51. Hello Sir,
    It'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.

    ReplyDelete
  52. Now it is not working blank page is showing after login. Please check may be auth code code changed.

    ReplyDelete
  53. in demo, after login its dipslay the blank page. can you please let me know what is issue ?

    ReplyDelete
  54. Is there some document how to login with Instagram without refreshing the page.

    ReplyDelete
  55. {"code": 403, "error_type": "OAuthForbiddenException", "error_message": "You are not a sandbox user of this client"}

    that is the respons now in the demo, can you update this tutorial ?

    ReplyDelete
  56. Dear sir.
    How can work with scopes.please reply soon with code.

    ReplyDelete
  57. run the code ,but showing this error message:
    {"code": 403, "error_type": "OAuthForbiddenException", "error_message": "You are not a sandbox user of this client"}

    ReplyDelete
  58. not getting the posted pics.how can i access the sers pics to my webiste?

    ReplyDelete
  59. Thanks a lot.This is working.Thank you so much

    ReplyDelete
  60. run the code ,but showing this error message:
    {"code": 403, "error_type": "OAuthForbiddenException", "error_message": "You are not a sandbox user of this client"}

    can you update to new api 2016

    ReplyDelete
  61. Its not working,
    After redirecting when code fetch data as
    $data = $instagram->getOAuthToken($code);
    its blank.
    I checked on localhost as well on server.
    Please advise

    ReplyDelete
  62. not getting data from instagram and redirect directly to that page only.
    help me for getting data from instagram.

    ReplyDelete
  63. {"code": 403, "error_type": "OAuthForbiddenException", "error_message": "You are not a sandbox user of this client"}

    ReplyDelete
  64. Gr8 Article:).....But also need an update on how to upload images on Instagram with publishing likes and comments.

    ReplyDelete
  65. {"error_type": "OAuthException", "code": 400, "error_message": "Invalid scope field(s): basic,likes"}

    ReplyDelete
  66. This comment has been removed by a blog administrator.

    ReplyDelete

mailxengine Youtueb channel
Make in India
X