Login with Twitter using PHP


Twitter is one of the most popular social network on the internet and millions of users are registered with twitter. You can increase the subscriber number of your website using Twitter Login. Nowadays users are not interested in filling the big registration forms. Twitter Login API helps to solve this problem. Twitter API allow your website visitors to log in with their Twitter account at your site without register in your website.

Twitter OAuth PHP library helps web developer to integrate twitter login system by the quick, easy and powerful way. In this tutorial, we’ll show how to implement user Login with Twitter API and store the user information into the MySQL database using PHP. We will go through the complete process to create Twitter Apps and implement sign in with twitter using PHP. The Twitter OAuth PHP library will be used in our script that supports OAuth for Twitter’s REST API.

Before you get started, take a look at the folders and files structure of our Twitter OAuth login script.

  • src/
    • OAuth.php
    • twitteroauth.php
  • User.php
  • twConfig.php
  • index.php
  • logout.php
  • images/
  • style.css

Twitter Apps Creation

To access Twitter API you need to create a Twitter App and get the Consumer key & Consumer secret. If you haven’t already created a Twitter App, follow the below steps to creating and configure a Twitter App from the Application Management page.

  • At first go to the Application Management page and login with your Twitter account.
  • Create New App with the following details.
    • Name: Your application Name. This is shown to the user while authorizing.
    • Description: Your application Description. This is shown to user while authorizing.
    • Website: Your application website.
    • Callback URL(*): After authorization, this URL is called with oauth_token.
  • Change the apps permission to Read and Write or Read, Write and Access direct messages. For changing the apps permission, you need to add a mobile number to your twitter account.

Once Twitter App creation is completed, click on Test OAuth for testing OAuth. After testing you would be redirected to the OAuth Settings page. From the OAuth Settings page, you’ll get the Consumer key and Consumer secret. Note this Consumer key and Consumer secret for later use in the script.

Are you want to get a detailed guide on Twitter App creation? See this guide to create Twitter OAuth Application.

Database Table Creation

To store the user information from the Twitter database, a table (users) need to be created in your MySQL database. At first, create a database (like codexworld) and run the below SQL on the database. The following SQL creates a users table with some basic fields in the database to hold the Twitter profile information.

CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `oauth_provider` enum('','facebook','google','twitter','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,
 `gender` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
 `locale` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
 `picture` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `username` varchar(100) 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;

Twitter OAuth PHP

The src/ directory contains the Twitter OAuth library for PHP and all the related files are included in our source code.

User Class (User.php)

The User class is used to insert or update Twitter profile information to the database using PHP and MySQL. Specify your MySQL database credentials ($dbHost, $dbUsername, $dbPassword, and $dbName) and table name ($userTbl) to store the user’s profile information.

<?php
class User {
    private 
$dbHost     "localhost";
    private 
$dbUsername "root";
    private 
$dbPassword "*****";
    private 
$dbName     "codexworld";
    private 
$userTbl    'users';
    
    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 = '".date("Y-m-d H:i:s")."' 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 = '".date("Y-m-d H:i:s")."', modified = '".date("Y-m-d H:i:s")."'";
                
$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;
    }
}
?>

Twitter API Configuration (twConfig.php)

In twConfig.php file, define the Consumer Key ($consumerKey), Consumer Secret ($consumerSecret), and Callback URL ($redirectURL) of your Twitter App to connect with Twitter API.

<?php
session_start
();

//Include Twitter client library 
include_once 'src/twitteroauth.php';

/*
 * Configuration and setup Twitter API
 */
$consumerKey    'InsertYourConsumerKey';
$consumerSecret 'InsertYourConsumerSecret';
$redirectURL    'http://localhost/twitter_login_php/';

?>

Note that: You’ll find the Consumer Key and Consumer Secret on Twitter OAuth Settings page.

Twitter Authentication & Profile Information (index.php)

Initially, the Sign in with Twitter button will be shown. Once the user authenticates with their Twitter account, the profile information will be fetched and pass to the User class for inserting into the database. Also, the profile details, latest tweets, and tweet post option with logout button will be displayed.

