AllsWeb Blog
No Result
View All Result
  • Home
  • Main Home
  • PHP and MySQL
  • JavaScript
    • jQuery & AJAX
  • WordPress
  • SEO
  • Web Hosting
  • Comparison
Support
Knowledgebase
  • Home
  • Main Home
  • PHP and MySQL
  • JavaScript
    • jQuery & AJAX
  • WordPress
  • SEO
  • Web Hosting
  • Comparison
No Result
View All Result
AllsWeb White Logo
No Result
View All Result
Home PHP and MySQL

Login with Twitter using PHP

Create a Twitter App

Lakshika Mathur by Lakshika Mathur
December 14, 2019
Reading Time: 12 mins read
0
Login with Twitter using PHP

Nowadays, the significant form is not a preferred way to register the user on the website. It is always suggested that making the registration process more accessible and short for website users. So, the fast signup process helps to increase the number of a subscriber on your website. Login with Social media account is the quickest way to add a short signup process on the site. In this tutorial, we will learn Login with Twitter using PHP, Twitter is one of the most renowned social networks on the internet. Therefore, lakhs of users are registered with Twitter. Sign in with Twitter is a fast and straightforward way to integrate the user login system on the website.

Twitter API permits the website visitors to log in with their Twitter account without register on your website. Twitter OAuth PHP Library helps web developers to integrate the Twitter login system in the quick, easy, and compelling way. With the help of this tutorial, we’ll show how to implement user Login with Twitter API. Also, to store the user profile information into the MySQL database by using PHP. In the example 

Twitter login script, we will go through the whole process of creating Twitter apps and implementing Sign in with Twitter using PHP. We will use the Twitter OAuth PHP library in our script that supports OAuth for Twitter’s Twitter REST API.

Before proceeding to integrate the Twitter OAuth login, let’s have a look at the file structure.

twitter_login_php/
├── config.php
├── index.php
├── logout.php
├── User.class.php
├── twitter-oauth-php/
├── images/
│   ├── twitter-login-btn.png
└── css/
    └── style.css

Create a Twitter App

To access the Twitter API, you must create a Twitter App. After that, specify the consumer key and consumer secret at the time of creating the Twitter API. If you have not created the Twitter app already, then follow the steps given below to create and configure Twitter App from the Application Management page.

  • Go to the Twitter Developer account and log in with your Twitter account.
  • Click on the Create App button. Before creating a Twitter App, you have to apply for a developer account. If you do not already have a Twitter developer account, please provide the necessary details to use. Once Twitter approves your developer account, create a new app.
    • Name: It is your application Name. You can show it to the user in the Twitter OAuth dialog.
    • Description: It is your application Description. You can show it to the user while authorizing it.
    • Website URL: It is your web application URL.
    • Callback URL(*): After authorization, this URL is loaded with oauth_token
    • Now, Change the apps permission to Read and Write or Read, Write, and Access direct messages. To change the permissions of apps, you will need to add a mobile number to your Twitter account.

Once the creation of the Twitter app is complete, click on OAuth to test OAuth. After verifying, you will be directed to the OAuth Settings page. Switch to the Key and Token tabs. You will see that the consumer API key is generated. Copy this API key (consumer key) and API secret key (consumer secret) to use it later in the script.

Create Database Table

You need to create a table in the database to store the user profile information from the Twitter account. The following SQL creates a user table with some necessary fields in the MySQL database.

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

Twitter OAuth Library for PHP

The Twitter-OAuth-Php / directory has the Twitter OAuth library that helps integrate the Twitter API with PHP. You do not need to download the Twitter PHP OAuth library separately, and all the necessary files are placed in our Twitter login PHP source code.

User Class (User.class.php)

The User class handles the operations related to database (connect, insert, and update) using PHP and MySQL. It is used to add databases and insert/update Twitter account data in a user’s static.

  • __construct() – Connect to the MySQL database.
  • checkUser() – Insert or update user profile data based on OAuth provider and ID. Returns user account data as an array.

Site Settings and API Configuration (config.php)

The config.php file defines the database variable and the constant variable for the Twitter API configuration.

