Login with Twitter in CodeIgniter

Twitter is the most popular social networking service. Millions of people around the world are connected with Twitter. Integrate login with Twitter in the web application surely helps to make the login process smoother and easier for the user. The main advantage of integrating Twitter login is the user doesn’t need to register their account on your website. Instead, they can log into your website using their Twitter account. Since almost the web users have a Twitter account, Login with Twitter definitely helps you to increase the subscription of your website.

Twitter API allows to authenticate with Twitter account and retrieve the user’s profile information. You can easily integrate login with Twitter using PHP and Twitter OAuth library. If your web application uses CodeIgniter, the Twitter OAuth PHP library needs to be integrated into the CodeIgniter. In this tutorial, we will show you how to integrate Twitter login in CodeIgniter using Twitter OAuth PHP library and allow the user to sign in with Twitter in CodeIgniter application.

In our example code, we will go through the complete process to implement Twitter login in CodeIgniter and get the user account data using Twitter API. Also, the user’s profile data will be stored in the MySQL database.

Before you begin to implement Twitter login in CodeIgniter 3 using OAuth Library, create a Twitter app in Application Management panel and get the Consumer Key and Consumer Secret.

Create Twitter Application

The Consumer Key and Consumer Secret are required to use Twitter API and these credentials will be generated on the Twitter App. You need to create a Twitter App to get API Key and API Secret.

  • Go to the Twitter Application Management page and sign in to your Twitter account.
  • Enter the following details to create a new Twitter app.
    • 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.

After a successful Twitter App creation, click on Test OAuth to test the authentication. On OAuth test completion, you will be redirected to the OAuth Settings page. In the OAuth Settings page, you will see the Consumer Key (API Key) and Consumer Secret (API Secret).

twitter-oauth-login-app-consumer-api-key-secret-codexworld

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

Before getting started to Twitter login integration process, take a look at the files structure of Twitter login in CodeIgniter.

codeigniter_twitter_login/
├── application/
│   ├── config/
│   │   └── twitter.php
│   ├── controllers/
│   │   └── User_authentication.php
│   ├── libraries/
│   │   └── Twitteroauth.php
│   ├── models/
│   │   └── User.php
│   ├── third_party/
│   │   └── OAuth.php
│   └── views/
│       └── user_authentication/
│           └── index.php
└── assets/
    ├── css/
    │   └── style.php
    └── images/
        └── sign-in-with-twitter.png

Create Database Table

To store the user’s profile information a table needs to be created in the database. The following SQL creates a users table with some basic 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 DEFAULT 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;

Config (application/config/)

autoload.php
Specify the commonly used library (database and session) or helper (url) to load by default.

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

$autoload['helper'] = array('url');

twitter.php
Twitter API configuration variables are defined in this file. Specify the Consumer Key, Consumer Secret and Redirect URL according to your Twitter App credentials.

<?php
defined
('BASEPATH') OR exit('No direct script access allowed');

/*
|--------------------------------------------------------
| Twitter API Configuration
|--------------------------------------------------------
|
| To get API details you have to create a Twitter app
| at Twitter Application Management (https://apps.twitter.com/app/new)

| twitter_consumer_key        string   Your Twitter App Key.
| twitter_consumer_secret    string   Your Twitter App secret.
| twitter_redirect_url        string   URL to redirect back to after login. (do not include base URL)
|
*/
$config['twitter_consumer_key']     = 'Insert_Twitter_API_Key';
$config['twitter_consumer_secret']  = 'Insert_Twitter_API_Secret';
$config['twitter_redirect_url']     = '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 the twitter_consumer_key value with API key and twitter_consumer_secret value with API secret)

Third Party (application/third_party/)

OAuth.php
The OAuth library helps to authenticate with Twitter API. You don’t need to download it separately, this library is included in the source code.

Libraries (application/libraries/)

