Sign in with Twitter OAuth API Using PHP

Posted by & filed under CSS, HTML5, JQUERY, MYSQL, PHP.

In this tutorial we are going to see how to integrate Twitter Oauth Authentication to webapplication using PHP.

Now every webapplication will have this social networks Oauth  Authentication (Facebook, Google and Twitter ) to improve comfortness of their users. So users don’t need to create separate login credentials to each application they visit. They will use any one of the social network (Google, Facebook or Twitter ) login credentials to register and login to the webapplication they visit.

 

Please refer my previous tutorial on

1. Simple User login, Registration and Forget Password using PHP5, jQuery, MySQLi and Bootstrap

2. Login with Google OAuth 2 Using PHP and MySQL

3. Facebook OAuth 2 Login Using PHP

 

 

Integrate Twitter Oauth Login Using PHP

Integrate Twitter Oauth Login Using PHP

Step 1:

Before continuing our coding part we need to create Twitter Application using twitter app dashboard. To create Twitter App please going to following URL.

https://apps.twitter.com/

Now login with your twitter account login credentials. Once you logged in, you will get following screen.

Steps to Create Twitter Application

Steps to Create Twitter Application

Now click on Create New App button to continue.

Step 2:

Fill the following filelds to create Twitter Applications like in the images below.

Twitter Applications Creation Steps

Twitter Applications Creation Steps

 

Twitter Applications Creation Steps

Twitter Applications Creation Steps

Please select Read and Write Permission in the Permission tab and click on update settings button to update.

Step 3:

Create sample Databse with table using following SQL queries.

