Try Tuts+ Premium, Get Cash Back!
How to Authenticate Users With Twitter OAuth

How to Authenticate Users With Twitter OAuth

Tutorial Details
  • Topic: PHP
  • Difficulty: Intermediate
  • Estimated Completion Time: 30-45 minutes

Beginning August 16th, Twitter will no longer support the basic authentication protocol for its platform. That means the only way to authenticate users will be through a Twitter application. In this tutorial, I’ll show you how to use Twitter as your one-click authentication system, just as we did with Facebook.


Step 1: Setting Up The Application

We’ll first need to set up a new Twitter application.

  • Register a new app at dev.twitter.com/apps/
  • Fill in the fields for your site accordingly, just be sure to select Browser in Application Type, and set the Callback URL to something like http://localhost.com/twitter_login.php (http://localhost/ won’t be accepted because it doesn’t have a domain name).
  • Finally, select Read & Write. Fill in the captcha, click “Register Application,” and accept the Terms of Service.

Now, you’ll see the screen as shown below.

We will be using the Consumer key and Consumer secret values shortly.

Now that this is done, let’s download a library. As we will be coding with PHP, it seems the best one is twitteroauth; but if you’re using another language, you’ll find other good libraries here.

Find the twitteroauth directory inside the zip file, and extract it to your application’s folder.

Finally, since we’re using Twitter to authenticate users, we’ll need a database table to store those users. Here’s a quick example of what we will be doing.

CREATE TABLE `users` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `oauth_provider` varchar(10),
    `oauth_uid` text,
    `oauth_token` text,
    `oauth_secret` text,
    `username` text,
    PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1;

Notice the oauth_token and oauth_secret fields. Twitter’s OAuth requires token and a token_secret values to authenticate the users, so that’s why we’re including those. With that, we are done with the setup!


Step 2: Registering Users

In this step we, will be doing three things:

  • Requesting authorization from Twitter.
  • Registering or, if the user is already registered, logging the user in.
  • Setting the data into a session.

Requesting authorization

The OAuth workflow starts by generating a URL for the request; the user is redirected to that URL and is asked for authorization. After granting it, the application redirects back to our server with two tokens in the URL parameters, which are required for the authentication.

Let’s begin by including the library and starting a session handler.

require("twitteroauth/twitteroauth.php");
session_start();

After that, let’s create a new TwitterOAuth instance, giving it the consumer key and consumer secret that Twitter gave us when we created the application. Then, we’ll request the authentication tokens, saving them to the session, and redirect the user to Twitter for authorization.

// The TwitterOAuth instance
$twitteroauth = new TwitterOAuth('YOUR_CONSUMER_KEY', 'YOUR_CONSUMER_SECRET');
// Requesting authentication tokens, the parameter is the URL we will be redirected to
$request_token = $twitteroauth->getRequestToken('http://localhost.com/twitter_oauth.php');

// Saving them into the session
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];

// If everything goes well..
if($twitteroauth->http_code==200){
    // Let's generate the URL and redirect
    $url = $twitteroauth->getAuthorizeURL($request_token['oauth_token']);
    header('Location: '. $url);
} else {
    // It's a bad idea to kill the script, but we've got to know when there's an error.
    die('Something wrong happened.');
}

Save it as twitter_login.php, go to http://localhost.com/twitter_login.php or whatever your local host name is. If everything went correctly, you should be redirected to twitter.com, and you should see something like this.

Click allow, and you will be redirected to http://localhost.com/twitter_oauth.php — since we set this URL as a parameter in the getRequestToken statement. We haven’t created that file, so it should throw an error. Create that file, and then include the library and start a session, just like we did in the first file.

After that, we will need three things:

  • Auth verifier in the URL query data
  • Auth token from the session
  • Auth secret from the session

So, the first thing to do in this script is validate this data and redirect if one of these variables is empty.

if(!empty($_GET['oauth_verifier']) && !empty($_SESSION['oauth_token']) && !empty($_SESSION['oauth_token_secret'])){
    // We've got everything we need
} else {
    // Something's missing, go back to square 1
    header('Location: twitter_login.php');
}

Now, if everything is set, inside the conditional we will be creating the TwitterOAuth instance, but with the tokens we just got as third and fourth parameters; after that, we will be getting the access token, which is an array. That token is the one we will be saving to the database. Finally, we’ll do a quick test to see if everything works out.