<?php 
/* 
 * User Class 
 * This class is used for database related (connect, insert, and update) operations 
 * @author    Allsweb.com 
 * @url        http://www.allsweb.com 
 * @license    http://www.allsweb.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']."', 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); 
            }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']."', 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; 
    } 
}

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 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:

  •  To connect with Twitter API and to work with OAuth client you have to use the PHP OAuth library is used

Note: You will get Consumer Key and Consumer Secret from the Keys and Token page of your Twitter app.

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

  • Firstly, generate the authentication URL using getAuthorizeURL() method of TwitterOAuth class and Sign in with Twitter button is displayed on the web page.
  • Now, if the user authenticates with their Twitter account, the following things will happen:
    • Information on the profile is fetched from the Twitter account using Twitter API.
    • Insert the account data into the database using checkUser() function of the User class.
    • Store the user account information in the SESSION.
    • The Twitter profile details (First name, Username, Lastname Locale, Profile link, and Pictures) displays on the webpage.
  • Moreover, the latest tweets and tweet posting form will be displayed.
    • Using the tweet form, logged-in users will be able to post tweets from the website to their Twitter account.
      <?php 
      // 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 
          unset($_SESSION['token']); 
          unset($_SESSION['token_secret']); 
      } 
       
      // 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 
          if(isset($_POST["updateme"])){ 
              $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 
              unset($_SESSION['token']); 
              unset($_SESSION['token_secret']); 
               
              // Redirect the user back to the same page 
              header('Location: ./'); 
          }else{ 
              $output = '<h3 style="color:red">Some problem occurred, please try again.</h3>'; 
          } 
      }else{ 
          // 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>'; 
          }else{ 
              $output = '<h3 style="color:red">Error connecting to Twitter! Try again later!</h3>'; 
          } 
      } 
      ?>
      
      <!DOCTYPE html>
      <html lang="en-US">
      <head>
      <title>Login with Twitter using PHP by Allsweb</title>
      <meta charset="utf-8">
      </head>
      <body>
      <div class="container">
          <!-- Display login button / Twitter profile information -->
          <?php echo $output; ?>
      </div>
      </body>
      </html>

       

Logout (logout.php)

We have to use the logout.php file for logging the user out from the Twitter account.

RELATED POSTS

What is Application Programming Interface (APIs)?

Like Dislike Rating System with jQuery, Ajax, and PHP

Star Rating System with jQuery, Ajax, PHP, and MySQL

  • Delete access token, token secret, and user data from the SESSION.
  • Redirect the user to the homepage.
<?php 
// Start session 
if(!session_id()){ 
    session_start(); 
} 
 
// Remove user data from session 
unset($_SESSION['userData']); 
 
// Destroy all session data 
session_destroy(); 
 
// Redirect to the homepage 
header("Location:index.php"); 
?>

Retrieve User Email from Twitter Account

Twitter doesn’t return the user’s email after authentication. You need to whitelist the application by Twitter to obtain the user’s email address with the Twitter API. To understand and store the user email address, follow the steps below.

Retrieve User Email from Twitter Account
Retrieve User Email from Twitter Account
  1. Use this form to submit your request. It will take some time. Please be patient.
  2. Once whitelisted, the Request email addresses from the user’s checkbox will be available under the Additional permissions section on the Permissions tab. Now, you just need to add a Terms of Service URL and Privacy Policy URL in App details to enable additional permissions.
  3. 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']);
  4. 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 user’s table, so you done don’t need to alter the database table structure.

Conclusion

Firstly, We’ve tried to make the Twitter login integration process simple as much as possible. Using our script, you can easily add a Twitter login system to your website using PHP and MySQL. Secondly, include all the required files in our source code, including Twitter OAuth Library. In addition, you only need to configure some minimal settings to integrate Sign in with Twitter using OAuth client and PHP.

Also, read our previous blog- Login with Facebook using PHP

  • Login with Instagram using JavaScript SDK

  • Login with Instagram using PHP

  • Login with LinkedIn using JavaScript SDK

  • Login with GitHub OAuth API using PHP

  • Login with Twitter using PHP

Tags: PHPTwitter
ShareTweetSendShareSharePinScan
Lakshika Mathur

Lakshika Mathur

Related Posts

What is Application Programming Interface (APIs), Types, and Importance.
PHP and MySQL

What is Application Programming Interface (APIs)?

January 29, 2022
61
Like Dislike Rating System with jQuery, Ajax, and PHP
jQuery & AJAX

Like Dislike Rating System with jQuery, Ajax, and PHP

January 6, 2020
739
Star Rating System with jQuery, Ajax, PHP, and MySQL
jQuery & AJAX

Star Rating System with jQuery, Ajax, PHP, and MySQL

January 6, 2020
162
How to Force Download File in PHP
PHP and MySQL

How to Force Download File in PHP

January 2, 2020
82
How to Connect to the Remote MySQL Database using PHP
PHP and MySQL

How to Connect to the Remote MySQL Database using PHP

January 1, 2020
28
How to Generate QR Code with PHP using Google Chart API
PHP and MySQL

How to Generate QR Code with PHP using Google Chart API

January 1, 2020
83
Next Post
Login with GitHub OAuth API using PHP

Login with GitHub OAuth API using PHP

Login with LinkedIn using JavaScript SDK

Login with LinkedIn using JavaScript SDK

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Categories

  • Comparison (3)
  • HTML & CSS (9)
  • Interesting Facts (1)
  • JavaScript (27)
    • jQuery & AJAX (18)
  • PHP and MySQL (48)
  • Security (10)
  • SEO (2)
  • Trademark (2)
  • Tutorials (5)
  • Uncategorized (1)
  • Web Hosting (19)
    • VPS Server (5)
  • WordPress (8)

Recent Posts

  • Is the Trademark valuable to your Brand or domain?
  • Ideas For Ten Fantastic Online Business From Home
  • Some best free WordPress Themes for Affiliate Marketing Websites
  • Home
  • Posts
  • Privacy Policy
  • Terms and Conditions

Built and Maintained With ♥ by AllsWeb Team

No Result
View All Result
  • Home
  • Main Home
  • PHP and MySQL
  • JavaScript
    • jQuery & AJAX
  • WordPress
  • SEO
  • Web Hosting
  • Comparison

Built and Maintained With ♥ by AllsWeb Team

Go to mobile version