--
-- Database: `user_login`
--
CREATE DATABASE IF NOT EXISTS `user_login` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `user_login`;

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE IF NOT EXISTS `users` (
  `user_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `email` varchar(60) NOT NULL,
  `password` varchar(60) NOT NULL,
  `social_id` varchar(100) NOT NULL,
  `picture` varchar(250) NOT NULL,
  `created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`user_id`),
  UNIQUE KEY `email` (`email`),
  KEY `login` (`password`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;

 

Now create config.php file and define application related constants. Once you created Twitter application successfully, you will get Consumer Key (API Key) and Consumer Secret (API Secret). Please note it down.

<?php
/**
@author muni
@copyright http:www.smarttutorials.net
 */

require_once 'messages.php';

//site specific configuration declartion
define( 'BASE_PATH', 'http://demo.smarttutorials.net/twitter/');
define( 'DB_HOST', 'localhost' );
define( 'DB_USERNAME', 'root');
define( 'DB_PASSWORD', '');
define( 'DB_NAME', 'user_login');

//Twitter login
define('TWITTER_CONSUMER_KEY', 'YOUR_CONSUMER_KEY');
define('TWITTER_CONSUMER_SECRET', 'YOUR_CONSUMER_SECRET');
define('TWITTER_OAUTH_CALLBACK', 'http://demo.smarttutorials.net/twitter/index.php');

function __autoload($class)
{
	$parts = explode('_', $class);
	$path = implode(DIRECTORY_SEPARATOR,$parts);
	require_once $path . '.php';
}

Please download below source file, and just replace TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET and TWITTER_OAUTH_CALLBACK with your Consumer Key (API Key), Consumer Secret (API Secret) and callback URL. Then upload this to your server. Now it will work successfully.

Note : Callback URL in your config.php must match with Callback URL in the Twitter App settings page. Please select the checkbox option of Allow this application to be used to Signin with Twitter.

 

 

Step 4:

Create index.php and include twitteroauth.php and config.php at the top of the file.

require_once 'config.php'; 
require_once('twitteroauth/twitteroauth.php');

Here index.php full script,

<?php 
ob_start();
session_start();
require_once 'config.php'; 

//initalize user class
$user_obj = new Cl_User();
/*** Twitter****/
require_once('twitteroauth/twitteroauth.php');

if (TWITTER_CONSUMER_KEY === '' || TWITTER_CONSUMER_SECRET === '' || TWITTER_CONSUMER_KEY === 'TWITTER_CONSUMER_KEY_HERE' || TWITTER_CONSUMER_SECRET === 'CONSUMER_SECRET_HERE') {
	echo 'You need a consumer key and secret to test the sample code. Get one from <a href="https://dev.twitter.com/apps">dev.twitter.com/apps</a>';
	exit;
}

if(!isset( $_SESSION['oauth_token'] )){
	$connection = new TwitterOAuth(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET);
	$request_token = $connection->getRequestToken(TWITTER_OAUTH_CALLBACK);
	$_SESSION['oauth_token'] = $token = $request_token['oauth_token'];
	$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
	switch ($connection->http_code) {
		case 200:
			$url = $connection->getAuthorizeURL($token);
			break;
		default:
			$error = 'Could not connect to Twitter. Refresh the page or try again later.';
	}
}else{
	$connection = new TwitterOAuth(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
	$access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
	$_SESSION['access_token'] = $access_token;
	$content = $connection->get('account/verify_credentials');
	$data = array();
	if( !empty( $content->id )){
		$data['id'] = $content->id;
		$data['name'] = $content->name;
		$data['screen_name'] = $content->screen_name;
		$data['picture'] = $content->profile_image_url;
		try {
			$user_obj->twitter_login($data);
		}catch (Exception $e) {
			$error = $e->getMessage();
		}

	}else{
		session_unset();
		session_destroy();
		header('Location: index.php');
	}
}
/*** Twitter****/
?>
<?php 
	if( !empty( $_POST )){
		try {

			$data = $user_obj->login( $_POST );
			if(isset($_SESSION['logged_in']) && $_SESSION['logged_in']){
				header('Location: home.php');
			}
		} catch (Exception $e) {
			$error = $e->getMessage();
		}
	}
	//print_r($_SESSION);
	if(isset($_SESSION['logged_in']) && $_SESSION['logged_in']){
		header('Location: home.php');
	}
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Smart Login Page</title>
	<link href='http://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'>
    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/font-awesome.min.css" rel="stylesheet">
    <link href="css/login.css" rel="stylesheet">
    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="js/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>
  </head>
  <body>
	<div class="container">
		<?php require_once 'templates/ads.php';?>
		<div class="login-form">
			<?php require_once 'templates/message.php';?>
			<h1 class="text-center">Smart Tutorials</h1>
			<div class="form-header">
				<i class="fa fa-user"></i>
			</div>
			<form id="login-form" method="post" class="form-signin" role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>">
				<input name="email" id="email" type="email" class="form-control" placeholder="Email address" autofocus> 
				<input name="password" id="password" type="password" class="form-control" placeholder="Password"> 
				<button class="btn btn-block bt-login" type="submit">Sign in</button>

				<h4 class="text-center login-txt-center">Alternatively, you can log in using:</h4>

				<a class="btn btn-default twitter" href="<?php echo $url;?>"> <i class="fa fa-twitter modal-icons"></i> Sign In with Twitter </a>
			</form>
			<div class="form-footer">
				<div class="row">
					<div class="col-xs-6 col-sm-6 col-md-6">
						<i class="fa fa-lock"></i>
						<a href="forget_password.php"> Forgot password? </a>

					</div>

					<div class="col-xs-6 col-sm-6 col-md-6">
						<i class="fa fa-check"></i>
						<a href="register.php"> Sign Up </a>
					</div>
				</div>
			</div>
		</div>
	</div>
	<!-- /container -->
    <script src="js/jquery.validate.min.js"></script>
    <script src="js/login.js"></script>
  </body>
</html>
<?php ob_end_flush(); ?>

Here is User class twitter_login() method which saves twitter OAuth response in database and signin the user to our webapplication.

/**
	 * This will handle twitter login
	 * @param array $data
	 * @throws Exception
	 * @return boolean
	 */

	public function twitter_login( array $data )
	{
		if( !empty( $data ) ){
			// Trim all the incoming data:
			$trimmed_data = array_map('trim', $data);
		}

		// escape variables for security
		$social_id = mysqli_real_escape_string( $this->_con, $trimmed_data['id'] );
		$name = mysqli_real_escape_string( $this->_con, $trimmed_data['name'] );
		$screen_name = mysqli_real_escape_string( $this->_con, $trimmed_data['screen_name'] );
		$picture = mysqli_real_escape_string( $this->_con, $trimmed_data['picture'] );

		$query = "SELECT user_id, name, email, created FROM user where social_id = '$social_id' ";
		$result = mysqli_query($this->_con, $query);
		$data = mysqli_fetch_assoc($result);
		$count = mysqli_num_rows($result);
		if( $count == 1){
			$_SESSION = $data;
			$_SESSION['logged_in'] = true;
			return true;
		}else{

			$query = "INSERT INTO user (user_id, name, social_id, picture, created) VALUES (NULL, '$name', '$social_id', '$picture', CURRENT_TIMESTAMP)";
			if(mysqli_query($this->_con, $query));
			$query = "SELECT user_id, name, email, created FROM user where social_id = '$social_id' ";
			$result = mysqli_query($this->_con, $query);
			$data = mysqli_fetch_assoc($result);
			$count = mysqli_num_rows($result);
			if( $count == 1){
				$_SESSION = $data;
				$_SESSION['logged_in'] = true;
				return true;
			}else{
				throw new Exception( LOGIN_FAIL );
			}
		}
	}

 .

Download Premium Only Scripts & 80+ Demo scripts Instantly at just 1.95 USD per month + 10% discount to all Exclusive Scripts

If you want any of my script need to be customized according to your business requirement,

Please feel free to contact me [at] muni2explore[at]gmail.com

Note: But it will be charged based on your customization requirement

Get Updates, Scripts & Other Useful Resources to your Email

Join 10,000+ Happy Subscribers on feedburner. Click to Subscribe (We don't send spam)
Every Email Subsciber could have access to download 100+ demo scripts & all future scripts.

%d bloggers like this:

Get Instant Script Download Access!