Twitter Login using TwitterOAuth and PHP

Twitter Login Using PHP

[button-blue url=”http://demos.eggslab.net/twitter-login-using-php/” target=”_blank” position=””]LIVE DEMO[/button-blue][button-green url=”http://demos.eggslab.net/downloads/13″ target=”_blank” position=””]DOWNLOAD[/button-green]

I got several requests for Social Login using PHP, so here is my first tutorial on this series. In this tutorial I am going to show you that how you can simply integrate “Twitter Login using PHP” in your website. It’s very easy to integrate in your site. If you follow my tutorial step by step you can definitely be able to integrate Twitter Login in your website or project.

So first and the foremost step is to register your app in Twitter Application Management page. You can go from here. You should have email verified twitter account in order to create an app. After login you will see “Create New App” at right side of page.

Create New App

When you click on “Create New App” you will redirect to a form where they will ask you some detail about your App. Be easy and give them right detail.

Create Twitter App

Give them your application name, description about your application and your website URL. In Callback URL give them a path of page twitter_back.php (Code is given below for this page). Then you will see a Developer Agreement at bottom of page. Read it carefully and check “Yes, I agree” and hit “Create your Twitter Application”.

Twitter's Developer Agreement

Congrats your application is ready to use. Now you will redirected to your application page there you will see “Permission” tab click on it. In this page you are being asked that “What type of access does your application need?” Select “Read and Write”. And hit “Update Setting”.

Application's Permissions

And go to “Keys and Access Tokens” tab. Here you will find some useful information about App. There are two very important assets of your application one is called Consumer Key also known as API Key and the other is Consumer Secret also known as API Secret. So save it secretly and don’t share it with others.

Keys and Access Token

Don’t worry these are just demo keys 😛 I have change them after taking snapshot 😉 so no one can misuse of my app. Ok let’s move toward coding.

[You may also like: PHP Login Script with Session]

There are many PHP libraries are available for use with the Twitter OAuth REST API. You can check out twitter recommend libraries from here.

I am using TwitterOAuth by @abraham.

Grab your latest copy of TwitterOAuth from here . I am using version 0.6.1. It’s depend on you whether you use latest version or use my given code.

First let’s start a session on the start of page twitter_login.php

session_start();

Then load library files

require "lib/autoload.php";

use Abraham\TwitterOAuth\TwitterOAuth;

Now create a config.php file and define Consumer Key and Consumer Secret that you have got during the creation of your application at Twitter Application Manager. If you don’t know about it then don’t worry go back to apps.twitter.com and select your app and then go to Key and Access Tokens tab and copy your Consumer Key and Consumer Secret. Include this file in your page twitter_login.php.

define("Consumer_Key", "YOUR_CONSUMER_KEY");

define("Consumer_Secret", " YOUR_CONSUMER_SECRET");

Now it’s time to connect our server to our twitter application and requesting authentication tokens from twitter. The parameter oauth_callback is the URL where our rest of secret is stored. Please change this URL before using my given script.

$connection = new TwitterOAuth(Consumer_Key, Consumer_Secret);

$request_token = $connection->oauth("oauth/request_token", array("oauth_callback" => "http://localhost/twitter-login-using-php/twitter-back.php"));

After that we store that oauth_token and oauth_token_secret in session variable so that we can use them on next page.

$_SESSION['oauth_token'] = $request_token['oauth_token'];

$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];

Now let’s redirect the page to next page where our rest of script is store.

$url = $connection->url("oauth/authorize", array("oauth_token" => $request_token['oauth_token']));

header('Location: ' . $url);

Now you will be prompted to authorize application to use your account. Click on authorize button

Authorize Application

After successful authorization it will redirect you to callback_url that we have define in the above variable request_token’s parameter. It will provide you two parameter in callback_url oauth_token and oauth_verifier. We will use these two parameter to get access token from Twitter by making a request to Twitter’s Server. So let’s create a twitter_back.php file and complete our login process.

[You may also like: PHP Login Script with Session]

Again here in this file we start session at the top of file, include config.php file and load TwitterOAuth library files.

session_start();

include("config.php");

require "lib/autoload.php";

use Abraham\TwitterOAuth\TwitterOAuth;

