OAuth for PHP Twitter Apps, Part 1

Share this article

As of August 31, Twitter’s HTTP Basic Authenticated API service has been disabled entirely. Now, any interface with the API will be required to use a token-based authentication method known an OAuth.

What does this mean? Anyone who’s written a server-based application that talks to Twitter via its API will need to spend some time upgrading it. In this article, we’ll focus on automated back-end type applications, such as an app that automatically tweets when a new deal is available on a website, a sports score tweeter, or other similar apps. In part II, we’ll have a look at the more traditional OAuth model, where individual users authorize your app to access their Twitter accounts via a web interface.

At first glance, the task of implementing OAuth can appear daunting, and OAuth’s token exchange system can be confusing if you’re unfamiliar with it. Fortunately, there are some rather clever individuals who’ve done the groundwork for us, so let’s get started.

Registering Your App

Previously, Twitter didn’t require you to register your application. Under OAuth, however, you must do so. When you do, Twitter will provide you with a set of keys that you’ll need to connect your application to the API.

To register your app, visit http://dev.twitter.com/apps and complete the form, most of which is quite straightforward—though there are a couple of fields that may throw you:

  • Callback URL may be left blank if there’s no requirement for your application to authenticate users via a web interface. In the examples I mentioned above (auto-tweeting features of a website), there’s no login process, so there’s no need to provide a URL to redirect users to.

  • Default Access type refers to the access your application will have to Twitter. Read-only removes the ability to post tweets or add/remove friends, while Read & Write allows complete access. This is almost certainly what you want for your application.

  • Application Type should be changed to Client, even though this application may be run by a cron job simulating a web browser hit, or via a behind-the-scenes trigger from your website, a user will never directly interact with it through a browser.

Once your app is registered, you’ll be provided with an OAuth Consumer key and Consumer secret. These two strings are the basis for our OAuth connection.

Download the TwitterOAuth PHP Class

Originally developed by Abraham Williams, TwitterOAuth handles the generation, registration, and authentication of OAuth requests to interface with Twitter. Thanks to this class, it’s unnecessary to understand all the ins and outs of OAuth key and token manipulation. Go ahead and download a copy of the library. For this article I’ll be using version 0.2.0-beta3.

Modify the Class to Allow PIN-based OAuth Registration

Usually, web-based Twitter apps will authenticate with Twitter by passing the user over to Twitter, where they can click on an Authorize button. However, for apps without user interaction (such as the automated Tweet applications given as examples above), we’d rather avoid having to do that. Fortunately, Twitter has provided a PIN-based authentication option intended for desktop applications, but equally suitable for our automated web-based application.

The initial request is authorized by Twitter, and will give you a seven-digit PIN. Your application will then make a request using that PIN, which will provide it with an access token to be used in future requests.

However, the TwitterOAuth class we grabbed above lacks native support for PIN-based registration, so we’ll need to make a quick change to the code to make everything work. This code is based, with some modifications, on this blog post by Konstantin Kovshenin. Edit the file twitteroauth.php and replace the function getAccessToken beginning at line 111 with the following:

function getAccessToken($token = NULL, $pin = NULL) {  if($pin) {    $request = $this->oAuthRequest($this->accessTokenURL(), 'POST', array('oauth_verifier' => $pin));  } else {    $request = $this->oAuthRequest($this->accessTokenURL());  }  $token = OAuthUtil::parse_parameters($request);  $this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']);  return $token;}

Create a Request Token and a Registration URL

Now you need to generate some access tokens for your app. This takes place in two steps: first, you generate some request tokens and a register URL, and then you use those to generate the access tokens. The code you’ll write is only for the purposes of acquiring these tokens, and can be separate from your application. As a result, you can run it from your development or local server.

Create a folder in your server’s web root, and put the twitteroauth folder you downloaded (and modified) inside it.

Also in that folder, create a file called register.php, containing the following code:

Example 1. register.php

<?phprequire_once('twitteroauth/twitteroauth/twitteroauth.php');$oauth = new TwitterOAuth('consumer_key','consumer_secret');$request = $oauth->getRequestToken();$requestToken = $request['oauth_token'];$requestTokenSecret = $request['oauth_token_secret'];// place the generated request token/secret into local filesfile_put_contents('request_token', $requestToken);file_put_contents('request_token_secret', $requestTokenSecret);// display Twitter generated registration URL$registerURL = $oauth->getAuthorizeURL($request);echo '<a href="' . $registerURL . '">Register with Twitter</a>';?>

Remember to add in your consumer key and secret.

Once you’ve created the register script you’ll need to run it to request access from Twitter:

  1. Log in to Twitter (via the website) using the Twitter account you want the app to use

  2. Load the register.php file in your browser

  3. The script will create two files in its directory containing your request token and request token secret

  4. A link will display on the screen; this is a link to your registration URL.

  5. Click the link, and Twitter will ask if you’d like to authorize the app to access your account (the one you signed in to in step 1).

  6. Finally, Twitter will display a seven-digit PIN. Copy it down.

Generate Access Tokens

Now that Twitter has authorized our request for access, we need to pass back the provided PIN in order to generate an access token and its secret. Once this is done, our application will never again have to go through this authentication process, and will have permanent access to the linked Twitter account.

Create a new file, validate.php, in your development folder:

Example 2. validate.php

<?php// Retrieve our previously generated request token & secret$requestToken = file_get_contents("request_token");$requestTokenSecret = file_get_contents("request_token_secret");// Include class file & create object passing request token/secret alsorequire_once("twitteroauth/twitteroauth/twitteroauth.php");$oauth = new TwitterOAuth('consumer_key', 'consumer_secret', $requestToken, $requestTokenSecret);// Generate access token by providing PIN for Twitter$request = $oauth->getAccessToken(NULL, $_GET["pin"]);$accessToken = $request['oauth_token'];$accessTokenSecret = $request['oauth_token_secret'];// Save our access token/secretfile_put_contents("access_token", $accessToken);file_put_contents("access_token_secret", $accessTokenSecret);?>

This script expects you to pass the PIN as a GET parameter (for example, http://dev.machine/validate.php?pin=1234567), and will save files called access_token and access_token_secret to the folder. Access it in your browser, passing in the PIN.

warning: Time is of the Essence

The request tokens and register URL we generated in the previous step aren’t indefinite: Twitter will expire them after a given time has passed. If you receive errors accessing validate.php, or find that the generated files are empty, it could be because you’ve taken too long to fire up the script.

If this happens, simply hit up register.php again to generate a new PIN.

Tweet Away!

With all of the OAuth tokens done and dusted, it’s time to actually use the API. Let’s try the simplest test possible, and tweet “hello world” from the authorized account:

Example 3. test.php

<?php// Read in our saved access token/secret$accessToken = file_get_contents("access_token");$accessTokenSecret = file_get_contents("access_token_secret");// Create our twitter API objectrequire_once("twitteroauth/twitteroauth/twitteroauth.php");$oauth = new TwitterOAuth('consumer_key', 'consumer_secret', $accessToken, $accessTokenSecret);// Send an API request to verify credentials$credentials = $oauth->get("account/verify_credentials");echo "Connected as @" . $credentials->screen_name;// Post our new "hello world" status$oauth->post('statuses/update', array('status' => "hello world"));?>

Put this file in your test directory, and access it via your browser (again, you’ll need to paste in your own consumer key and secret). You’ll see confirmation that your account was connected, and if you now load up the account’s Twitter profile, you should see a “hello world” tweet!

Finally, a Clean-up and Some Security

Now that you’re up and running, the register.php, validate.php, request_token, and request_token_secret files are no longer required for the operation of your app. The access tokens that have been generated now handle all back and forwards between your app and Twitter. You’ll also note that none of the code we’ve written, or in any of the generated files, is there any mention of the linked Twitter account’s user name or password; this is a major security advantage of the OAuth method.

That said, if your access_token and access_token_secret files are in a publicly accessible web directory, the account’s security can still be compromised. Once generated, they should be shifted outside of your server’s web folders, and loaded in with PHP’s file operations. If, for some reason, that’s not an option for you, move them to a subfolder that’s inaccessible via the Web.


While it’s become a little more complicated up-front to set up an application with access to a Twitter account, there are definite security benefits to the OAuth approach. Once you learn the ropes, it’s quite straightforward to set up new applications with access to a Twitter account.

In part II of this series, we’ll turn our attention to Twitter apps that involve your users individually authorizing their accounts via the Web.

Image credit: drdjo

Raj DeutRaj Deut
View Author
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form