<?php
//start session
session_start();

//Include Twitter config file && User class
include_once 'twConfig.php';
include_once 
'User.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'];
    
$profilePicture   $_SESSION['userData']['picture'];
    
    
/*
     * Prepare output to show to the user
     */
    
$twClient = new TwitterOAuth($consumerKey$consumerSecret$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 .= '<img src="'.$profilePicture.'" width="120" height="110"/>';
    
$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($consumerKey$consumerSecret$_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();
        
        
//Insert or update user data to the database
        
$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_provider'=> 'twitter',
            
'oauth_uid'     => $userInfo->id,
            
'first_name'    => $fname,
            
'last_name'     => $lname,
            
'email'         => '',
            
'gender'        => '',
            
'locale'        => $userInfo->lang,
            
'picture'       => $userInfo->profile_image_url,
            
'link'          => $profileLink,
            
'username'      => $userInfo->screen_name
        
);
        
        
$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($consumerKey$consumerSecret);
    
$request_token $twClient->getRequestToken($redirectURL);
    
    
//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($authUrlFILTER_SANITIZE_URL).'"><img src="images/sign-in-with-twitter.png" width="151" height="24" border="0" /></a>';
    }else{
        
$output '<h3 style="color:red">Error connecting to twitter! try again later!</h3>';
    }
}
?>
<!DOCTYPE html> <html lang="en"> <head>     <meta charset="utf-8">     <title>Login with Twitter using PHP by CodexWorld</title>     <link rel='stylesheet' type='text/css' href='style.css'> </head> <body>     <!-- Display login button / profile information -->
    <?php echo $output?>
</body> </html>

Logout (logout.php)

This file is used to logout the user from their Twitter account.

<?php
//Start session
session_start();

//Remove user data from session
unset($_SESSION['userdata']);

//Destroy all session data
session_destroy();

//Redirect to the homepage
header("Location:index.php");
?>

Getting User Email from Twitter Account

Basically, Twitter doesn’t return the user email after authentication. To get the user’s Email Address, your application needs to be whitelisted by Twitter. To get and store the user email address, follow the below steps.

  • Use this form to submit your request. It will take some times please be patient.
  • Once whitelisted, the Request email addresses from users checkbox will be available under your app permission on Application Management. Under settings, Privacy Policy URL and Terms of Service URL fields will be available. If enabled, users will be informed that your app can access their email on the OAuth dialog.
  • Open the index.php file and use include_email parameter in get() function. To do that replace $user_info variable line value with the following line of code (probably line no. 74).
    $userInfo $connection->get('account/verify_credentials', ['include_email' => 'true']);
  • Now you can get the user email address using $userInfo->email. Provide the user email ($userInfo->email) in $twUserData array.

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

Conclusion

We’ve tried to make Twitter login integration process simple as much as possible. Using our script, you can easily add Twitter login system to your website. You only need to include few files and specify some minimal settings for integrate login system with Twitter using PHP.

Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request

Recommended Tutorials For You

30 Comments

  1. Mrutyunjaya Behera Said...
  2. Parul Said...
  3. Ibrahim Said...
  4. Arsh Said...
  5. Gurpreet Said...
  6. Jeena Said...
  7. Jo Miller Said...
    • CodexWorld Said...
  8. Jo Miller Said...
  9. Jayendra Said...
    • CodexWorld Said...
  10. Jayendra Said...
  11. Gaurav Said...
  12. Nirav Said...
  13. Parag Said...
  14. Parag Said...
    • CodexWorld Said...
  15. Alex Said...
  16. Valentin Said...
  17. Khalid Said...
  18. Duwi Said...
    • CodexWorld Said...
  19. Dharmendra Said...
    • CodexWorld Said...
  20. Gaurav Pachani Said...
  21. Freddy Sidauruk Said...
  22. Freddy Sidauruk Said...
    • CodexWorld Said...

Leave a reply