How To Login With Twitter Using Php

How To Login With Twitter Using Php

How To Login With Twitter Using Php

0 Sales


The big form is not a preferred way of registering the user on the website nowadays. Making the registration process short and easy for web users is always recommended. The method of fast sign-up helps increase the number of subscribers on your website. Login to the Social Media account is the easiest way to add a quick website sign-up process. Twitter is one of the internet's most popular social network and Twitter counts millions of users. Registering with Twitter is a quick and easy way to integrate the web application's user login system.


The Twitter API allows users to sign in without logging on your website for their Twitter account. Through the fast, easy and powerful way, Twitter OAuth PHP Library helps web developers integrate Twitter login system. In this example, we will demonstrate how user login with Twitter API can be implemented and user profile information can be stored in the MySQL database using PHP. In the Twitter login script example, we will use PHP to build Twitter Apps through the entire process and sign in with twitter. Our script that supports OAuth for the REST API of Twitter will use the Twitter OAuth PHP library.


Before you begin to integrate the Twitter OAuth login, take a look at the files structure.


├── config.php

├── index.php

├── logout.php

├── User.class.php

├── twitter-oauth-php/

├── images/

│   ├── twitter-login-btn.png

└── css/

    └── style.css


You need to create a Twitter App to access the Twitter API and define the User Key & Customer Secret when calling the Twitter API. If you have not already developed a Twitter App, follow the steps below to build and configure a Twitter App from the Application Management site.


  1. Go to the Developer account for Twitter and log in to your Twitter account.


  1. Click the button Create an app. You need to apply for a Developer account before you create a Twitter App. If you do not already have a Twitter Developer account, please provide the details you need to apply. Once Twitter has approved your developer account, create a new app.


  • Name: The name of your submission. It is shown in the OAuth dialog for the client on Twitter.

  • Definition: Description of your query. It is shown to the client during the authorization process.

  • URL of your website: URL of your web application.

  • Callback URL(*): This URL will be loaded with oauth token after authorization.


  1. Adjust app permission for direct messages to read and write or read, write and connect. You need to add a mobile number to your twitter account to change the app permission.


Once you have completed the development of the Twitter App, press Check OAuth to check OAuth. You'd be redirected to the OAuth Settings page after testing. Switch to the tab Keys and tokens, you will see the keys provided by the User API. For future use in the file, copy this API key (Consumer key) and API secret key (Consumer secret).


Create Database Table

A table must be created in the database to store user profile information from the Twitter account. The following SQL creates a user table in the MySQL database with some basic fields.


CREATE TABLE `users` (


 `oauth_provider` enum('','facebook','google','twitter') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'twitter',

 `oauth_uid` varchar(50) COLLATE utf8_unicode_ci NOT NULL,

 `first_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,

 `last_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,

 `email` varchar(25) COLLATE utf8_unicode_ci DEFAULT NULL,

 `gender` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,

 `locale` varchar(10) COLLATE utf8_unicode_ci NOT NULL,

 `picture` varchar(200) COLLATE utf8_unicode_ci NOT NULL,

 `username` varchar(50) COLLATE utf8_unicode_ci NOT NULL,

 `link` varchar(100) COLLATE utf8_unicode_ci NOT NULL,

 `created` datetime NOT NULL,

 `modified` datetime NOT NULL,


) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


Twitter OAuth Library for PHP

The directory of twitter-oauth-php/ contains the library of Twitter OAuth that helps to integrate the Twitter API into PHP. You don't have to install the Twitter PHP OAuth library separately, all the files you want are included in our PHP source code for Twitter Login.


User Class (User.class.php)


The client class uses PHP and MySQL to manage the operations related to the server (connect, add, and update). It used to connect the database and insert / update the user table's Twitter account data.


  1. construct() –The MySQL database is connected.

  2. CheckUser() –Insert or update the OAuth Provider and ID-based user profile data. Gives the account data of the consumer as a set.




 * 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']."', locale = '".$userData['locale']."', picture = '".$userData['picture']."', username = '".$userData['username']."', 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']."', locale = '".$userData['locale']."', picture = '".$userData['picture']."', username = '".$userData['username']."', 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 constant variables for database settings and configuration of the Twitter API are specified in the config.php file.

Constants of the server: 

  • DB HOST–Specify the host of the database.

  • DB USERNAME–Enter the username of the server.

  • DB PASSWORD–Specify the password for the server.

  • DB NAME–Enter the name of the server.

  • DB USER TBL–Specify the name of the table that will store the account data of the user.


