loading

How to Login with Instagram using PHP

How to Login with Instagram using PHP

How to Login with Instagram using PHP

0 Sales

Free

The Instagram API makes it simple to add a user authentication system into a web application. Login via Instagram allows users to log into the website by authenticating using their Instagram account. The web application does not require user registration because the authentication procedure is handled via the Instagram API. The Instagram Login provides rapid access to the user without the need to create an account on the website.

To authenticate and authorise the user, the Instagram API employs OAuth 2.0. Using the Instagram API and PHP, you can quickly integrate the Login system. In this article, we'll teach you how to use PHP to connect Login with Instagram. cURL is a quick and easy way to use PHP to reach the Instagram API. To connect the Insta API in PHP, we will utilise cURL.

The following features will be included in the sample Instagram OAuth script.

 - Using access token, authenticate with your Instagram account.

 - Retrieve the user's profile information from their Instagram account.

 - Using PHP and MySQL, save profile data in a database.

 - Display the account details for the user.

Register Instagram Client ID

To use the Instagram API, you must have a Client ID and a Client Secret. Before you begin implementing Instagram Login with PHP on your website, complete the steps below to create a new Insta Client and obtain the Client ID and Password.

1. Navigate to Instagram's Developer Panel.

2. Create a profile as a programmer and sign in to your account.

3. Go to the Manage Clients page and press the Register a New Client button.

4. Fill out the Application Information and click the Register button to submit.

     - Valid redirect URIs must match the redirect URL supplied during the API call.

5. Following the development of the App, it will be featured in the Manage Clients page. Select MANAGE from the drop-down menu.

The Client ID and Client Password may be found on the App information page. Make a note of the API keys (Client ID and Client Secret) for subsequent usage in the script.

Create Database Table

A table in the database is necessary to record the user's Instagram profile information. In the MySQL database, the below SQL generates a customers table with the some basic columns.

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;

Instagram OAuth Library

The InstagramAuth class facilitates PHP authentication using the Instagram API.

 - getAccessToken() – Using PHP cURL, retrieve the access token via the Instagram OAuth API (oauth/access token).

 - getUserProfileInfo() – Retrieve the user's profile data via the Instagram User API (users/self) using the 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($chCURLOPT_URL$this->act_url);         
        curl_setopt($chCURLOPT_RETURNTRANSFER1); 
        curl_setopt($chCURLOPT_POST1);         
        curl_setopt($chCURLOPT_SSL_VERIFYPEERFALSE); 
        curl_setopt($chCURLOPT_POSTFIELDS$urlPost);             
        $data json_decode(curl_exec($ch), true);     
        $http_code curl_getinfo($chCURLINFO_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($chCURLOPT_URL$url);         
        curl_setopt($chCURLOPT_RETURNTRANSFER1);     
        curl_setopt($chCURLOPT_SSL_VERIFYPEERFALSE); 
        $data json_decode(curl_exec($ch), true); 
        $http_code curl_getinfo($chCURLINFO_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 class uses PHP and MySQL to perform database operations (login, edit, and update).

 - __construct() – Establish a connection to the MySQL database.

 - checkUser() – Based on the OAuth provider and ID, insert or update the user account data (Instagram profile information). As an array, this method returns the user's account info.

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

Site Settings and API Configuration (config.php)

The config.php file defines the database settings and Instagram API setup constant variables.

Constants in the database:

 - DB HOST – The database hostname.

 - DB USERNAME – Enter the database username here.

 - DB PASSWORD – Enter the database password here.

 - DB NAME – Enter the name of the database.

 - DB USER TBL – Enter the name of the table where the user's account data will be kept.

Constants in the Instagram API:

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

 - INSTAGRAM CLIENT SECRET – Enter the Instagram Client Secret here.

 - INSTAGRAM REDIRECT URI – Enter the Callback URL here.

Initiate Instagram Auth class:

The Instagram Auth module connects to the Instagram API and works with OAuth clients.

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

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

The Instagram API verification procedure is handled by PHP in this file.

 - Firstly, the authentication URL is produced using the Instagram Auth class's getAuthURL() function, and the Instagram Sign-in button is presented on the web page.

 - When a person authenticates their Instagram account, the following occurs:

      - The code returned during the authorisation phase uses getAccessToken() to retrieve the access token.

      - The access token retrieves the profile information from the Instagram account using getUserProfileInfo().

      - The checkUser() method of the User class is used to put the account data into the database.

      - The user's account information is saved in the PHP SESSION.

      - The homepage displays the Instagram profile data (First name,  Last name, ID, Picture, and Profile link).

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

The logout.php data is downloaded if the user decides to log out of their Instagram account.

 - Remove the SESSION's authentication token and user data.

 - Redirect the user to the website's main page.

Conclusion

Our Instagram Auth library makes it possible to connect Instagram login with PHP. Using PHP cURL, our sample code simplifies the Instagram API integration procedure. With a few API settings, you can quickly integrate Instagram login into your website. If you want to make the Instagram login process more user-friendly, utilise the JavaScript SDK to integrate Instagram Login without requiring a page refresh.

 

LICENSE OF USE

You can use it for personal or commercial projects. You can't resell it partially or in this form.

PRODUCT INFO

Create Date : Jan 24, 2022

Updated Date : Jan 24, 2022

Ratings

Comments : 0

Downloads : 0