How to get profile data in Twitter using Codeigniter

Twitter is one of the popular and most used social networks. When the get data in twitter into your web application, The main facility of Twitter data 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.

Click here to download and Click here to demo

Step 1: libraries/twitter-oauth-php/twitteroauth.php

public function __construct()
{
	parent::__construct();
	include_once APPPATH."libraries/twitter-oauth-php/twitteroauth.php";
}

Step 2: Twitter button on click and redirect controller function like (index())

public function index(){
   $userData = array();

   $consumerKey = ''; //Insert_Twitter_API_Key
   $consumerSecret = ''; //Insert_Twitter_API_Secret
   $oauthCallback = base_url().'login/';

   $sessToken = $this->session->userdata('token');
   $sessTokenSecret = $this->session->userdata('token_secret');

   $sessStatus = $this->session->userdata('status');
   $sessUserData = $this->session->userdata('userData');

   if(isset($sessStatus) && $sessStatus == 'verified')
   {
	   $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));
	   $userData = $sessUserData;
	   echo "<pre>";
	   print_r($userData);
	   die;
   }
   elseif(isset($_REQUEST['oauth_token']) && $sessToken == $_REQUEST['oauth_token'])
   {
	   $connection = new TwitterOAuth($consumerKey, $consumerSecret, $sessToken, $sessTokenSecret);
	   $accessToken = $connection->getAccessToken($_REQUEST['oauth_verifier']);

		   $userInfo = $connection->get('account/verify_credentials');

		   $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
		   );

		   $userData['accessToken'] = $accessToken;
		   $this->session->set_userdata('status','verified');
		   $this->session->set_userdata('userData',$userData);
		   echo "<pre>";
		   print_r($userData);
		   die;
   }
   else
   {
	   $this->session->unset_userdata('token');
	   $this->session->unset_userdata('token_secret');

	   $connection = new TwitterOAuth($consumerKey, $consumerSecret);
	   $requestToken = $connection->getRequestToken($oauthCallback);

	   $this->session->set_userdata('token',$requestToken['oauth_token']);
	   $this->session->set_userdata('token_secret',$requestToken['oauth_token_secret']);

	   $twitterUrl = $connection->getAuthorizeURL($requestToken['oauth_token']);
	   $data['oauthURL'] = $twitterUrl;
   }

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

Step 3: Session destroy Code

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('/login');
}

Output

Array
(
    [oauth_provider] => twitter
    [oauth_uid] => 11235064246243
    [username] => HARDIKDAYANI
    [first_name] => HARDIK
    [last_name] => DAYANIHA
    [locale] => en
    [profile_url] => https://twitter.com/HDDAYANI
    [picture_url] => http://abs.twimg.com/profile_normal.png
    [accessToken] => Array
        (
            [oauth_token] => 1350642463-kvR0j
            [oauth_token_secret] => CbMbOzQ
            [user_id] => 11235064246243
            [screen_name] => HARDIKDAYANI
            [x_auth_expires] => 0
        )

)

Complete page source here.

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

class Login extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
		include_once APPPATH."libraries/twitter-oauth-php/twitteroauth.php";
	}
	
	public function index(){
		$userData = array();
		
		$consumerKey = 'Jpzd4c1SJkggmZ4RC4uKAR8vW'; //Insert_Twitter_API_Key
		$consumerSecret = 'N27jQMUnce68eZXyWncawcb05CN0GtWraePY0MnMzxcQjLLhC0'; //Insert_Twitter_API_Secret
		$oauthCallback = base_url().'login/';
		
		$sessToken = $this->session->userdata('token');
		$sessTokenSecret = $this->session->userdata('token_secret');
		
		$sessStatus = $this->session->userdata('status');
		$sessUserData = $this->session->userdata('userData');
		
		if(isset($sessStatus) && $sessStatus == 'verified')
		{
			$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));
			$userData = $sessUserData;
			echo "<pre>";
			print_r($userData);
			die;
		}
		elseif(isset($_REQUEST['oauth_token']) && $sessToken == $_REQUEST['oauth_token'])
		{
			$connection = new TwitterOAuth($consumerKey, $consumerSecret, $sessToken, $sessTokenSecret);
			$accessToken = $connection->getAccessToken($_REQUEST['oauth_verifier']);
		
				$userInfo = $connection->get('account/verify_credentials');
		
				$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
				);
				
				$userData['accessToken'] = $accessToken;
				$this->session->set_userdata('status','verified');
				$this->session->set_userdata('userData',$userData);
				echo "<pre>";
				print_r($userData);
				die;
		}
		else
		{
			$this->session->unset_userdata('token');
			$this->session->unset_userdata('token_secret');
			
			$connection = new TwitterOAuth($consumerKey, $consumerSecret);
			$requestToken = $connection->getRequestToken($oauthCallback);
			
			$this->session->set_userdata('token',$requestToken['oauth_token']);
			$this->session->set_userdata('token_secret',$requestToken['oauth_token_secret']);
			
			$twitterUrl = $connection->getAuthorizeURL($requestToken['oauth_token']);
			$data['oauthURL'] = $twitterUrl;
        }

		$data['userData'] = $userData;
		$this->load->view('login',$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('/login');
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *