The Twitter API, PHP, and OAuth

Just a quick note today on how to access the Twitter API using PHP, specifically using the Abraham Williams PHP TwitterOAuth library. While the library itself seems very good, I couldn't find much in the way of documentation, particularly a simple "getting started" tutorial, so I thought I'd share this code.

In short, I dug through the PHP files in the root directory of the TwitterOAuth library, eventually creating this simple PHP Twitter client example:

<?php

// include the twitteroauth library
require_once('twitteroauth/twitteroauth.php');

// two steps here. first, edit the config.php file to include the CONSUMER_KEY
// and CONSUMER_SECRET codes. you get these from twitter when you log into the twitter
// dev site as a developer, and create a new app.
// step two is to then include this file, like this:
require_once('config.php');

// i got these codes from twitter as "alvin alexander, the consumer".
// they say "alvin alexander has approved access for this application":
$access_token        = '<your twitter access token here>';
$access_token_secret = '<your twitter access token secret here>';

// with all the codes you need, now create a TwitterOauth object.
// the twitteroauth examples referred to this as $connection, so i
// stayed with that naming convention.
$connection = new TwitterOAuth(CONSUMER_KEY, 
                               CONSUMER_SECRET, 
                               $access_token,
                               $access_token_secret);

$content = $connection->get('account/rate_limit_status');
echo "Current API hits remaining: {$content->remaining_hits}.";

// you can now call all the methods on the twitteroauth/connection object
$user = $connection->get('account/verify_credentials');
var_dump($user);

?>

If you 1) download and install the TwitterOAuth PHP library, 2) create a Twitter app (to get the consumer key and secret), 3) get the Twitter access codes you need (as an app user), then 3) name this file mytest.php, you should then be able to run this PHP script from the command line like this:

php mytest.php

The echo statement at the end of the script should show something like this:

Current API hits remaining: 349

Once you have this basic functionality working, you can dig through test.php script which is included with the TwitterOAuth library for many more examples.

Again, this was just a simple "getting started" with TwitterOAuth example, but I hope you find it helpful in getting started with the Twitter API and PHP. You can find more information on the Twitter developer website, and you can also explore the Twitter API with Twitter's developer console.