Twitter API Constants: 

  • TW CONSUMER KEY–Specify App Key for Twitter. 

  • TW CONSUMER SECRET–Specify App Secret for Twitter.

  • TW REDIRECT URL–The callback URL is defined.


Call Twitter API:

The PHP OAuth library is used to connect to the Twitter API and to work with the OAuth server.




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


// Twitter API configuration 

define('TW_CONSUMER_KEY', 'Insert_Twitter_API_Key'); 

define('TW_CONSUMER_SECRET', 'Insert_Twitter_API_Secret'); 

define('TW_REDIRECT_URL', 'Callback_URL'); 


// Start session 





// Include Twitter client library  

require_once 'twitter-oauth-php/twitteroauth.php';

Login & Get Twitter Account Data (index.php)


This file uses PHP to handle the process of authenticating the Twitter API.


  1. The authentication URL is initially generated using the TwitterOAuth class method getAuthorizeURL) (and the Twitter button Sign in is displayed on the web page.


  1. If your Twitter account is authenticated by the user, the following will happen:


  • The profile information is fetched from the Twitter account using Twitter API.

  • The account data is inserted into the database using checkUser) (function of the User class.

  • The user's account information is stored in the SESSION.

  • The Twitter profile details (First name, Last name, Username, Locale, Picture, and Profile link) is displayed on the webpage.


  1. Also, the latest tweets and tweet posting form will be displayed. 


  • Using the Tweet form, the user logged in can post Tweet to their Twitter account from the website.



// Include configuration file 

require_once 'config.php'; 


// Include User class 

require_once 'User.class.php'; 


// If OAuth token not matched 

if(isset($_REQUEST['oauth_token']) && $_SESSION['token'] !== $_REQUEST['oauth_token']){ 

    //Remove token from session 





// If user already verified  

if(isset($_SESSION['status']) && $_SESSION['status'] == 'verified' && !empty($_SESSION['request_vars'])){ 

    //Retrive variables from session 

    $username         = $_SESSION['request_vars']['screen_name']; 

    $twitterId        = $_SESSION['request_vars']['user_id']; 

    $oauthToken       = $_SESSION['request_vars']['oauth_token']; 

    $oauthTokenSecret = $_SESSION['request_vars']['oauth_token_secret']; 

    $name             = $_SESSION['userData']['first_name'].' '.$_SESSION['userData']['last_name']; 

    $profilePicture   = $_SESSION['userData']['picture']; 



     * Prepare output to show to the user 


    $twClient = new TwitterOAuth(TW_CONSUMER_KEY, TW_CONSUMER_SECRET, $oauthToken, $oauthTokenSecret); 


    //If user submits a tweet to post to twitter 


        $my_update = $twClient->post('statuses/update', array('status' => $_POST["updateme"])); 



    // Display username and logout link 

    $output = '<div class="welcome_txt">Welcome <strong>'.$username.'</strong> (Twitter ID : '.$twitterId.'). <a href="logout.php">Logout</a>!</div>'; 


    // Display profile iamge and tweet form 

    $output .= '<div class="tweet_box">'; 

    $output .= '<div class="left">'; 

    $output .= '<img src="'.$profilePicture.'" width="120" height="110"/>'; 

    $output .= '<p>'.$name.'</p>'; 

    $output .= '</div>'; 

    $output .= '<form method="post" action=""><table width="200" border="0" cellpadding="3">'; 

    $output .= '<tr>'; 

    $output .= '<td><textarea name="updateme" cols="60" rows="4"></textarea></td>'; 

    $output .= '</tr>'; 

    $output .= '<tr>'; 

    $output .= '<td><input type="submit" value="Tweet" /></td>'; 

    $output .= '</tr></table></form>'; 

    $output .= '</div>'; 


    // Get latest tweets 

    $myTweets = $twClient->get('statuses/user_timeline', array('screen_name' => $username, 'count' => 5)); 


    // Display the latest tweets 

    $output .= '<div class="tweet_list"><strong>Latest Tweets : </strong>'; 

    $output .= '<ul>'; 

    foreach($myTweets  as $tweet){ 

        $output .= '<li>'.$tweet->text.' <br />-<i>'.$tweet->created_at.'</i></li>'; 


    $output .= '</ul></div>'; 

}elseif(isset($_REQUEST['oauth_token']) && $_SESSION['token'] == $_REQUEST['oauth_token']){ 

    // Call Twitter API 

    $twClient = new TwitterOAuth(TW_CONSUMER_KEY, TW_CONSUMER_SECRET, $_SESSION['token'] , $_SESSION['token_secret']); 


    // Get OAuth token 

    $access_token = $twClient->getAccessToken($_REQUEST['oauth_verifier']); 


    // If returns success 

    if($twClient->http_code == '200'){ 

        // Storing access token data into session 

        $_SESSION['status'] = 'verified'; 

        $_SESSION['request_vars'] = $access_token; 


        // Get user profile data from twitter 

        $userInfo = $twClient->get('account/verify_credentials'); 


        // Initialize User class 

        $user = new User(); 


        // Getting user's profile data 

        $name = explode(" ",$userInfo->name); 

        $fname = isset($name[0])?$name[0]:''; 

        $lname = isset($name[1])?$name[1]:''; 

        $profileLink = ''.$userInfo->screen_name; 

        $twUserData = array( 

            'oauth_uid'     => $userInfo->id, 

            'first_name'    => $fname, 

            'last_name'     => $lname, 

            'locale'        => $userInfo->lang, 

            'picture'       => $userInfo->profile_image_url, 

            'link'          => $profileLink, 

            'username'      => $userInfo->screen_name 



        // Insert or update user data to the database 

        $twUserData['oauth_provider'] = 'twitter'; 

        $userData = $user->checkUser($twUserData); 


        // Storing user data into session 

        $_SESSION['userData'] = $userData; 


        // Remove oauth token and secret from session 




        // Redirect the user back to the same page 

        header('Location: ./'); 


        $output = '<h3 style="color:red">Some problem occurred, please try again.</h3>'; 



    // Fresh authentication 

    $twClient = new TwitterOAuth(TW_CONSUMER_KEY, TW_CONSUMER_SECRET); 

    $request_token = $twClient->getRequestToken(TW_REDIRECT_URL); 


    // Received token info from twitter 

    $_SESSION['token']         = $request_token['oauth_token']; 

    $_SESSION['token_secret']= $request_token['oauth_token_secret']; 


    // If authentication returns success 

    if($twClient->http_code == '200'){ 

        // Get twitter oauth url 

        $authUrl = $twClient->getAuthorizeURL($request_token['oauth_token']); 


        // Display twitter login button 

        $output = '<a href="'.filter_var($authUrl, FILTER_SANITIZE_URL).'"><img src="images/twitter-login-btn.png" /></a>'; 


        $output = '<h3 style="color:red">Error connecting to Twitter! Try again later!</h3>'; 




<!DOCTYPE html>

<html lang="en-US">


<title>Login with Twitter using PHP by CodexWorld</title>

<meta charset="utf-8">



<div class="container">

    <!-- Display login button / Twitter profile information -->

    <?php echo $output; ?>




Logout (logout.php)


The user is logged out of the Twitter account using the logout.php file.


  • Remove SESSION access token, hidden token and user data.

  • Turn the user back to the homepage.



// Start session 





// Remove user data from session 



// Destroy all session data 



// Redirect to the homepage 



Retrieve User Email from Twitter Account


Generally, after authentication, Twitter will not return the user's email. Your software must be whitelisted by Twitter to get the user's email address with the Twitter API. Follow the steps below to get and store the email address of the user.


  1. To send your application, use this form. Please be patient a few times.

  2. When whitelisted, the client checkbox Request email addresses will be available on the Permissions tab in the Additional permissions page.


  • To allow additional permissions, you need to include a Terms of Service URL and Privacy Policy URL in the description of the App.


  1. Add provide email parameter to get() in the index.php file. To do this, replace the variable value of $userInfo with the following code section.


$userInfo = $twClient->get('account/verify_credentials', ['include_email' => 'true']);


  1. Now you can use $userInfo->email to get the user's email address from Twitter. In the $twUserData set, add the user's address ($userInfo->email).

$twUserData = array(

    'oauth_uid'     => $userInfo->id,

    'first_name'    => $fname,

    'last_name'     => $lname,

    'email'         => $userInfo->email,

    'locale'        => $userInfo->lang,

    'picture'       => $userInfo->profile_image_url,

    'link'          => $profileLink,

    'username'      => $userInfo->screen_name



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


Create Date : May 14, 2020

Updated Date : May 14, 2020


Comments : 0

Downloads : 0