Created: 2011-07-17 09:20
Updated: 2014-06-21 02:34
License: mit



A PHP class using the Pear OAuth library to connect to the Twitter api.


  • PHP 5.3+
  • PECL OAuth (tested with 1.1)
    • sudo pecl install oauth
  • PECL HTTP (tested with 1.7.1)
    • sudo pecl install pecl_http
  • PHPUnit if you want to run the tests

Example usage

In these examples, the consumer key and secret are stored as constants named CONSUMER_KEY and CONSUMER_SECRET respectively. First up, create a Twitteryauth object:

$options = array(
	'consumer_key' => CONSUMER_KEY,
	'consumer_secret' => CONSUMER_SECRET

$twitter = new Twitteryauth($options);

Request an authorisation URL, passing in the URL that twitter will use as a callback, and store the request secret in a session:

$url = $twitter->get_authorize_url('');
$_SESSION['request_secret'] = $twitter->get_config('request_secret');
header('Location: '.$url);

In your callback function, you want to grab the oauth token and pass that through to the authenticate method. If all is good, this will give you the access key and secret. You'll then want to save these in the session too, and use them in future to access the api:


$_SESSION['access_key'] = $twitter->get_config('access_key');
$_SESSION['access_secret'] = $twitter->get_config('access_secret');

unset($_SESSION['request_secret']); // no longer needed


To make things easier for yourself after you have the access tokens, when you're initialising your Twitteryauth object, I'd pass in an array of options. That way, you can have the object being created in one place:

$options = array(
	'consumer_key' => CONSUMER_KEY,
	'consumer_secret' => CONSUMER_SECRET

$tokens = array('request_secret', 'access_key', 'access_secret');

foreach ($tokens as $token)
	if (isset($_SESSION[$token]))
		$options[$token] = $_SESSION[$token];

$twitter = new Twitteryauth($options);

You can always check to see if you're authenticated (the Twitteryauth object having the access tokens):


To make calls to the twitter api:


$twitter->post('statuses/update', array(
	'status' => 'Trying out Twitteryauth!'
Cookies help us deliver our services. By using our services, you agree to our use of cookies Learn more