Skip to Content
login with instagram api
php code / September 12, 2021

The Instagram API makes it simple to incorporate a user authentication system into your web app. Logging in with Instagram allows users to log into the website using their Instagram account. The web application does not require the user’s registration feature because the authentication process is handled by the Instagram API. The Instagram Login allows users to visit the website without having to create an account.

The Instagram API authenticates and authorises users using OAuth 2.0. Using the Instagram API and PHP, you can quickly integrate the Login system with Instagram. We’ll teach you how to use PHP to integrate Login with Instagram in this tutorial. The Instagram API may be accessed with PHP using cURL, which is a simple and effective method. To connect the Instagram API in PHP, we’ll utilise cURL.

In the example Instagram OAuth script, the following features will be implemented.

Using access token, authenticate with your Instagram account.
Get the user’s profile information from their Instagram account.
Using PHP and MySQL, save profile data in a database.
Display information about the user’s account.
Take a look at the file structure before you start integrating Instagram Login in PHP.

├── config.php
├── index.php
├── logout.php
├── User.class.php
├── InstagramAuth.class.php
├── images/
└── css/

Client ID on Instagram should be registered.
To use the Instagram API, you’ll need the Client ID and Client Secret. Before you begin implementing Instagram Login with PHP on your website, you must first create a new Instagram Client and obtain the Client ID and Secret.

To access the Instagram Developer Panel, go to

Create a developer account and log in to your developer account.

To register a new client, go to the Manage Clients page and click the Register a New Client button.

To submit, fill out the Application information and click the Register button.

Valid redirect URIs must match the redirect URL supplied when the API request is made.

The App will appear in the Manage Clients tab after it has been created. Select MANAGE from the drop-down menu.

The Client ID and Client Secret can be found on the App Details page. These API credentials (Client ID and Client Secret) should be saved for further usage in the script.

Make a database table.
A table in the database is necessary to record the user’s Instagram profile information. In the MySQL database, the following SQL creates a users table with some basic fields.