Then we will connect our server to our Twitter’s Application, but this time we will also use oauth_token and oauth_token_secret parameters while connecting to twitter’s server. Remember we store these two parameters in session variable and I said we will use these two later as used finasteride. So now it’s time to use these parameters. And request Twitter to give us user’s access_token and access_secret_token to use his account.

$connection = new TwitterOAuth(Consumer_Key, Consumer_Secret, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);

$access_token = $connection->oauth('oauth/access_token', array('oauth_verifier' => $_REQUEST['oauth_verifier'], 'oauth_token'=> $_GET['oauth_token']));

In connection variable we provide ‘oauth_token’ and ‘oauth_token_secret’ from session variables whereas in access_token request we provide oauth_verifier from the URL by getting it through GET method.

$accessToken=$access_token['oauth_token'];

$secretToken=$access_token['oauth_token_secret'];

So here we have user’s access token and secret token. Now we can access to user’s profile. Now we are going to make a new connection to twitter server to get user’s profile data, but this time we provide access_token and access_token_secret parameters in connection variable.

$connection = new TwitterOAuth(Consumer_Key, Consumer_Secret, $access_token['oauth_token'], $access_token['oauth_token_secret']);

All done! Now we make a get request to twitter’s server to access user’s profile data. Here you go:

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

Now what’s next? Nothing difficult 😀 now we just need to store these data in our database to let user to sign in again via this simple application.

Following is the database structure

CREATE TABLE `user` (

`uid` int(10) NOT NULL AUTO_INCREMENT,

`oauth_id` int(10) NOT NULL,

`oauth_token` varchar(50) NOT NULL,

`oauth_secret_token` varchar(45) NOT NULL,

`oauth_provider` varchar(10) NOT NULL,

`username` varchar(25) NOT NULL,

PRIMARY KEY (`uid`)

);

Now let’s write PHP code to store these data into database. First we check if there is any user available with same twitter’s ID. If yes, we will UPDATE his access token and access secret token. If no, then we will INSERT it into database. Before doing it, make sure that you have included your database configuration in this file. Open your config.php file and include this code too:

define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);

Now get back to your twitter_back.php file and write the following code.

$sql="SELECT uid FROM user WHERE oauth_provider = 'twitter' and oauth_id = $user_id";
$result=mysqli_query($db,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);

if(mysqli_num_rows($result) == 1)
{
$query = mysqli_query($db, "UPDATE user SET oauth_token = '$oauth_token', oauth_secret_token = '$oauth_token_secret' WHERE oauth_provider = 'twitter' and oauth_id = $user_id");
if($query)
{
$_SESSION['name'] = $user_name;
header('Location: index.php');
}else
{
echo mysqli_error($db);
}

}
else
{
$query = mysqli_query($db, "INSERT INTO twitter (oauth_id, oauth_provider, oauth_token, oauth_secret_token, oauth_name) VALUES ($user_id, 'twitter', '$oauth_token', '$oauth_token_secret', '$user_name')");
if($query)
{
$_SESSION['name'] = $user_name;
header('Location: index.php');
}else
{
echo mysqli_error($db);
}

Where $user_name and $user_id are the variables that stores user twitter’s ID and name.

$user_id = $user_info->id;
$user_name = $user_info->name;

These are two only two properties I have use here, if you want to get more account’s detail then echo $user_info variable. You will get everything about user.

echo "<pre>";
print_r($user_info);
echo "</pre>";

That’s all. I am done with everything. If you need anything more you can comment below and I will try my best to help you out.

[button-blue url=”http://demos.eggslab.net/twitter-login-using-php/” target=”_blank” position=””]LIVE DEMO[/button-blue][button-green url=”http://demos.eggslab.net/downloads/13″ target=”_blank” position=””]DOWNLOAD[/button-green]


4 responses to “Twitter Login using TwitterOAuth and PHP”

  1. satish Avatar
    satish

    hello sir tell me how to make our website user they post some status file whatever so how to fix user id = status id

  2. Abdullah Majid Avatar

    Hey Satish!
    Sorry brother I am not getting you. What you really wants from me? Do you want to upload statuses on twitter profile using your website or anything else? Please clear your requirement.

  3. Samuel Avatar
    Samuel

    Hi Abdullah thanks for share. I try in my server but give back an error. twitter_back.php

    ” Unknown column ‘oauth_name’ in ‘field list ‘”

Leave a Reply

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