Twitteroauth.php
The Twitter OAuth library helps to integrate Twitter REST API in CodeIgniter 3.x application. Using this Twitter API library, you can easily add the login with Twitter functionality to the CodeIgniter application using PHP OAuth library. You don’t need to download it separately, this library is included in the source code.

Controllers (application/controllers/)

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

  • __construct() – The Twitter OAuth library and User model are loaded in this method.
  • index() – This function handles the authentication functionality with Twitter account.
    • If the user already logged in with Twitter, latest tweets will be fetched from their timeline.
      • If the user authenticated with Twitter, the following happens:
      • Twitter OAuth is initiated and get the access token from Twitter.
      • Get the user’s profile info from Twitter account.
      • Insert profile data in the database using checkUser() method of the User model.
      • Get the latest tweets from the user timeline.
      • Store access token and user profile info into session.
    • Otherwise, fresh authentication is initiated and Twitter authentication URL is generated.
  • logout() – This function removes the OAuth Token and user data from the SESSION. The logout() method is loaded to logout the user from their Twitter account.
<?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');
        
        
// Load twitter oauth library
        
$this->load->library('twitteroauth');
    }
    
    public function 
index(){
        
$userData = array();
        
        
// 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(!empty(
$sessStatus) && $sessStatus == 'verified'){
            
// Connect and get latest tweets
            
$twitteroauth $this->twitteroauth->authenticate($sessUserData['accessToken']['oauth_token'], $sessUserData['accessToken']['oauth_token_secret']);
            
            
$data['tweets'] = $twitteroauth->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
            
$twitteroauth $this->twitteroauth->authenticate($sessToken$sessTokenSecret);
            
$accessToken $twitteroauth->getAccessToken($_REQUEST['oauth_verifier']);
            
            if(
$twitteroauth->http_code == '200'){
                
// Get the user's twitter profile info
                
$userInfo $twitteroauth->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,
                    
'link' => 'https://twitter.com/'.$userInfo->screen_name,
                    
'picture' => $userInfo->profile_image_url
                
);
                
                
// Insert or update user data
                
$userID $this->user->checkUser($userData);
                
                
// Get latest tweets
                
$data['tweets'] = $twitteroauth->get('statuses/user_timeline', array('screen_name' => $userInfo->screen_name'count' => 5));
                
                
// Store the status and user profile info into session
                
$userData['accessToken'] = $accessToken;
                
$this->session->set_userdata('status''verified');
                
$this->session->set_userdata('userData'$userData);
            }else{
                
$data['error_msg'] = 'Authentication failed, please try again later!';
            }
        }elseif(isset(
$_REQUEST['denied'])){
            
$data['oauthURL'] = base_url().'user_authentication/';
            
$data['error_msg'] = 'Twitter authentication was denied!';
        }else{
            
// Unset token and token secret from the session
            
$this->session->unset_userdata('token');
            
$this->session->unset_userdata('token_secret');
            
            
// Fresh authentication
            
$twitteroauth $this->twitteroauth->authenticate($sessToken$sessTokenSecret);
            
$requestToken $twitteroauth->getRequestToken();
            
            
// If authentication is successful (http code is 200)
            
if($twitteroauth->http_code == '200'){
                
// Get token info from Twitter and store into the session
                
$this->session->set_userdata('token'$requestToken['oauth_token']);
                
$this->session->set_userdata('token_secret'$requestToken['oauth_token_secret']);
            
                
// Twitter authentication url
                
$twitterUrl $twitteroauth->getAuthorizeURL($requestToken['oauth_token']);
                
$data['oauthURL'] = $twitterUrl;
            }else{
                
// Internal authentication url
                
$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() {
        
// Remove session data
        
$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 to the login page
        
redirect('/user_authentication/');
    }
    
}

Models (application/models/)

User.php
The User model handles the database related operations (insert and update).

  • __construct() – Define the database table name and primary key.
  • checkUser() – Insert or update the user profile information based on the OAuth provider and ID. Returns the user ID on success, and FALSE on error.
<?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()){
        if(!empty(
$data['oauth_provider']) && !empty($data['oauth_uid'])){
            
$this->db->select($this->primaryKey);
            
$this->db->from($this->tableName);
            
            
$con = array(
                
'oauth_provider' => $data['oauth_provider'],
                
'oauth_uid' => $data['oauth_uid']
            );
            
$this->db->where($con);
            
            
$query $this->db->get();

            
$rowNum $query->num_rows();
            
            if(
$rowNum 0){
                
// Get existing user data
                
$result $query->row_array();
                
                
// Update user data
                
$data['modified'] = date("Y-m-d H:i:s");
                
$update $this->db->update($this->tableName$data, array('id' => $result['id']));
                
                
// Get user id
                
$userID $result['id'];
            }else{
                
// Insert user data
                
$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);
                
                
// Get user id
                
$userID $this->db->insert_id();
            }
            
            
// Return user id
            
return $userID?$userID:false;
        }else{
            return 
false;
        }
    }
}

