Login with Twitter using PHP


Currently, registering with a big form is not the preferred method of registering a user on a website. It’s always recommended to make the registration process simple and short for web users. You can increase the number of subscribers on your website by providing a quick signup process.


You can easily add a short sign-up process on the website by allowing visitors to sign up with their Social media accounts. In the world of social networking, Twitter is one of the most popular social networks and is used by millions of people on a daily basis. This is a simple and quick way to implement a user login system for a web application that can be accessed via Twitter.

The Twitter API lets website visitors log in with their Twitter accounts without having to register on your website. With the Twitter OAuth PHP Library, web developers can easily and quickly implement the Twitter login process to their websites with just a few clicks.

With the help of this tutorial, you will learn how to implement user login using the Twitter API and how to store user profile data into a MySQL database using PHP. For the purpose of this example Twitter login script, we’ll take you through the complete process of creating Twitter Apps and how to implement Twitter login using PHP. We will be using the Twitter OAuth PHP library in our script to enable us to authenticate against Twitter’s REST API using OAuth.

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

Create Twitter App

If you haven’t already done so, follow the following steps to create and configure a Twitter App from Application Management. In order to use Twitter API, a Twitter App must be created and its Consumer key & Consumer secret specified.

  1. Log in with your Twitter account on the Twitter Developer account.
  2. Create an app by clicking the Create an app button. You must apply for a developer account before creating a Twitter App. Please provide the required details if you do not already have a Twitter Developer account. You can then create a newly created app after your developer account has been approved.
    1. Name: The name of your application. It is displayed in the Twitter OAuth dialog.
    2. Description: This is your application description. It is displayed to the user during the authorization process.
    3. Website URL: The address of your web application.
    4. Callback URL(*): After authorization, this URL is loaded with oauth_token.
  3. Set the app permission to Read and Write or to Read, Write, and Access direct messages. The twitter app permission can only be changed if your Twitter account has a mobile phone number.

Click Test OAuth for testing OAuth once you have created the Twitter App. The page for OAuth settings will appear once you have completed the testing. You will see the Consumer API keys generated on the Keys and Tokens tab. For the script, you need to copy the API secret key (Consumer secret) and API key (Consumer key).

To test OAuth, click on Test OAuth once you’ve created a Twitter App. Your OAuth settings page will appear once testing is completed. The Consumer API keys are generated on the Keys and Tokens tab. The API key (Consumer key) and API secret key (Consumer secret) should be copied.


Create Database Table

In the database, a table needs to be created to store the user profile information from Twitter accounts. SQL creates a users 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;

OAuth Library for Twitter

In PHPTwitter OAuth Library for PHP is contained in the twitter-oauth-php/ directory. This library can be used to integrate Twitter API with PHP. All the required files are included in our Twitter Login PHP source code, so you don’t need to download the Twitter PHP OAuth library separately.

User Class (User.class.php)

MySQL and PHP are used to handle the database related operations (connect, insert, and update). The method is used to update or insert Twitter account data into the users table by connecting to the database.

__construct() – Connect to the MySQL

database.checkUser() – Insert or update the user profile data based on the OAuth provider and ID. Returns the user’s account data as an array.

 * 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(){ 
            // 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($data = array()){  
            // Check whether the user already exists in the database  
            $checkQuery = "SELECT * FROM ".$this->userTbl." WHERE oauth_provider = '".$data['oauth_provider']."' AND oauth_uid = '".$data['oauth_uid']."'";  
            $checkResult = $this->db->query($checkQuery);  
            // Add modified time to the data array  
                $data['modified'] = date("Y-m-d H:i:s");  
            if($checkResult->num_rows > 0){  
                // Prepare column and value format  
                $colvalSet = '';  
                $i = 0;  
                foreach($data as $key=>$val){  
                    $pre = ($i > 0)?', ':'';  
                    $colvalSet .= $pre.$key."='".$this->db->real_escape_string($val)."'";  
                $whereSql = " WHERE oauth_provider = '".$data['oauth_provider']."' AND oauth_uid = '".$data['oauth_uid']."'";  
                // Update user data in the database  
                $query = "UPDATE ".$this->userTbl." SET ".$colvalSet.$whereSql;  
                $update = $this->db->query($query);  
                // Add created time to the data array  
                    $data['created'] = date("Y-m-d H:i:s");  
                // Prepare column and value format  
                $columns = $values = '';  
                $i = 0;  
                foreach($data as $key=>$val){  
                    $pre = ($i > 0)?', ':'';  
                    $columns .= $pre.$key;  
                    $values  .= $pre."'".$this->db->real_escape_string($val)."'";  
                // Insert user data in the database  
                $query = "INSERT INTO ".$this->userTbl." (".$columns.") VALUES (".$values.")";  
                $insert = $this->db->query($query);  
            // Get user data from the database  
            $result = $this->db->query($checkQuery);  
            $userData = $result->fetch_assoc();  
        // Return user data  
        return !empty($userData)?$userData:false;  

Site Settings and API Configuration (config.php)

In the config.php file, The constant variables are defined for database settings and Twitter API configuration.
Database Constants:

  • DB_HOST – Specify the database host.
  • DB_USERNAME – Specify the database username.
  • DB_PASSWORD – Specify the database password.
  • DB_NAME – Specify the database name.
  • DB_USER_TBL – Specify the table name where the user’s account data will be stored.

Twitter API Constants:

  • TW_CONSUMER_KEY – Specify the Twitter App ID.
  • TW_CONSUMER_SECRET – Specify the Twitter App Secret.
  • TW_REDIRECT_URL – Specify the Callback URL.

Call Twitter API:

  • The PHP OAuth library is used to connect with Twitter API and working with OAuth client.
 * 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 handles the Twitter API authentication process using PHP.

  • Initially, the authentication URL is generated using getAuthorizeURL() method of TwitterOAuth class and Sign in with Twitter button is displayed on the web page.
  • If the user authenticates with their Twitter account, the following happens:
    • 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.
  • Also, the latest tweets and tweet posting form will be displayed.
    • Using the Tweet form, the logged-in user will be able to post Tweet from the website to their Twitter account.
// 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 = 'https://twitter.com/'.$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)

Logging out of a Twitter account is done through the logout.php file.

  1. Removing access tokens, token secrets, and user data from SESSION.
  2. Bring the user back to the home page.
// Start session 
// Remove user data from session 
// Destroy all session data 
// Redirect to the homepage 

Retrieving user email from Twitter accounts

In general, Twitter does not return the user’s email after authentication. You will need to be whitelisted by Twitter in order to get the user’s email address with Twitter API.

The steps below will show you how to do this.

  • Please fill out this form to submit your request. It will take some times please be patient.
  • On the Permissions tab, under Additional permissions there will be a checkbox to request users’ email addresses once whitelisted.
    1. To enable additional permissions, you need to add Terms of Service and Privacy Policy URLs in App details.


    • In the index.php file, add include_email parameter in get() function. To do that, replace the $userInfo variable value with the following line of code
    $userInfo = $twClient->get('account/verify_credentials', ['include_email' => 'true']);
  • Now you will be able to get the user email address from Twitter using $userInfo->email. Add the user’s email ($userInfo->email) in $twUserData array.
$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

The email field already added to the users table, so, you don’t need to alter the database table structure.


As much as possible, the Twitter login integration process has been simplified. We offer a PHP and MySQL script that allows you to easily add Twitter login functionality to your website. Our source code includes all the required files, including the Twitter OAuth Library. Sign in with Twitter using the OAuth client and PHP requires just a few settings.


Post a Comment (0)
Previous Post Next Post