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.
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.
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).
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
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;
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)
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.
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.
User_authentication.php
The User_Authentication controller contains 3 functions, __construct(), index(), and logout().
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/');
}
}
User.php
The User model handles the database related operations (insert and update).
<?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;
}
}
}
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 } ?>
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.
Now, the email can be retrieved from the Twitter API after authentication.
In the index()
method of User_Authentication controller, implement the following changes:
include_email
parameter in get()
method of TwitterOAuth class.
$userInfo = $twitteroauth->get('account/verify_credentials', ['include_email' => 'true']);
$userInfo->email
) in the $userData
to insert email address in the database.
'email' => $userInfo->email
Login with Facebook in CodeIgniter
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
How to get email from twitter
To get the user’s Email Address, your application needs to be whitelisted by Twitter. Use this form to submit your request. Once whitelisted, the “Request email addresses from users” checkbox will be available under your app permission on Application Management.
hi,
how i can use google adwords lib in codeigniter 3?