Views (application/views/)

user_authentication/index.php
If the user already logged in with their Twitter account, the profile details and latest tweets are displayed. Otherwise, Sign in with Twitter button will be shown.

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

<?php if(!empty($userData)){ ?> <h1>Twitter Profile Details</h1> <div class="welcome-txt">Welcome <b><?php echo $userData['first_name']; ?></b></div> <div class="tw-box"> <!-- Display profile information --> <p class="img"><img src="<?php echo $userData['picture']; ?>" /></p> <p><b>Twitter Username : </b><?php echo $userData['username']; ?></p> <p><b>Name : </b><?php echo $userData['first_name'].' '.$userData['last_name']; ?></p> <p><b>Locale : </b><?php echo $userData['locale']; ?></p> <p> <b>Twitter Profile Link : </b> <a href="<?php echo $userData['link']; ?>" target="_blank"><?php echo $userData['link']; ?></a> </p> <p><b>You are logged in with : </b>Twitter</p> <p><b>Logout from <a href="<?php echo base_url('user_authentication/logout/'); ?>">Twitter</a></b></p> <!-- Display latest tweets --> <?php if(!empty($tweets)){ ?> <div class="tweetList"> <strong>Latest Tweets : </strong> <ul>                 <?php
                
foreach($tweets  as $tweet){
                    echo 
'<li>'.$tweet->text.' <br />-<i>'.$tweet->created_at.'</i></li>';
                }
                
?> </ul> </div> <?php ?> </div>
<?php }else{ ?> <!-- Display sign in button --> <a href="<?php echo $oauthURL?>"><img src="<?php echo base_url('assets/images/sign-in-with-twitter.png'); ?>" /></a> <?php ?>

Getting User Email from Twitter Account

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

  • Use this form to submit your request via Twitter Help Center. Be patient it will take some time to accept your request by Twitter.
  • Once your Twitter App is whitelisted, the Request email addresses from users checkbox will be available under the app permission on the Application Management page. Select this checkbox.
  • Under the 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.
  • Update Settings of your Twitter App.

Now, the email can be retrieved from the Twitter API after authentication.

In the index() method of User_Authentication controller, implement the following changes:

  • Add include_email parameter in get() method of TwitterOAuth class.
    $userInfo $twitteroauth->get('account/verify_credentials', ['include_email' => 'true']);
  • The email field will be available in $userInfo that returned by the Twitter API. Specify the email field ($userInfo->email) in the $userData to insert email address in the database.
    'email' => $userInfo->email

Login with Facebook in CodeIgniter

Conclusion

Here we have tried to make the Twitter login integration easier for CodeIgniter web application. Hope! The example code will help you to easily implement the Twitter login in CodeIgniter using the OAuth library. Our CodeIgniter Twitter Oauth library allows the user to sign in to the website using their Twitter account. Also, you can store the user’s Twitter account info in the MySQL database.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

3 Comments

  1. Sam Said...
    • CodexWorld Said...
  2. Farhad Said...

Leave a reply

keyboard_double_arrow_up