Login with Instagram using PHP


0

In this tutorial we will see login with Instagram using PHP

Introduction

The Instagram API give us simple way to integrate login authentication system in the web app. With login Instagram permit the user to authenticate with their Instagram account and log into the web app. After, the authentication procedure managed by the Instagram API, the web app does not need the user registration operation. The Instagram Login enables fast access for the user without generating an account on the website.

OAuth 2.0 Instagram API uses to authenticate and authorize the user’s. You can smoothly execute the Login with Instagram using Instagram API with PHP. In this article, we will discuss how to merge Login using Instagram wit PHP. The cURL is an easy and efficient way to access the Instagram API in PHP. We will use cURL to join the Instagram API using PHP.

The following functionality will be performed in the sample Instagram OAuth script.

  • Authenticate with Instagram account with access_token.
  • Fetch the user’s profile data from Instagram account.
  • Save profile data in the Db with PHP and MySQL.
  • Display the user’s account information.


Earlier you begin to integrate Instagram Login with PHP, take a look at the file structure.

Register Instagram Client ID


The Client ID and Secret are needed to access the Instagram API. Earlier making started to execute Instagram Login using PHP on the website, follow the given steps to register a new Instagram Client, and get the Secret and Client ID.

  • Go to the Instagram Developer Panel.
  • Create an account as a developer and login to developer account.
  • Go to the Manage Clients page, click on Register a New Client.
  • Give the Application information and click the Register to submit button.
  • The Valid redirect URIs must be matching with the redirect URL defined at the time of API request.
  • Followed the App creation, it will be listed in the Guide Clients page. Click the MANAGE.

In the App details page, you will see the Client Secret and Client ID. Note given API credentials (Client Secret and Client ID ) for subsequently use in the script.

Create Database Table

To save the user profile info from Instagram, a table is needed in the DB. The given SQL generate a users table with a few basic fields in the MySQL database.

CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `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,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


Create Database Table



Instagram OAuth Library

The InstagramAuth class help us to authenticate with the Instagram API in PHP.

  • getAccessToken() – Fetch access_token from Instagram OAuth API (oauth/access_token) using PHP cURL.
  • getUserProfileInfo() – Retrieve the user profile record from Instagram User API (users/self) by access_token.
<?php 
/* 
 * Instagram API Class 
 * This class helps to authenticate with Instagram API 
 * @author    CodexWorld.com 
 * @url        http://www.codexworld.com 
 * @license    http://www.codexworld.com/license 
 */ 
class InstagramAuth { 
    public $client_id         = ''; 
    public $client_secret     = ''; 
    public $redirect_url     = ''; 
    private $act_url         = 'https://api.instagram.com/oauth/access_token'; 
    private $ud_url         = 'https://api.instagram.com/v1/users/self/'; 
     
    public function __construct(array $config = array()){ 
        $this->initialize($config); 
    } 
     
    public function initialize(array $config = array()){ 
        foreach ($config as $key => $val){ 
            if (isset($this->$key)){ 
                $this->$key = $val; 
            } 
        } 
        return $this; 
    } 
     
    public function getAuthURL(){ 
        $authURL = "https://api.instagram.com/oauth/authorize/?client_id=" . $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_SSL_VERIFYPEER, FALSE); 
        curl_setopt($ch, CURLOPT_POSTFIELDS, $urlPost);             
        $data = json_decode(curl_exec($ch), true);     
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);     
        curl_close($ch); 
        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);     
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
        $data = json_decode(curl_exec($ch), true); 
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);     
        curl_close($ch);  
        if($data['meta']['code'] != 200 || $http_code != 200){ 
            throw new Exception('Error : Failed to get user information'); 
        } 
        return $data['data']; 
    } 
}

User Class (User.class.php)

The User’s class managed the DB connected operations (insert, connect,and update) with PHP and MySQL.

  • __construct() – Connect to the MySQL database.
  • checkUser() – update or Insert the user account record (Instagram profile information) established on the OAuth provider and ID. Returns the user account record as an array.
<?php 
/* 
 * User Class 
 * This class is used for database related (connect, insert, and update) operations 
 * @author    CodexWorld.com 
 * @url        http://www.codexworld.com 
 * @license    http://www.codexworld.com/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(){ 
        if(!isset($this->db)){ 
            // Connect to the database 
            $conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName); 
            if($conn->connect_error){ 
                die("Failed to connect with MySQL: " . $conn->connect_error); 
            }else{ 
                $this->db = $conn; 
            } 
        } 
    } 
     
    function checkUser($userData = array()){ 
        if(!empty($userData)){ 
            // 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); 
            }else{ 
                // 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; 
    } 
}

Website Settings and API Configuration (config.php)

The DB settings and Instagram API configuration constant variables are specified in the config.php file.

Database Constants:

  • DB_HOST – Define the database host.
  • DB_USERNAME – Define the database username.
  • DB_PASSWORD – Define the database password.Instagram API Constants:
  • DB_NAME – Define the database name.
  • DB_USER_TBL – Define the table name where the user account data will be saved.

Instagram API Constants:

  • INSTAGRAM_CLIENT_ID – Define the Instagram Client ID.
  • INSTAGRAM_CLIENT_SECRET – Define the Instagram Client Secret.
  • INSTAGRAM_REDIRECT_URI – Define the Callback URL.


Initiate Instagram Auth class:
The Instagram Auth library is used to connect the Instagram API and working using OAuth client.

<?php 
/* 
 * 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 
if(!session_id()){ 
    session_start(); 
} 
 
/* 
 * 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 
)); 

Note that: You will find the Client and Client ID Secret on your Instagram Client settings page.

Login with Instagram and Get Account record (index.php)

In below file, the Instagram API authentication procedure is managed using PHP.

  • To begin with, the authentication URL is created using the getAuthURL() method of Instagram Auth class and the Instagram Sign-in button is displayed on the web page.
  • If the user authenticates with their own Instagram account, the given happens:
  • The access_token is restored using getAccessToken() by the code that collected during the authorization step.
  • The profile info is restored from the Instagram account using getUserProfileInfo() by the access_token.
  • The account data is inserted into the DB using checkUser() function of User class.
  • The user account data is saved in the PHP SESSION.
  • The Instagram profile details (ID, First name, Last name, Picture, and Profile link) are displayed on the web.
<?php 
// 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 
if(isset($_GET['code'])){ 
    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(); 
    } 
     
    if(!empty($userData)){ 
        $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 = 'https://www.instagram.com/'.$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>'; 
    }else{ 
        $output = '<h3 style="color:red">Instagram authentication has failed!</h3>'; 
        if(!empty($authErr)){ 
            $output = '<p style="color:red">'.$authErr.'</p>'; 
        } 
    } 
}else{ 
    // 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">
<head>
<title>Login with Instagram using PHP by CodexWorld</title>
<meta charset="utf-8">

<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
    <div class="inst-box">
        <!-- Display login button / Instagram profile information -->
        <?php echo $output; ?>
    </div>
</div>
</body>
</html>

Logout (logout.php)

If the user wants to log out from their Instagram account, the logout.php file is loaded.

  • Remove access token and user record from the SESSION.
  • Redirect the user’s to the home.
<?php 
// Remove user data from session 
unset($_SESSION['userData']); 
 
// Redirect to the homepage 
header("Location:index.php"); 
?>

Conclusion


This Instagram Auth library support you to merge Instagram login using PHP. In this tutorial code makes the Instagram API integration process easy using PHP cURL. You can simply execute the Instagram login in the website by some minimum API settings.






Like it? Share with your friends!

0
Developer

0 Comments