Nowadays, the big form is not a preferred way to register the user on the website. It’s always recommended to make the registration process short and simple for web users. The quick signup process helps to increase the subscriber number on your website. Login with Social media account is the quickest way to add a short sign-up process on the website. Twitter is one of the most popular social network on the internet and millions of users are registered with Twitter. Sign in with Twitter is a quick and simple way to integrate the user login system on the web application.
Twitter API allows the website visitors to log in with their Twitter account without register on your website. Twitter OAuth PHP Library helps the web developer to integrate Twitter login system in a quick, easy, and powerful way. In this tutorial, we’ll show how to implement user Login with Twitter API and store the user profile information into the MySQL database using PHP. In the example Twitter login script, we will go through the complete process to create Twitter Apps and implement sign in with twitter using PHP. The Twitter OAuth PHP library will be used in our script that supports OAuth for Twitter’s REST API.
Before you begin to integrate the Twitter OAuth login, take a look at the files structure.
twitter_login_php/ ├── config.php ├── index.php ├── logout.php ├── User.class.php ├── twitter-oauth-php/ ├── images/ │ ├── twitter-login-btn.png └── css/ └── style.css
To access Twitter API you need to create a Twitter App and specify the Consumer key & Consumer secret at the time of calling the Twitter API. If you haven’t already created a Twitter App, follow the below steps to create and configure a Twitter App from the Application Management page.
Once Twitter App creation is completed, click on Test OAuth for testing OAuth. After testing you would be redirected to the OAuth Settings page. Switch to Keys and tokens tab, you’ll see the Consumer API keys are generated. Copy this API key (Consumer key) and API secret key (Consumer secret) for later use in the script.
To store the user profile information from the Twitter account, 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 NOT 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;
The twitter-oauth-php/ directory contains the Twitter OAuth library that helps to integrate Twitter API with PHP. You don’t need to download the Twitter PHP OAuth library separately, all the required files are included in our Twitter Login PHP source code.
The User class handles the database related operations (connect, insert, and update) using PHP and MySQL. It used to connect the database and insert/update Twitter account data in the users table.
<?php
/*
* User Class
* This class is used for database related (connect, insert, and update) operations
* @author CodexWorld.com
* @url http://www.codexworld.com
* @license http://www.codexworld.com/license
*/
class User {
private $dbHost = DB_HOST;
private $dbUsername = DB_USERNAME;
private $dbPassword = DB_PASSWORD;
private $dbName = DB_NAME;
private $userTbl = DB_USER_TBL;
function __construct(){
if(!isset($this->db)){
// Connect to the database
$conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
if($conn->connect_error){
die("Failed to connect with MySQL: " . $conn->connect_error);
}else{
$this->db = $conn;
}
}
}
function checkUser($data = array()){
if(!empty($data)){
// Check whether the user already exists in the database
$checkQuery = "SELECT * FROM ".$this->userTbl." WHERE oauth_provider = '".$data['oauth_provider']."' AND oauth_uid = '".$data['oauth_uid']."'";
$checkResult = $this->db->query($checkQuery);
// Add modified time to the data array
if(!array_key_exists('modified',$data)){
$data['modified'] = date("Y-m-d H:i:s");
}
if($checkResult->num_rows > 0){
// Prepare column and value format
$colvalSet = '';
$i = 0;
foreach($data as $key=>$val){
$pre = ($i > 0)?', ':'';
$colvalSet .= $pre.$key."='".$this->db->real_escape_string($val)."'";
$i++;
}
$whereSql = " WHERE oauth_provider = '".$data['oauth_provider']."' AND oauth_uid = '".$data['oauth_uid']."'";
// Update user data in the database
$query = "UPDATE ".$this->userTbl." SET ".$colvalSet.$whereSql;
$update = $this->db->query($query);
}else{
// Add created time to the data array
if(!array_key_exists('created',$data)){
$data['created'] = date("Y-m-d H:i:s");
}
// Prepare column and value format
$columns = $values = '';
$i = 0;
foreach($data as $key=>$val){
$pre = ($i > 0)?', ':'';
$columns .= $pre.$key;
$values .= $pre."'".$this->db->real_escape_string($val)."'";
$i++;
}
// Insert user data in the database
$query = "INSERT INTO ".$this->userTbl." (".$columns.") VALUES (".$values.")";
$insert = $this->db->query($query);
}
// Get user data from the database
$result = $this->db->query($checkQuery);
$userData = $result->fetch_assoc();
}
// Return user data
return !empty($userData)?$userData:false;
}
}
In the config.php
file, The constant variables are defined for database settings and Twitter API configuration.
Database Constants:
Twitter API Constants:
Call Twitter API:
<?php /* * Basic Site Settings and API Configuration */ // Database configuration define('DB_HOST', 'MySQL_Database_Host'); define('DB_USERNAME', 'MySQL_Database_Username'); define('DB_PASSWORD', 'MySQL_Database_Password'); define('DB_NAME', 'MySQL_Database_Name'); define('DB_USER_TBL', 'users'); // Twitter API configuration define('TW_CONSUMER_KEY', 'Insert_Twitter_API_Key'); define('TW_CONSUMER_SECRET', 'Insert_Twitter_API_Secret'); define('TW_REDIRECT_URL', 'Callback_URL'); // Start session if(!session_id()){ session_start(); } // Include Twitter client library require_once 'twitter-oauth-php/twitteroauth.php';
Note that: You’ll get the Consumer Key and Consumer Secret from Keys and tokens page of your Twitter App.
This file handles the Twitter API authentication process using PHP.
<?php
// Include configuration file
require_once 'config.php';
// Include User class
require_once 'User.class.php';
// If OAuth token not matched
if(isset($_REQUEST['oauth_token']) && $_SESSION['token'] !== $_REQUEST['oauth_token']){
//Remove token from session
unset($_SESSION['token']);
unset($_SESSION['token_secret']);
}
// If user already verified
if(isset($_SESSION['status']) && $_SESSION['status'] == 'verified' && !empty($_SESSION['request_vars'])){
//Retrive variables from session
$username = $_SESSION['request_vars']['screen_name'];
$twitterId = $_SESSION['request_vars']['user_id'];
$oauthToken = $_SESSION['request_vars']['oauth_token'];
$oauthTokenSecret = $_SESSION['request_vars']['oauth_token_secret'];
$name = $_SESSION['userData']['first_name'].' '.$_SESSION['userData']['last_name'];
$profilePicture = $_SESSION['userData']['picture'];
/*
* Prepare output to show to the user
*/
$twClient = new TwitterOAuth(TW_CONSUMER_KEY, TW_CONSUMER_SECRET, $oauthToken, $oauthTokenSecret);
//If user submits a tweet to post to twitter
if(isset($_POST["updateme"])){
$my_update = $twClient->post('statuses/update', array('status' => $_POST["updateme"]));
}
// Display username and logout link
$output = '<div class="welcome_txt">Welcome <strong>'.$username.'</strong> (Twitter ID : '.$twitterId.'). <a href="logout.php">Logout</a>!</div>';
// Display profile iamge and tweet form
$output .= '<div class="tweet_box">';
$output .= '<div class="left">';
$output .= '<img src="'.$profilePicture.'" width="120" height="110"/>';
$output .= '<p>'.$name.'</p>';
$output .= '</div>';
$output .= '<form method="post" action=""><table width="200" border="0" cellpadding="3">';
$output .= '<tr>';
$output .= '<td><textarea name="updateme" cols="60" rows="4"></textarea></td>';
$output .= '</tr>';
$output .= '<tr>';
$output .= '<td><input type="submit" value="Tweet" /></td>';
$output .= '</tr></table></form>';
$output .= '</div>';
// Get latest tweets
$myTweets = $twClient->get('statuses/user_timeline', array('screen_name' => $username, 'count' => 5));
// Display the latest tweets
$output .= '<div class="tweet_list"><strong>Latest Tweets : </strong>';
$output .= '<ul>';
foreach($myTweets as $tweet){
$output .= '<li>'.$tweet->text.' <br />-<i>'.$tweet->created_at.'</i></li>';
}
$output .= '</ul></div>';
}elseif(isset($_REQUEST['oauth_token']) && $_SESSION['token'] == $_REQUEST['oauth_token']){
// Call Twitter API
$twClient = new TwitterOAuth(TW_CONSUMER_KEY, TW_CONSUMER_SECRET, $_SESSION['token'] , $_SESSION['token_secret']);
// Get OAuth token
$access_token = $twClient->getAccessToken($_REQUEST['oauth_verifier']);
// If returns success
if($twClient->http_code == '200'){
// Storing access token data into session
$_SESSION['status'] = 'verified';
$_SESSION['request_vars'] = $access_token;
// Get user profile data from twitter
$userInfo = $twClient->get('account/verify_credentials');
// Initialize User class
$user = new User();
// Getting user's profile data
$name = explode(" ",$userInfo->name);
$fname = isset($name[0])?$name[0]:'';
$lname = isset($name[1])?$name[1]:'';
$profileLink = 'https://twitter.com/'.$userInfo->screen_name;
$twUserData = array(
'oauth_uid' => $userInfo->id,
'first_name' => $fname,
'last_name' => $lname,
'locale' => $userInfo->lang,
'picture' => $userInfo->profile_image_url,
'link' => $profileLink,
'username' => $userInfo->screen_name
);
// Insert or update user data to the database
$twUserData['oauth_provider'] = 'twitter';
$userData = $user->checkUser($twUserData);
// Storing user data into session
$_SESSION['userData'] = $userData;
// Remove oauth token and secret from session
unset($_SESSION['token']);
unset($_SESSION['token_secret']);
// Redirect the user back to the same page
header('Location: ./');
}else{
$output = '<h3 style="color:red">Some problem occurred, please try again.</h3>';
}
}else{
// Fresh authentication
$twClient = new TwitterOAuth(TW_CONSUMER_KEY, TW_CONSUMER_SECRET);
$request_token = $twClient->getRequestToken(TW_REDIRECT_URL);
// Received token info from twitter
$_SESSION['token'] = $request_token['oauth_token'];
$_SESSION['token_secret']= $request_token['oauth_token_secret'];
// If authentication returns success
if($twClient->http_code == '200'){
// Get twitter oauth url
$authUrl = $twClient->getAuthorizeURL($request_token['oauth_token']);
// Display twitter login button
$output = '<a href="'.filter_var($authUrl, FILTER_SANITIZE_URL).'"><img src="images/twitter-login-btn.png" /></a>';
}else{
$output = '<h3 style="color:red">Error connecting to Twitter! Try again later!</h3>';
}
}
?>
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Login with Twitter using PHP by CodexWorld</title>
<meta charset="utf-8">
</head>
<body>
<div class="container">
<!-- Display login button / Twitter profile information -->
<?php echo $output; ?>
</div>
</body>
</html>
The logout.php
file is used to log the user out from the Twitter account.
<?php // Start session if(!session_id()){ session_start(); } // Remove user data from session unset($_SESSION['userData']); // Destroy all session data session_destroy(); // Redirect to the homepage header("Location:index.php"); ?>
Generally, Twitter doesn’t return the user’s email after authentication. To get the user’s Email Address with Twitter API, your application needs to be whitelisted by Twitter. To get and store the user email address, follow the below steps.
index.php
file, add include_email parameter in get()
function. To do that, replace the $userInfo
variable value with the following line of code.
$userInfo = $twClient->get('account/verify_credentials', ['include_email' => 'true']);
$userInfo->email
. Add the user’s email ($userInfo->email) in $twUserData
array.
$twUserData = array( 'oauth_uid' => $userInfo->id, 'first_name' => $fname, 'last_name' => $lname, 'email' => $userInfo->email, 'locale' => $userInfo->lang, 'picture' => $userInfo->profile_image_url, 'link' => $profileLink, 'username' => $userInfo->screen_name );
The email field already added to the users
table, so, you don’t need to alter the database table structure.
Login with Twitter in CodeIgniter
We’ve tried to make the Twitter login integration process simple as much as possible. Using our script, you can easily add Twitter login system to your website using PHP and MySQL. All the required files are included in our source code including Twitter OAuth Library. You only need to configure some minimal settings to integrate Sign in with Twitter using OAuth client and PHP.
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
How to get “statuses_count” (total amount of Tweets)?
Hi, Thanks for this post. It is very useful. Please create an article for integrating with CodeIgniter framework also. Thank you
We have already published the Twitter Login for CodeIgniter, see the tutorial from here – https://www.codexworld.com/twitter-login-codeigniter/
hi CodexWorld
tnx for amazing script .
plz Can you tell me how to save user Access Token and user Access Token Secret to db
where are the files of library OAuth.php and twitterOAuth.php?
The source code contains all the required files including OAuth.php and twitterOAuth.php, download the source code.
Thanks @CodexWorld for reply.
One more thiing..
I want to save twitter account email id in database. so what code I have to change.
Please follow the instruction given in Getting User Email from Twitter Account section of the tutorial.
Its showing A session had already been started in twConfig.php on line 2
when i run it and value does not inserted into database.
In
twConfig.php
file, replacesession_start();
with the following code.if(!session_id()){
session_start();
}
Any chance we can also add gender in this
Hi,
How to implement it on my index.html page ?
Regards,
This script needs PHP file for executing.
Thank you so much for help
You guys really rocks..
but please provide link for this with codeigniter
@Parul We’ve published the Twitter Login tutorial for CodeIgniter. Check it out from here – http://www.codexworld.com/twitter-login-codeigniter/
wow great work
i want to ask you can i make the tweeting page
a separate page and tweet for multi accounts ?
hii. login with twitter done successfully. but i am unable to add tweet from there. Please help me
How to auto retweets and auto favorites all the tweets I tweet out from my main account
Good work!!!
Anybody? What do I need to change on your code to make it save the user emails into mysql?
@Jo Follow the following steps to insert the user email to the database.
1. Add new field (email) in users table.
2. Open the
includes/functions.php
file and add $email parameter to thecheckUser()
function. Modify the INSERT and UPDATE query with email column name and value.3. Open the
process.php
file and pass the Twitter account email tocheckUser()
function once user logged in.I’ve got that email permission and did everything on twitter as said.
What do I need to change on your code to make it save the user emails into mysql?
but I want to get the email address also. Is it possible?
@Jayendra To get the user’s Email Address, your application need 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.
Nice Work bro….
How can I download the source code ,when I click on source code no download link appears.
@Gaurav You can download the source code from here – http://www.codexworld.com/downloads/login-with-twitter-using-php
Hello,
Thank You for providing really very good tutorials.
Can you provide tutorial on instagram login with php?
@CodexWorld Thank you very much .You are doing excellent work.Thanks a Lot!!!!!!
@CodexWorld .Great Tutorial But can we get user email from “userinfo” object.or it anyway can we able to get email of user while user login with twitter.?.please help me as soon as possible
@Parag To get the user’s Email Address, your application need 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.
Great tutorial !!! Very easy and simple and Effective one.
Great tutorial!
Any news regarding the tutorial to merge FB,G+ and Twitter at the same time?
Looking forward, I belive it would help a lot of people.
Nice it is working 100%
note * OAUTH_CALLBACK in config file must same im the app setting .
Hi,
how i can integrate it in codeigniter framework, i already subscribe newsletter
thanks
@Duwi We’ll try to publish the same for CodeIgniter framework soon and you will be notified.
how i can integrate it in codeigniter framework
@Dharmendra We’ll publish Login with Twitter in CodeIgniter tutorial soon. Please subscribe our newsletter for getting the notification.
i like to add re tweet and favorite button. how can i do this???
done, i have subscribe it ! hope the tutorial will launch as soon as you can, hope in codeignter ! Thanks
regards Freddy Sidauruk
hi, i have a disscussion, if you don’t mind can i write in here !
i have projects that user can register by using facebook, twitter ?
and the users can input products,
i have been searching in your blog and found it usefull but i have problem how can i make both login working like charm ?
@Freddy
We’ve already published the Facebook, Google, Twitter, and LinkedIn login using PHP tutorial. Also, We have received many requests for a tutorial on making all social login together. We’ll merge all the social login (Facebook, Google, Twitter, and LinkedIn) and publish soon. Please subscribe our newsletter for receiving the tutorial in your mail box.