Schlagwort-Archive: twitter

How to use the Twitter API with PHP and OAuth (single user)

Since a few months, applications have to use OAuth to authenticate a Twitter account using the REST API. If you want to write a php application for just one account (like your own small webclient), you don’t have to go the „ping-pong“ way of authentication. You only need this to authenticate different users and as we only need access for one single user, it is possible to simplify the oauth authentication step. Nevertheless I find it much more comfortable to you a finished library. In this example we will use Abraham Williams‘ awesome TwitterOAuth library for PHP, which requires a minimum PHP version of 5.2.x, cURL and OpenSSL.

First you have to visit http://dev.twitter.com/apps an register a new application. Choose „Browser“ as application type and set the default access level to „Read & Write“. You will need the printed „Consumer key“ and „Consumer secret“ in the next step. Also you will need the „Access Token (oauth_token)“ and „Access Token Secret (oauth_token_secret)“, which can be found under „My Access Token“ in the right menu.

Include the library in your PHP script. Change the path accordingly.

require_once(‚twitteroauth/twitteroauth.php‘);

Open your config file and define the 4 needed keys like:

define(‚CONSUMER_KEY‘, ‚aAaAaAaAaAaAaAaAaAaA‘);
define(‚CONSUMER_SECRET‘, ‚bBbBbBbBbBbBbBbBbBbB‘);
define(‚OAUTH_TOKEN‘, ‚cCcCcCcCcCcCcCcCcCcC‘);
define(‚OAUTH_TOKEN_SECRET‘, ‚dDdDdDdDdDdDdDdDdDdD‘);

To connect to Twitter, add in your PHP script:

$twitter = new TwitterOAuth (CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET);

You can now use the $twitter object to interact with the Twitter API. For example fetch your user information or post an update.

$twitter->get(‚account/verify_credentials‘);
$twitter->post(„statuses/update“, array(„status'“=> „First tweet using my own Twitter app!“));

Check out the TwitterOAuth documentation for more options and the Twitter documentation for available ressources.

I hope this small guide helps you getting started and I would love to see some of your results. Questions? Comments!