Login with Twitter in CodeIgniter


Twitter is one of the popular and most used social networks. Millions of people around the world are connected with Twitter. When the login system integrated into your web application, login with Twitter surely helps to make login process smoother for the user. The main facility of Twitter login is the user does not need to create an account for log in your website. They can log into your website with their Twitter account. Also, you can get the user profile details from Twitter when they login with Twitter.

In our earlier Twitter login integration tutorial has shown how you can easily integrate Twitter login in PHP using Twitter OAuth PHP library. Today we’ll show you how to integrate Twitter login in CodeIgniter using Twitter OAuth PHP library and allow the user to login with Twitter in CodeIgniter application.

Twitter Apps Creation

Consumer Key and Consumer Secret is needed to use Twitter OAuth library and it can get from Twitter App. That’s why you need to create a Twitter App first.

  • Go to the Twitter Application Management page and sign in with your Twitter account credentials.
  • Enter the following details to create a new Twitter apps.
    • Name: Your application Name. This is shown to the user while authorizing.
    • Description: Your application Description. This is shown to the user while authorizing.
    • Website: Your application website. (http://example.com)
    • Callback URL(*): After authorization, this URL is called with oauth_token. (http://example.com/user_authentication/)
  • Change the apps permission to Read and Write or Read, Write and Access direct messages. For change the apps permission, you need to add a mobile number to your twitter account.
  • Now you should need to test the OAuthentication, click on Test OAuth and login with your twitter account for test OAuth. After completing you would be redirected to the OAuth Settings page. At the OAuth Settings page, you can see the Consumer Key (API Key) and Consumer Secret (API Secret).

Copy the Consumer Key and Consumer Secret for later use in the script.

Before you begin Twitter login integration process, take a look at the folders and files structure for Twitter login in CodeIgniter.

codeigniter-twitter-login-files-structure-codexworld

Database Table Creation

To store user profile information a table need to be created in the database. The following SQL creates users table with some required fields into the MySQL database.

CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `oauth_provider` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `oauth_uid` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `username` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `first_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `last_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `locale` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
 `picture_url` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `profile_url` 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;

Controllers (User_authentication.php)

User_Authentication controller contains 3 functions __construct(), index(), and logout().

  • __construct() Loads the User model for insert or update the user data into the database.
  • index() Connect with Twitter API, pass the user profile information to the User model, load the login link or profile details view, and pass the user data to the view – all of those functionalities are handled by this function.
  • logout() This function log out the user from their Twitter account.

In index() function, specify the Consumer Key ($consumerKey) and Consumer Secret ($consumerSecret) of your Twitter App. Also, don’t forget to update Callback URL in your Twitter App based on the $oauthCallback variable value.

<?php defined('BASEPATH') OR exit('No direct script access allowed');
class 
User_Authentication extends CI_Controller
{
    function 
__construct() {
        
parent::__construct();
        
//Load user model
        
$this->load->model('user');
    }
    
    public function 
index(){
        
$userData = array();
        
        
//Include the twitter oauth php libraries
        
include_once APPPATH."libraries/twitter-oauth-php-codexworld/twitteroauth.php";
        
        
//Twitter API Configuration
        
$consumerKey 'Insert_Twitter_API_Key';
        
$consumerSecret 'Insert_Twitter_API_Secret';
        
$oauthCallback base_url().'user_authentication/';
        
        
//Get existing token and token secret from session
        
$sessToken $this->session->userdata('token');
        
$sessTokenSecret $this->session->userdata('token_secret');
        
        
//Get status and user info from session
        
$sessStatus $this->session->userdata('status');
        
$sessUserData $this->session->userdata('userData');
        
        if(isset(
$sessStatus) && $sessStatus == 'verified'){
            
//Connect and get latest tweets
            
$connection = new TwitterOAuth($consumerKey$consumerSecret$sessUserData['accessToken']['oauth_token'], $sessUserData['accessToken']['oauth_token_secret']); 
            
$data['tweets'] = $connection->get('statuses/user_timeline', array('screen_name' => $sessUserData['username'], 'count' => 5));

            
//User info from session
            
$userData $sessUserData;
        }elseif(isset(
$_REQUEST['oauth_token']) && $sessToken == $_REQUEST['oauth_token']){
            
//Successful response returns oauth_token, oauth_token_secret, user_id, and screen_name
            
$connection = new TwitterOAuth($consumerKey$consumerSecret$sessToken$sessTokenSecret);
            
$accessToken $connection->getAccessToken($_REQUEST['oauth_verifier']);
            if(
$connection->http_code == '200'){
                
//Get user profile info
                
$userInfo $connection->get('account/verify_credentials');

                
//Preparing data for database insertion
                
$name explode(" ",$userInfo->name);
                
$first_name = isset($name[0])?$name[0]:'';
                
$last_name = isset($name[1])?$name[1]:'';
                
$userData = array(
                    
'oauth_provider' => 'twitter',
                    
'oauth_uid' => $userInfo->id,
                    
'username' => $userInfo->screen_name,
                    
'first_name' => $first_name,
                    
'last_name' => $last_name,
                    
'locale' => $userInfo->lang,
                    
'profile_url' => 'https://twitter.com/'.$userInfo->screen_name,
                    
'picture_url' => $userInfo->profile_image_url
                
);
                
                
//Insert or update user data
                
$userID $this->user->checkUser($userData);
                
                
//Store status and user profile info into session
                
$userData['accessToken'] = $accessToken;
                
$this->session->set_userdata('status','verified');
                
$this->session->set_userdata('userData',$userData);
                
                
//Get latest tweets
                
$data['tweets'] = $connection->get('statuses/user_timeline', array('screen_name' => $userInfo->screen_name'count' => 5));
            }else{
                
$data['error_msg'] = 'Some problem occurred, please try again later!';
            }
        }else{
            
//unset token and token secret from session
            
$this->session->unset_userdata('token');
            
$this->session->unset_userdata('token_secret');
            
            
//Fresh authentication
            
$connection = new TwitterOAuth($consumerKey$consumerSecret);
            
$requestToken $connection->getRequestToken($oauthCallback);
            
            
//Received token info from twitter
            
$this->session->set_userdata('token',$requestToken['oauth_token']);
            
$this->session->set_userdata('token_secret',$requestToken['oauth_token_secret']);
            
            
//Any value other than 200 is failure, so continue only if http code is 200
            
if($connection->http_code == '200'){
                
//Get twitter oauth url
                
$twitterUrl $connection->getAuthorizeURL($requestToken['oauth_token']);
                
$data['oauthURL'] = $twitterUrl;
            }else{
                
$data['oauthURL'] = base_url().'user_authentication';
                
$data['error_msg'] = 'Error connecting to twitter! try again later!';
            }
        }

        
$data['userData'] = $userData;
        
$this->load->view('user_authentication/index',$data);
    }

    public function 
logout() {
        
$this->session->unset_userdata('token');
        
$this->session->unset_userdata('token_secret');
        
$this->session->unset_userdata('status');
        
$this->session->unset_userdata('userData');
        
$this->session->sess_destroy();
        
redirect('/user_authentication');
    }
}

Note that: You’ll find the Consumer Key and Consumer Secret at your Twitter App. (Go to the Twitter Application Management page » Click on your app » Navigate to the Keys and Access Tokens tab » Copy the API Key and API Secret » Replace $consumerKey value with API key and $consumerSecret value with API secret)

Models (User.php)

User model contains only one function named checkUser(), it is used to insert or update the user data into the users table.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class 
User extends CI_Model{
    function 
__construct() {
        
$this->tableName 'users';
        
$this->primaryKey 'id';
    }
    public function 
checkUser($data = array()){
        
$this->db->select($this->primaryKey);
        
$this->db->from($this->tableName);
        
$this->db->where(array('oauth_provider'=>$data['oauth_provider'],'oauth_uid'=>$data['oauth_uid']));
        
$prevQuery $this->db->get();
        
$prevCheck $prevQuery->num_rows();
        
        if(
$prevCheck 0){
            
$prevResult $prevQuery->row_array();
            
$data['modified'] = date("Y-m-d H:i:s");
            
$update $this->db->update($this->tableName,$data,array('id'=>$prevResult['id']));
            
$userID $prevResult['id'];
        }else{
            
$data['created'] = date("Y-m-d H:i:s");
            
$data['modified'] = date("Y-m-d H:i:s");
            
$insert $this->db->insert($this->tableName,$data);
            
$userID $this->db->insert_id();
        }

        return 
$userID?$userID:FALSE;
    }
}

Views (user_authentication/index.php)

Initially, the Login with Twitter button is shown to the user. Once the user successfully logged in with their Twitter account, the profile details and some latest tweets will be shown.

<?php
if(!empty($error_msg)){
    echo 
'<p class="error">'.$error_msg.'</p>';    
}
?>

<?php
if(!empty($userData)){
    
$outputHTML '
        <div class="wrapper">
            <h1>Twitter Profile Details </h1>
            <div class="welcome_txt">Welcome <b>'
.$userData['first_name'].'</b></div>
            <div class="tw_box">
                <p class="image"><img src="'
.$userData['picture_url'].'" alt="" width="300" height="220"/></p>
                <p><b>Twitter Username : </b>'
.$userData['username'].'</p>
                <p><b>Name : </b>'
.$userData['first_name'].' '.$userData['last_name'].'</p>
                <p><b>Locale : </b>' 
$userData['locale'].'</p>
                <p><b>Twitter Profile Link : </b><a href="'
.$userData['profile_url'].'" target="_blank">'.$userData['profile_url'].'</a></p>
                <p><b>You are login with : </b>Twitter</p>
                <p><b>Logout from <a href="'
.base_url().'user_authentication/logout">Twitter</a></b></p>';
    
//Latest tweets
    
if(!empty($tweets)){
        
$outputHTML .= '<div class="tweetList"><strong>Latest Tweets : </strong>
            <ul>'
;
        foreach(
$tweets  as $tweet){
            
$outputHTML .= '<li>'.$tweet->text.' <br />-<i>'.$tweet->created_at.'</i></li>';
        }
        
$outputHTML .= '</ul></div>';
    }
    
$outputHTML .= '</div>
        </div>'
;
}else{
    
$outputHTML '<a href="'.$oauthURL.'"><img src="'.base_url().'assets/images/sign-in-with-twitter.png" alt=""/></a>';
}
?>
<?php 
echo $outputHTML?>

Libraries (twitter-oauth-php-codexworld/)

Insert the Twitter OAuth PHP folder in the application/libraries directory. You’ll find the Twitter OAuth PHP folder into the source code ZIP.

Config (autoload.php)

CodeIgniter Twitter Login using session and database, load the session and database libraries in the autoload.php file.

$autoload['libraries'] = array('session','database');

Conclusion

That’s all! Now your CodeIgniter application allows the user to login with their Twitter account and you can be able to store the user profile information to the MySQL database. Also, you’ve seen the user email is not inserted into the database because Twitter doesn’t return the user email. To get the user’s email your application needs to be whitelisted by Twitter. If you want to get and store the user email address, follow the steps provided in our previous Twitter login in PHP tutorial.

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

Recommended Tutorials For You

Leave a reply