9lessons programming blog
Loading Search
9lessons Bring Friends
Wall Script
Follow Me:
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=mysql_query("select instagram_id from instagram_users where instagram_id='$id'");
if(mysql_num_rows($id) == 0)
{
// Inserting values into USERS table
mysql_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 you have to modify username, password and database name values.
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'Username');
define('DB_PASSWORD', 'Password');
define('DB_DATABASE', 'Database');
$connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die(mysql_error());
$database = mysql_select_db(DB_DATABASE) or die(mysql_error());
?>

Next post I will explain how to use instagram access token to access friend relations. If any queries please comment here.
Comments
{ 55 comments }
Pierre said...

Great article, thanks!

Anonymous said...

a nice one!!!

Aloko Ademola Bamidele said...

this is wonderful!!!

Raaz said...

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

Anonymous said...

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

Nguyễn Văn Ánh said...

nice!

Jobsbox said...

Nice

adiputra said...

ey...
bookmark!

Anonymous said...

Super! Super Great Article. Nice! Thanks!!!

Anonymous said...

Good Tutorial ,
thanks a lot

Christian said...

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

Roman said...

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

Why is it so?

Anonymous said...

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

BONAR said...

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

but not shown anything.

How to???? whats wrong?

Anonymous said...

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!

Andy Corney said...

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

Zach said...

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

Anonymous said...

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

bhanu said...

great tutorial..

indiresult said...

nice tutorial i liked it.
thanks for this.

V.Vamshi Krishna Reddy said...

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

ejje said...

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

Josh said...

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 josh.calvert@instapouch.com

Thanks!

Anonymous said...

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

Anonymous said...

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.

David Gabor said...

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

Cheryl Ray said...

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.

Misha Fironov said...

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?

bhk said...

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?

Emma Tegström said...

This helped me alot! Thanks! :)

Anonymous said...

Great, but how to log out of it?

elcoke said...

save my time, thanks

Matthieu said...

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

Anonymous said...

what is instagram.class.php?

Anonymous said...

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

Takipçi Durağı said...

{"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

Krupal Lakhia said...

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

Anonymous said...

thats what I was searching. thanks

Anonymous said...

Nice!

Anonymous said...

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.

Anonymous said...

Where is the instagram.class.php code?

Amalero High said...

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

Denis said...

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

Anonymous said...

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?

Utpal said...

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,

sjunnesson said...

great article. A big thank

Gaurav Kumar said...

How can we register to istagram.

Rajasekhar zonup said...

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.

Ông Tám said...

Good article.

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

Anonymous said...

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

Devendra Tandel said...

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...

Anonymous said...

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

Paksu Backlink said...

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 .

chi said...

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

Anonymous said...

Awesome comment

Post a Comment