Sign in with Twitter using PHP

With millions of registered users worldwide, twitter is one of the most used social networking website on the internet, we cannot overlook its importance, it can really boost registrations rate in your site. In this tutorial, we will be using Twitter API to register users on your website.

I have created 3 PHP files for the tutorial : configuration, Login and process PHP files.
We also need Abraham William’s Twitter PHP Library, which is a widely used and known for its simplicity. I have included this library in downloadable file along with tutorial files below.

Configuration

Configuration file stores your Twitter Customer key, secret and callback URL. If you haven’t created Twitter application for your website, go to Twitter developer page and create one here. Once you finish creating Twitter App, you need to get your Customer key & Secret, and replace config variables in config.php file.

 
1
2
3
4
5
<?php
define('CONSUMER_KEY', 'XXX');
define('CONSUMER_SECRET', 'XXX');
define('OAUTH_CALLBACK', 'http://yoursite.com/process.php');
?>

Login page

Login Page (index.php) contains a login button, but you can put login button anywhere in your website. Once user clicks login, user must be redirected to process.php, from where user is sent to Twitter Auth page to obtains a request token, and again user is redirected back to process.php. On successful authorization, process.php sets details in session variables which will be used later in other pages to make GET/POST requests.

Trick is very simple, if this session is not set login button must be displayed in order to redirect use to Twitter authorization page.

 
1
2
3
4
5
6
if(isset($_SESSION['status']) && $_SESSION['status']=='verified')
{
// user is logged in
}else{
//show login button
}

Complete code of login page.

 
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
//start session
session_start();

//just simple session reset on logout click
if(isset($_GET["reset"]) && $_GET["reset"]==1)
{
    session_destroy();
    header('Location: ./index.php');
}

// Include config file and twitter PHP Library by Abraham Williams (abraham@abrah.am)
include_once("config.php");
include_once("inc/twitteroauth.php");
?>
<html>
<head>
<title>Sign-in with Twitter</title>
<link href="twitter_style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="wrapper">
<?php

if(isset($_SESSION['status']) && $_SESSION['status']=='verified')
{   //Success, redirected back from process.php with varified status.
    //retrive variables
    $screenname         = $_SESSION['request_vars']['screen_name'];
    $twitterid          = $_SESSION['request_vars']['user_id'];
    $oauth_token        = $_SESSION['request_vars']['oauth_token'];
    $oauth_token_secret = $_SESSION['request_vars']['oauth_token_secret'];

    //Show welcome message
    echo '<div class="welcome_txt">Welcome <strong>'.$screenname.'</strong> (Twitter ID : '.$twitterid.'). <a href="index.php?reset=1">Logout</a>!</div>';
    $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $oauth_token, $oauth_token_secret);

    //see if user wants to tweet using form.
    if(isset($_POST["updateme"]))
    {
        //Post text to twitter
        $my_update = $connection->post('statuses/update', array('status' => $_POST["updateme"]));
        die('<script type="text/javascript">window.top.location="index.php"</script>'); //redirect back to index.php
    }

    //show tweet form
    echo '<div class="tweet_box">';
    echo '<form method="post" action="index.php"><table width="200" border="0" cellpadding="3">';
    echo '<tr>';
    echo '<td><textarea name="updateme" cols="60" rows="4"></textarea></td>';
    echo '</tr>';
    echo '<tr>';
    echo '<td><input type="submit" value="Tweet" /></td>';
    echo '</tr></table></form>';
    echo '</div>';

        //Get latest tweets
        $my_tweets = $connection->get('statuses/user_timeline', array('screen_name' => $screenname, 'count' => 5));
        /* echo '<pre>'; print_r($my_tweets); echo '</pre>'; */

        echo '<div class="tweet_list"><strong>Latest Tweets : </strong>';
        echo '<ul>';
        foreach ($my_tweets  as $my_tweet) {
            echo '<li>'.$my_tweet->text.' <br />-<i>'.$my_tweet->created_at.'</i></li>';
        }
        echo '</ul></div>';

}else{
    //login button
    echo '<a href="process.php"><img src="images/sign-in-with-twitter-l.png" width="151" height="24" border="0" /></a>';
}

?>
</div>
</body>
</html>

Process

Main task of process.php  is to compare variables and redirect user back and forth. When user clicks on login button in index.php, user is sent to process.php, then it obtains a request token which is passed to Twitter Authorize page as oauth_token parameter. Once user signs in, user is authenticated and returned to the callback URL.

 
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php
session_start();
include_once("config.php");
include_once("inc/twitteroauth.php");

if (isset($_REQUEST['oauth_token']) && $_SESSION['token']  !== $_REQUEST['oauth_token']) {

    // if token is old, distroy any session and redirect user to index.php
    session_destroy();
    header('Location: ./index.php');

}elseif(isset($_REQUEST['oauth_token']) && $_SESSION['token'] == $_REQUEST['oauth_token']) {

    // everything looks good, request access token
    //successful response returns oauth_token, oauth_token_secret, user_id, and screen_name
    $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['token'] , $_SESSION['token_secret']);
    $access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
    if($connection->http_code=='200')
    {
        //redirect user to twitter
        $_SESSION['status'] = 'verified';
        $_SESSION['request_vars'] = $access_token;

        // unset no longer needed request tokens
        unset($_SESSION['token']);
        unset($_SESSION['token_secret']);
        header('Location: ./index.php');
    }else{
        die("error, try again later!");
    }

}else{

    if(isset($_GET["denied"]))
    {
        header('Location: ./index.php');
        die();
    }

    //fresh authentication
    $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
    $request_token = $connection->getRequestToken(OAUTH_CALLBACK);

    //received token info from twitter
    $_SESSION['token']          = $request_token['oauth_token'];
    $_SESSION['token_secret']   = $request_token['oauth_token_secret'];

    // any value other than 200 is failure, so continue only if http code is 200
    if($connection->http_code=='200')
    {
        //redirect user to twitter
        $twitter_url = $connection->getAuthorizeURL($request_token['oauth_token']);
        header('Location: ' . $twitter_url);
    }else{
        die("error connecting to twitter! try again later!");
    }
}
?>

I hope this tutorial will help you, Once you understand the flow, it will be easier to implement it on your website. any feedback or comment is appreciated, Good luck!

Download Demo

Related Articles:

Article by on August 7, 2012 Tagged under Tagged under , . If you like this article, please consider sharing it.

10 Thoughts

  1. despite I’ve tried more than once I getting always “error connecting to twitter! try again later!” (error code 401). I was wondering whether I have forgotten to setting something on twitter when I created the application. Can anyone tell me if there’s something else to set on twitter?

    • hi sir . i am new in php and i am trying to create twitter user login id by php as i process accrdoing to your code step by step by getting error whenever i am trying to use by remote

Leave a Comment

Get your comment picture from Gravatar.com.
Your email address will not be published. Required fields are marked *