// TwitterOAuth instance, with two new parameters we got in twitter_login.php
$twitteroauth = new TwitterOAuth('YOUR_CONSUMER_KEY', 'YOUR_CONSUMER_SECRET', $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
// Let's request the access token
$access_token = $twitteroauth->getAccessToken($_GET['oauth_verifier']);
// Save it in a session var
$_SESSION['access_token'] = $access_token;
// Let's get the user's info
$user_info = $twitteroauth->get('account/verify_credentials');
// Print user's info
print_r($user_info);

If nothing goes wrong, the print_r should show the user’s data. You can get the user’s id with $user_info->id, his or her username with $user_info->screen_name; there’s a bunch of other info in there as well.

It is very important to realize that the oauth_verifier hasn’t been used before this. If you see the user’s info correctly and then reload the page, the script will throw an error since this variable has been used. Just go back to twitter_login.php and it will automatically generate another fresh token.

Registering users

Now that we have the user’s info we can go ahead and register them, but first we have to check if they exist in our database. Let’s begin by connecting to the database. Add these lines in the script’s beginning.

mysql_connect('localhost', 'YOUR_USERNAME', 'YOUR_PASSWORD');
mysql_select_db('YOUR_DATABASE');

Modify the database info as required. Now, just below where we fetch the user’s info, we’ll have to check for the user in our database. If he or she is not there, we’ll enter the info. If the user has been registered, we must update the tokens, because Twitter has generated new ones and the ones we have in the database are now unusable. Finally, we set the user’s info to the session vars and redirect to twitter_update.php.

if(isset($user_info->error)){
    // Something's wrong, go back to square 1
    header('Location: twitter_login.php');
} else {
    // Let's find the user by its ID
    $query = mysql_query("SELECT * FROM users WHERE oauth_provider = 'twitter' AND oauth_uid = ". $user_info->id);
    $result = mysql_fetch_array($query);

    // If not, let's add it to the database
    if(empty($result)){
        $query = mysql_query("INSERT INTO users (oauth_provider, oauth_uid, username, oauth_token, oauth_secret) VALUES ('twitter', {$user_info->id}, '{$user_info->screen_name}', '{$access_token['oauth_token']}', '{$access_token['oauth_token_secret']}')");
        $query = mysql_query("SELECT * FROM users WHERE id = " . mysql_insert_id());
        $result = mysql_fetch_array($query);
    } else {
        // Update the tokens
        $query = mysql_query("UPDATE users SET oauth_token = '{$access_token['oauth_token']}', oauth_secret = '{$access_token['oauth_token_secret']}' WHERE oauth_provider = 'twitter' AND oauth_uid = {$user_info->id}");
    }

    $_SESSION['id'] = $result['id'];
    $_SESSION['username'] = $result['username'];
    $_SESSION['oauth_uid'] = $result['oauth_uid'];
    $_SESSION['oauth_provider'] = $result['oauth_provider'];
    $_SESSION['oauth_token'] = $result['oauth_token'];
    $_SESSION['oauth_secret'] = $result['oauth_secret'];

    header('Location: twitter_update.php');
}

Note that these queries are not validated; if you leave them as they are, you are leaving your database vulnerable. Finally, below the database connection, we should set a check to verify that the user is logged in.

if(!empty($_SESSION['username'])){
    // User is logged in, redirect
    header('Location: twitter_update.php');
}

You can now greet the user by his or her username.

<h2>Hello <?=(!empty($_SESSION['username']) ? '@' . $_SESSION['username'] : 'Guest'); ?></h2>

Let’s get to the fun side: updating, following and reading.


Step 3: Reading Statuses

There are over twenty categories of resources available: timeline, tweets, users, trends, lists, direct messages, etc. Each one has a bunch of methods, you can check them all in the official documentation. We’ll get to the basics, as most of these features are accessed in a similar way.

Just like the other two scripts, we’ll need to create the TwitterOAuth instance, including the variables in the session.

if(!empty($_SESSION['username'])){
    $twitteroauth = new TwitterOAuth('YOUR_CONSUMER_KEY', 'YOUR_CONSUMER_SECRET', $_SESSION['oauth_token'], $_SESSION['oauth_secret']);
}

We’ll begin with the user’s timeline. The reference tells us that the path is statuses/home_timeline; ignore the version and format, the library will take care of it.

$home_timeline = $twitteroauth->get('statuses/home_timeline');
print_r($home_timeline);

That will get you the timeline. You can fetch each item with a foreach loop. However, the reference specifies some optional parameters like count, which limits how many tweets will be fetched. In fact, get‘s second parameter is an array of every option needed, so if you want to fetch the latest forty tweets, here’s the code:

$home_timeline = $twitteroauth->get('statuses/home_timeline', array('count' => 40));

Also, you can see somebody else’s timeline, as long as it’s not protected. statuses/user_timeline requires either a user’s id or screen name. If you want to check @nettuts timeline, you’ll have to use the following snippet:

$nettuts_timeline = $twitteroauth->get('statuses/user_timeline', array('screen_name' => 'nettuts'));

As you can see, after authenticating, reading timelines is a breeze.


Step 4: Friendships

With friendships, you can check if a user follows another one, as well as follow or unfollow other users. This snippet will check if you are following me and and will create the follow if not.

But first, check the friendships/exists and friendships/create reference. Notice something? friendships/create method is POST. Fortunately, the library includes a post() function, which works just as the get() function; the main difference is that get() is for reading and post() is for creating, deleting or updating.

Anyways, friendships/exists requires two parameters: user_a and user_b, and friendships/create requires just one, either screen_name or user_id.

$follows_faelazo = $twitteroauth->get('friendships/exists', array('user_a' => $_SESSION['username'], 'user_b' => 'faelazo'));
if(!$follows_faelazo){
    echo 'You are NOT following @faelazo!';
    $twitteroauth->post('friendships/create', array('screen_name' => 'faelazo'));
}

You can unfollow an user with basically the same code that creates a follow, just replace create with destroy:

$follows_faelazo = $twitteroauth->get('friendships/exists', array('user_a' => $_SESSION['username'], 'user_b' => 'faelazo'));
if($follows_faelazo){
    echo 'You are following @faelazo! Proceed to unfollow...';
    $twitteroauth->post('friendships/destroy', array('screen_name' => 'faelazo'));
}

Step 5: Posting Updates

This is probably the most interesting section, since it’s Twitter’s core: posting an update, as you might have imagined, is pretty straightforward. The path is statuses/update, the method is POST (since we are not reading), and the one required argument is status.

$twitteroauth->post('statuses/update', array('status' => 'Hello Nettuts+'));

Now go to your Twitter profile page and you’ll see your tweet.

Let’s retweet @Nettuts’ update announcing the HTML 5 Competition; the status id is 19706871538 and the reference tells us that the path is statuses/retweet/:id, where the :id part is the status id we will be retweeting. The method is POST and it doesn’t require additional parameters.

$twitteroauth->post('statuses/retweet/19706871538');

To delete a tweet, you’ll have to pass the status id you’ll be destroying in the first parameter, just like retweeting. If the tweet’s id is 123456789, the code to destroy will be.

$twitteroauth->post('statuses/destroy/123456789');

Of course, this code can only delete tweets made by the authenticated user.


Conclusions

Twitter’s API is quite easy to understand; it’s far more documented than even Facebook’s (even though Facebook offers an in-house library). Unfortunately, the authentication is not as smooth as we might hope, depending on session data.

One thing worth noticing is that, once a Twitter user has been authorized (assuming the app has read and write permissions), you have plenty of control over this account. If you change something on behalf of the user without his permission, you’ll create trouble. Use it with caution!

The API changes coming to Twitter will deny basic authentication; Twitter is focusing on ceasing the countless scams that trick users into giving up their login credentials. OAuth is the solution; and, if you’ve worked through the Facebook Connect tutorial, you can now provide your website or app users with a quick login without credentials, using your choice of the two most used social networks. How cool is that?

Rafael Soto is faelsoto on Codecanyon
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.facebook.com/MohamedZarhan Mohamed Zahran

    Great tutorial, I like API and I think i’m going to use it in my next script ;)

  • http://cdnpic.com cdnpic

    Very Detailed tutorial..
    Thanks :)

  • Sahan

    Thank you!

  • Will

    Loving the tutorial. How come people are still even suggesting using the antiquated mysql_connect though?

  • http://shamekh.ws/en Waseem

    this is an amazing tutorial ,

    but what about desktop apps ? like Air apps for example

    • http://peshir.nl/ peSHIr

      Youd have to ask Twitter to allow your application to use their XAuth API method. This allows you to ask the user for username and password (which you should only use for the XAuth call and never store!) and ask Twitter in one call to authenticate your app with this user. This gives you a token and secret for the user that you then use in the normal OAuth way to interact with the users Twitter account. This takes the OAuth web based redirect protocol to get a token and secret without actually getting username/password from the user out of the equation. See http://dev.twitter.com/pages/xauth for more information.

  • http://mkaito.github.com Michishige Kaito

    Awesome walkthrough! Now we’re missing one for Google OAuth.

    • http://jiewmeng.tumblr.com Jiew Meng

      I second that

  • Luke

    So glad to not see a “FIRST” post…

    I gotta say, this is amazing thankyou for the tutorial.

    @Waseem check out the Twitter API documentation, it’s great for things such as this.

  • http://www.nothing.com SAPONO

    Using Codeigniter pleasee………………

    waiting fot that.

    thanks…

  • http://samanthaarmacost.com Samantha Armacost

    This is a great tutorial. However, I don’t know if I am just having a hard time wrapping my head around it, but I’ve been trying to find info on the two legged use of OAuth. Does anyone know of a tutorial focusing on a more simplistic implementation of OAuth? Thanks in advance if you do!

  • Neil

    Hi there,

    Are there some files missing from the download? I didn’t get what the file should be named for the Registering Users section. :S

  • http://alvincrespo.com Alvin Crespo

    You forgot to mention that you’re using Abraham Williams OAuth library here: http://github.com/abraham/twitteroauth.

    • http://alvincrespo.com Alvin Crespo

      woops! I had skimmed through the article and missed the part where the library is mentioned. Sorry!

  • http://designsource.cz.cc esranull

    perfect post thanks

  • http://www.otreva.com Mike

    Hopefully this stops scams like they say because I will have to write a new widget for a client although it doesn’t look too bad.

  • http://www.thedevelopertuts.com Bratu Sebastian

    Great tutorial!

    This will enable us make our own logins !

  • # Unes

    Very helpful for newbies, thank you!

  • Josh

    Just so I’m clear, Twitter will break the connections in the below article come August so one cannot pull even a status, correct?

    http://net.tutsplus.com/tutorials/other/diving-into-the-twitter-api/

  • Eric

    I was just starting a project requiring Twitter data retrieval via the API and was having some trouble understanding the authentication flow – thanks for a clear explanation via this great tutorial!

  • Kunal Rajendra Sagar

    Nice one… :)

  • http://www.jsxtech.com Jaspal Singh

    Nice article to authenticate users with Twitter OAuth.
    Thanks for posting.

  • http://www.weebernet.com Penang Web Design

    thanks a lot…it is very details…

  • http:stembimo.com/ Parth

    A nice read. Thanks!

  • http://www.wwebz.com Rehaan

    Hey very detailed tutorial. Thanks for sharing such great information

    Thanks :)

  • kuzvac

    Great, Thanks!

  • Arnab

    Nice tutorial , but still we will have some problem regarding the control of the user accounts….

  • Oauth Developer

    Hi Rafael,

    Please update the download zip file with the source files for the code used in this tutorial.

    Thanks
    Jesie Lynn

    • http://alexanderquinonez.com alexander Quinonez

      I would also appreciate this or at lease update the tutorialto show what each page should look like after the code is entered correctly. As of right now im lost.

      Thanks!

    • shaon

      Please update the source file. It only has the oAuth.php and twitteroauth.php.

  • http://twitter.com/mamunabms Abdullah Al Mamun

    Nice explanation, thanks a lot for sharing. :-)

  • lona91

    I have a problem when running the twitter_login.php:
    “Fatal error: Call to undefined function curl_init() in C:\xampp\htdocs\twitter\twitteroauth\twitterOAuth.php on line 199″

    • Eric

      I have having the same issue here.

      • Eric

        Hey Lona91 the problem was in the php.ini. Its relatively easy to fix the extensions just is not active. go into your php.ini and take the semi colon off the

        extension=php_curl.dll

        save it and restart your server you should be up and running.

        a good way to check if the extension is active is

        <?php
        echo '’;
        var_dump(curl_version());
        echo ”;
        ?>

        if you get an error its not active. If you get an array with information your should be active and good to go

  • http://alexanderquinonez.com Alexander Quinonez

    Question: Im struggling with step 2. “twitter_oauth.php”

    I keep getting “Warning: Cannot modify header information – headers already sent by…” etc.

    after i put in the code for registering users. its giving me the proper info but im just getting that one error.

    Any ideas? Thanks!

    • Billybob

      A year old reply but incase others come across that issue in the future: comment out / remove references to “print_r”. Good luck.

  • shayuna

    great article. thanks.
    i have a question:
    no matter how i tried to pass a variable to the update_twitter.php, it didn’t succeed.
    i understand that the update_twitter.php is on a different session than the session that started the twit procedue, but still, is there anyway to pass a variable from my initiating page to the update_twitter.php page ?
    (i want to send a tweet, the content of which will be determined online)
    thanks

  • Diogo

    Hi, great toturial! Thank you.

    This is my case:
    We use one twitter account for our company, so in our system we have an area where everybody with permissions can read and post tweets. The question is: Now everybody have to know the user and pass of twitter account and login manually to begin work?

  • http://www.9lessons.info Srinivas Tamada

    Related Post:

    Connect Twitter API with OAuth using PHP.

    http://www.9lessons.info/2010/02/connect-twitter-api-with-oauth-using.html

  • João Lopes

    Great, i really was looking for this and it was just here.
    Nice job. :)

    I’ve made a simple program to facebook that allows me to publish even when the user is offline.
    Using only the id of the user. But in this api i simple can’t do that.
    By the way, if someone’s interested on my facebook program, please tell me and i’ll make a tutorial rebuilding it.

    One las thing, does anyone know how do i change my avatar picture?

  • http://spotdex.com Davidmoreen

    Very cool! This is one of the first OAuth tutorials I’ve seen that was really well done.

  • http://itvillage.site11.com/ IT Village

    very informative and cool. I will try it.

  • Fawaz

    Somehow, my callback URL gets called twice. The first time is ok but the second time “oauth_verifier” is invalid. I was unable to find out where the second call comes from. Any help? I am using 127.0.0.1 in the callback URL and it was working first time I put the code together.

  • http://buzzknow.com Buzzknow

    Hi

    why my script doesnt work when try to check about friendship?

    anyone has this problem too?

    its not return bool .. but like http request and all details

    thanks

    • http://buzzknow.com Buzzknow

      Its fix now :)

      btw anyone know how to undo retweet via api? since i can’t get ID of new retweet ..

      thanks

  • http://phun-ky.net Alexander Vassbotn Røyne-Helgesen

    Nice tutorial!

    You suddenly mention twitter_update.php here, what does it do? Cant find any other reference to the file..

  • james

    How I will get the “status Id” of a status (fro destroy)using oauth in php. can u explain…

    Great Demo…thanks

  • Rariti

    Hey Great Tutorial.
    I combined what I learned here as well as from http://www.1stwebdesigner.com/tutorials/twitter-app-oauth-php/
    and got my twitter app just the way I like it.
    I now have an app integrated into a custom CMS that posts to the db and Twitter, pulls timeline list from cache if nothing new, or pulls in new if new and updates db/cache.
    And most importantly from your great tutorial, got rid of the repeated Twitter authorization for active sessions.

    It took a little while, but the learning process was very beneficial.

    Well done.

  • John

    Not sure why everyone says this is a good tutorial, it doesn’t work. Even with a ton of fixes to the code, it still doesn’t work. The downloads only have Abraham’s O_Auth library which they haven’t given him credit for.

    Jeffery, I have to question the quality of Net Tuts, this is so poorly done. If you were my employee and put out crap like this, I would fire you!

  • cullen

    after following step 2, and testing to see if there is a twitter “authenticate this app” redirect, i get this:

    Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or ‘}’ in twitteroauth.php on like 17

    ive done nothing to edit that library file. whats going on?

  • Cullen

    nevermind. php version on server was 4 instead of 5

  • http://adisandu.ro Adi Sandu

    Hi!

    Any ideas for those who use php version under 5? My php version is 4.4. and it doesn’t work. I get this error:

    arse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or ‘}’ in twitteroauth.php on like 17

    My hosting cannot update to php 5 on the moment and i realy need something to update the twitter status.

    Thanks very much!

    Adrian

  • http://crossover-it.ch ihkawiss

    Thanks a lot !

  • Fabio

    It seems that @abraham’s code still doesnt change the avatar. Does anybody know how it can be done?

  • http://www.salhah.com/ Salhah

    excellent a lot.

  • Celina

    This is the fucking better guide ever!!

    Thanks a lot!!!!

  • saika

    Wooow maan u did a great job, thaaanks a lot.

  • Akash

    Hi,
    Please Help!! Why this error is coming

    Undefined property: TwitterOAuth::$http_code in…………..

  • http://ommune.com Santosh

    Nice stuff mate :)