CREATE TABLE `users` (
`oauth_provider` enum('instagram','facebook','google','linkedin','') COLLATE utf8_unicode_ci NOT NULL,
`oauth_uid` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`first_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`last_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`username` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`gender` varchar(5) COLLATE utf8_unicode_ci NOT NULL,
`picture` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`link` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

OAuth Library for Instagram
The InstagramAuth class allows you to use PHP to authenticate with the Instagram API.

getAccessToken() – Using PHP cURL, retrieve the access token via the Instagram OAuth API (oauth/access token).
getUserProfileInfo() – Using access token, retrieve the user’s profile data from the Instagram User API (users/self).

* Instagram API Class 
* This class helps to authenticate with Instagram API 
* @author 
* @url 
* @license 
class InstagramAuth { 
public $client_id = ''; 
public $client_secret = ''; 
public $redirect_url = ''; 
private $act_url = ''; 
private $ud_url = ''; 
public function __construct(array $config = array()){ 
public function initialize(array $config = array()){ 
foreach ($config as $key => $val){ 
if (isset($this->$key)){ 
$this->$key = $val; 
return $this; 
public function getAuthURL(){ 
$authURL = "" . $this->client_id . "&redirect_uri=" . urlencode($this->redirect_url) . "&response_type=code&scope=basic"; 
return $authURL; 
public function getAccessToken($code) { 
$urlPost = 'client_id='. $this->client_id . '&client_secret=' . $this->client_secret . '&redirect_uri=' . $this->redirect_url . '&code='. $code . '&grant_type=authorization_code'; 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $this->act_url); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $urlPost); 
$data = json_decode(curl_exec($ch), true); 
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
if($http_code != '200'){ 
throw new Exception('Error : Failed to receive access token'.$http_code); 
return $data['access_token']; 
public function getUserProfileInfo($access_token) { 
$url = $this->ud_url.'?access_token=' . $access_token; 

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
$data = json_decode(curl_exec($ch), true); 
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
if($data['meta']['code'] != 200 || $http_code != 200){ 
throw new Exception('Error : Failed to get user information'); 
return $data['data']; 

User Type (User.class.php)
The User class uses PHP and MySQL to handle database activities (connect, insert, and update).

Connect to the MySQL database via __construct().
checkUser() – Based on the OAuth provider and ID, insert or update the user account data (Instagram profile details). Returns an array of the user’s account info.

* User Class 
* This class is used for database related (connect, insert, and update) operations 
* @author 
* @url 
* @license 
class User { 
private $dbHost = DB_HOST; 
private $dbUsername = DB_USERNAME; 
private $dbPassword = DB_PASSWORD; 
private $dbName = DB_NAME; 
private $userTbl = DB_USER_TBL; 
function __construct(){ 
// Connect to the database 
$conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName); 
die("Failed to connect with MySQL: " . $conn->connect_error); 
$this->db = $conn; 
function checkUser($userData = array()){ 
// Check whether user data already exists in database 
$prevQuery = "SELECT * FROM ".$this->userTbl." WHERE oauth_provider = '".$userData['oauth_provider']."' AND oauth_uid = '".$userData['oauth_uid']."'"; 
$prevResult = $this->db->query($prevQuery); 
if($prevResult->num_rows > 0){ 
// Update user data if already exists 
$query = "UPDATE ".$this->userTbl." SET first_name = '".$userData['first_name']."', last_name = '".$userData['last_name']."', email = '".$userData['email']."', gender = '".$userData['gender']."', picture = '".$userData['picture']."', link = '".$userData['link']."', modified = NOW() WHERE oauth_provider = '".$userData['oauth_provider']."' AND oauth_uid = '".$userData['oauth_uid']."'"; 
$update = $this->db->query($query); 
// Insert user data 
$query = "INSERT INTO ".$this->userTbl." SET oauth_provider = '".$userData['oauth_provider']."', oauth_uid = '".$userData['oauth_uid']."', first_name = '".$userData['first_name']."', last_name = '".$userData['last_name']."', email = '".$userData['email']."', gender = '".$userData['gender']."', picture = '".$userData['picture']."', link = '".$userData['link']."', created = NOW(), modified = NOW()"; 
$insert = $this->db->query($query); 

// Get user data from the database 
$result = $this->db->query($prevQuery); 
$userData = $result->fetch_assoc(); 
// Return user data 
return $userData; 

Configuration of the API and Site Settings (config.php)
The config.php file contains the database settings and Instagram API configuration constant variables.

Constants in the Database:

DB HOST — This parameter specifies the database host.

DB USERNAME – This is the username for the database.

DB PASSWORD – This field is used to specify the database password.

DB NAME – Name of the database.

DB USER TBL – Name of the table that will hold the user’s account information.

Constants in the Instagram API:

INSTAGRAM CLIENT ID – The Instagram Client ID must be specified.

INSTAGRAM CLIENT SECRET — The Instagram Client Secret is specified here.

INSTAGRAM REDIRECT URI – The Callback URL must be specified.

The Instagram Auth library is used to connect to the Instagram API and communicate with OAuth clients.

* Basic Site Settings and API Configuration 
// Database configuration 
define('DB_HOST', 'MySQL_Database_Host'); 
define('DB_USERNAME', 'MySQL_Database_Username'); 
define('DB_PASSWORD', 'MySQL_Database_Password'); 
define('DB_NAME', 'MySQL_Database_Name'); 
define('DB_USER_TBL', 'users'); 
// Instagram API configuration 
define('INSTAGRAM_CLIENT_ID', 'Instagram_Client_Id'); 
define('INSTAGRAM_CLIENT_SECRET', 'Instagram_Client_Secret'); 
define('INSTAGRAM_REDIRECT_URI', 'Callback_URL'); 
// Start session 
* For the internal purposes only 
* changes not required 
// Include Instagram OAuth library 
require_once 'InstagramAuth.class.php'; 
// Initiate Instagram Auth class 
$instagram = new InstagramAuth(array( 
'client_id' => INSTAGRAM_CLIENT_ID, 
'client_secret' => INSTAGRAM_CLIENT_SECRET, 
'redirect_url' => INSTAGRAM_REDIRECT_URI 

Keep in mind that the Client ID and Client Secret can be found on the Instagram Client Settings page.

Get Account Data by Logging in with Instagram (index.php)

PHP is used to manage the Instagram API authentication procedure in this file.

The Instagram Sign-in button is displayed on the web page after the authentication URL is generated using the getAuthURL() function of the Instagram Auth class.

When a user logs in using their Instagram account, the following occurs:

The code acquired during the authorisation phase is used to retrieve the access token using getAccessToken().
The access token uses getUserProfileInfo() to retrieve profile information from the Instagram account.
The checkUser() function of the User class is used to insert account data into the database.
The PHP SESSION stores the user’s account information.
The homepage displays the Instagram profile details (ID, First name, Last name, Picture, and Profile link).

// Include configuration file 
require_once 'config.php'; 
// Include User class 
require_once 'User.class.php'; 
// If URL contains 'code' parameter that passed by Instagram in the Redirect URL 
try { 
// Get the access token 
$access_token = $instagram->getAccessToken($_GET['code']); 

// Get user profile info 
$userData = $instagram->getUserProfileInfo($access_token); 
} catch (Exception $e) { 
$authErr = $e->getMessage(); 
$username = $userData['username']; 
$full_name = $userData['full_name']; 
$full_name_arr = explode(' ',$full_name); 
$first_name = !empty($full_name_arr[0])?$full_name_arr[0]:''; 
$last_name = !empty($full_name_arr[1])?$full_name_arr[1]:''; 
$link = ''.$username; 
// Initialize User class 
$user = new User(); 
// Getting user's profile data 
$intUserData = array(); 
$intUserData['oauth_uid'] = $userData['id']; 
$intUserData['username'] = $username; 
$intUserData['first_name'] = $first_name; 
$intUserData['last_name'] = $last_name; 
$intUserData['picture'] = !empty($userData['profile_picture'])?$userData['profile_picture']:''; 
$intUserData['link'] = $link; 
$intUserData['email'] = ''; 
$intUserData['gender'] = ''; 
// Insert or update user data to the database 
$intUserData['oauth_provider'] = 'instagram'; 
$userData = $user->checkUser($intUserData); 
// Storing user data in the session 
$_SESSION['userData'] = $userData; 
// Get logout url 
$logoutURL = INSTAGRAM_REDIRECT_URI.'logout.php'; 
// Render Instagram profile data 
$output = '<h2>Instagram Profile Details</h2>'; 
$output .= '<div class="ac-data">'; 
$output .= '<img src="'.$userData['picture'].'"/>'; 
$output .= '<p><b>Account ID:</b> '.$userData['oauth_uid'].'</p>'; 
$output .= '<p><b>Name:</b> '.$userData['first_name'].' '.$userData['last_name'].'</p>'; 
$output .= '<p><b>Logged in with:</b> Instagram</p>'; 
$output .= '<p><b>Profile Link:</b> <a href="'.$userData['link'].'" target="_blank">Click to visit Instagram page</a></p>'; 
$output .= '<p><b>Logout from <a href="'.$logoutURL.'">Instagram</a></p>'; 
$output .= '</div>'; 
$output = '<h3 style="color:red">Instagram authentication has failed!</h3>'; 
$output = '<p style="color:red">'.$authErr.'</p>'; 
// Get login url 
$authURL = $instagram->getAuthURL(); 
// Render Instagram login button 
$output = '<a href="'.htmlspecialchars($authURL).'" class="instagram-btn"><span class="btn-icon"></span><span class="btn-text">Login with Instagram</span></a>'; 
<!DOCTYPE html>
<html lang="en">
<title>Login with Instagram using PHP by CodexWorld</title>
<meta charset="utf-8">
<link rel="stylesheet" href="css/style.css">
<div class="container">
<div class="inst-box">
<!-- Display login button / Instagram profile information -->
<?php echo $output; ?>

Logout (logout.php) The logout.php

file is loaded if the user decides to log out of their Instagram account.

Remove the SESSION’s access token and user data.
Redirect the user to the website’s main page.

// Remove user data from session 
// Redirect to the homepage 

Note :

Our Instagram Auth library allows you to use PHP to integrate Instagram login. Using PHP cURL and our example code, you can easily integrate the Instagram API. With only a few API settings, you can simply integrate Instagram login into your website. Use JavaScript SDK to integrate Instagram Login without refreshing the page if you want to make the Instagram login procedure more user-friendly.

PHPCODE © 2024