Login with Twitter using PHP

By

September 1, 2013PHPNo comments

Nowadays websites are implementing federated logins like twitter and Facebook where in you can sign-in using your social credentials instead of emails.

We are going to see how to implement Login with Twitter using PHP Twitter api library.

The entire process is based on the principle of Oauth.It is a protocol for secure authorization in a simple and standard method from web and mobile applications.

OAuth Guide

Instead of getting username and email from user, they will be redirected to twitter.com and authenticated with their twitter credentials and redirected to our application with a token code from twitter.This token code is like a key using which we can request twitter to provide the details we want or post update on behalf of the user in their streams.But password and email cannot be accessed by that token.

You can notice that there is  two redirection, first  is when the user click the “login with twitter” button and second is after authorization returning to our website.

authorize

redirect callback

redirect callback

 

Step by Step tutorial to login with Twitter using Php

Register the Application

Before getting started, the application which we are building should be registered in dev.twitter.com

Goto dev.twitter.com/apps and click  Create application

1.Provide the name for the application and description

2.Leave the call back url empty for now and complete the process

app registration

3.In the next screen click settings->application type select read only or read and write based on your requirements.If you are going to update the user stream you need to check read and write permission.(Don’t select Read, Write and Access direct messages)

4.Below that check the box where it says allow this application to be used to sign in with twitter

Click update settings button and note down the consumer secret,consumer key values from details tab

key

 Download the Abraham PHP library for Twitter API 1.1 and extract the files

 The existing example in the library is enough to get started but I have tweaked some code flow for simplicity sake.

In the config.php file add the keys which was noted earlier and mention the callback url.

Callback URL:It is the landing page after authorization completes.Once the user provides credentials, twitter will redirect to this call back url with additional data.In case of successful authentication the access token is returned and in case of failure error code is returned.

Tip : Callback url should handle both success and failure conditions.

In the connect.php file place the image link for the users to click.

sign in with twitter

After redirection request the access token specific for the user and store it in session variable for further.

1
2
3
$access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);

$access_token = $_SESSION['access_token'];

 

Requesting data from Twitter

1
2
3
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);

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

Get function will fetch the details from server and return the data in JSON format.Parse this JSON and filter the data needed.

response from twitter

Response from twitter

1
2
3
4
$user = json_decode($user, TRUE);
echo "Username".$user["name"];

echo "<br /><img src=\"".$user["profile_image_url"]."\"/>";

To access the tweets posted by the user

1
$tweets=$connection->GET('statuses/user_timeline');

Logout link simply clearing out the session variables like access token and other keys.

1
2
session_start();
session_destroy();

Destroying the session variables will clear the access token so that a new login request can be made next time.

Complete Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?php
session_start();
require_once('twitteroauth/twitteroauth.php');
require_once('config.php');

/* If access tokens are not available redirect to connect page. */
if (empty($_SESSION['access_token']) || empty($_SESSION['access_token']['oauth_token']) || empty($_SESSION['access_token']['oauth_token_secret'])) {
    header('Location: ./clearsessions.php');
}
/* Get user access tokens out of the session. */
$access_token = $_SESSION['access_token'];

/* Create a TwitterOauth object with consumer/user tokens. */
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);

/* If method is set change API call made. Test is called by default. */
$content = $connection->get('account/verify_credentials');
$user=json_encode($content);
 $user = json_decode($user, TRUE);
 echo "<pre>".print_r($user,1)."</pre>";
echo "Username: ".$user["name"];
echo "<br /><img src=\"".$user["profile_image_url"]."\"/>";
 $tweets=$connection->GET('statuses/user_timeline');
 $tweets = json_encode($tweets);
//print_r($tweets);
}
echo "<a href='./clearsessions.php'>Logout</a>"
?>

Demo

Download Source Code

Do you think this PHP twitter login tutorial is useful ? If Yes, Share/Comment below.You can also Get Regular Updates. Subscribe to Free RSS Feeds or Email Updates. Follow us on Twitter @Devlup and Like us on Facebook.

Related posts:

Leave a Reply