Twitter Login with Codeigniter
Twitter is the most popular social media in the world. People are communicating each other in a short message, it’s called Tweets. Creating a twitter account you can tweet anybody who follows you on the Twitter account.
In this tutorial, I will show you Twitter Login in PHP Codeigniter Framework. If you want to set a twitter login system on your webpage, then you are most welcome in this tutorial. In this tutorial, I use Twitter OAuth library for twitter login. You need to first see the file/folder structure of Twitter Login, see it carefully and open these pages for done your Twitter login.
application/config
1) Routes.php
2) autoload.php
/application/libraries/TwitterOAuth
1) OAuth.php
2) TwitterOAuth.php
/application/controllers
1) TwitterLoginController.php
/application/models
1) TwitterLoginModel.php
Download Twitter OAuth library for twitter login. The millions of users are connected and active day with Twitter. Nowadays every web application will have this social network OAuth to improve user comfort level. So, every client want to login with twitter on the web application.
Before work with twitter login OAuth libray you need to generate some option, that are:
1) Consumer Key,
2) Consumer Secret,
3) OAuth Callback URL.
You need to create a twitter login app.
CREATE TWITTER LOGIN APP
Click on this link https://apps.twitter.com/app/new. Enter your app name, app description, website url and callback url, then Developer Agreement and press on the Create your Twitter Application button.
When you done to create your login app, then copy the Consumer Key and Consumer Secret code. Now follow the Twitter login Example codes:
Index.php
In the index.php page give your root link in the anchor tag of Twitter Login.
<div class="modal-body"> <p>Sign in to get access to exclusive content, social features and much more!</p> <div class="slider"> <div class="login-panel panel-1"> <a href="<?php echo base_url(); ?>twitter-login" class="twitter btn btn-custom btn-block">Twitter</a> <a href="#" class="email btn btn-default btn-block">Use your e-mail</a> </div> <div class="login-panel panel-2"> <form method="POST" action="#"> <div class="input-container"> <input type="text" id="login-email" name="login-email" placeholder="E-mail address" required="required" /> </div> <div class="input-container"> <input type="password" id="login-password" name="login-password" placeholder="Password" required="required" /> </div> <input type="button" name="login" class="btn btn-custom" onclick="signin()" value="Sign in!" style="margin-top: 10px;" /> <a href="#" class="cancel btn btn-default">Cancel</a> <a href="#" class="password-forgotten btn">Password forgotten?</a> </form> </div> </div> </div>
Routes.php
Generate a route for Twitter Login.
$autoload['libraries'] = array('session','database');
autoload.php
Open config folder and open the autoload page and set this code.
<?php $autoload['libraries'] = array('session','database');
Controller:
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class TwitterLoginController extends CI_Controller { public function __construct(){ parent::__construct(); $this->load->helper('url'); $this->load->helper('form'); // Load facebook library $this->load->library('facebook'); // Model $this->load->model('TwitterLoginModel'); // Session $this->load->library('session'); } // Twitter Login public function twitter_login(){ $base_url=base_url(); $userData = array(); //Include the twitter oauth php libraries include_once APPPATH."libraries/TwitterOAuth/twitteroauth.php"; //Twitter API Configuration $consumerKey = 'Enter Your Consumer Key '; $consumerSecret = 'Enter Your Consumer Secret'; $oauthCallback = base_url().'twitter-login'; //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($this->input->get('oauth_token') !== null && $sessToken == $this->input->get('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($this->input->get('oauth_verifier')); if($connection->http_code == '200'){ //Get user profile info $userInfo = $connection->get('account/verify_credentials', ['include_email' => "true"]); //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, 'email' =>$userInfo->email ); //Insert or update user data $userID = $this->LoginModel->twitterLogin($userData); if(!empty($userID)){ $this->session->set_userdata('user_id',$userID); redirect($base_url); } //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; redirect($data['oauthURL'] ); }else{ $data['oauthURL'] = base_url().'user_authentication'; $data['error_msg'] = 'Error connecting to twitter! try again later!'; } } } } ?>
Model:
<?php class TwitterLoginModel extends CI_Model{ function __construct() { parent::__construct(); $this->load->database(); } // Twitter Login public function twitterLogin($userData=array()){ $this->db->select('*'); $this->db->from('signin'); $this->db->where(array('oauth_provider'=>$userData['oauth_provider'],'oauth_uid'=>$userData['oauth_uid'])); $query = $this->db->get(); $check = $query->num_rows(); if($check > 0){ $result = $query->row_array(); //$data['last_update_date'] = date("Y-m-d"); $update = $this->db->update('signin',$userData,array('user_id'=>$result['user_id'])); $userID = $result['user_id']; }else{ $insert = $this->db->insert('signin',$userData); $userID = $this->db->insert_id(); } return $userID?$userID:false; } } ?>