Twitter, PHP oAuth: update status

Recently Twitter announced they are going disable basic authentication mechanism. Basic auth can be used until June 30th 2010, so there is only less then one month left (assuming you are reading this on June 2010). I admit that for a long time i neglected the OAuth Twitter authorization, it seemed complicated and time consuming in comparison basic auth.



However, when i found out they are shutting down the basic api, i had no other choice then to learn how it works. What it turned out is that with the right tools it’s pretty easy to do. Especially if you are (like me) looking to setup application that will be using only single user. For example to automatically update your status.
The setup

With basic authorization all we needed was Twitter login and password, with OAuth it’s more complicated but a lot more secure at the same time, even if your app will be hacked your Twitter credentials are still safe.

Ok let’s get started with it:

  • Go to dev.twitter.com sign in with your Twitter credentials, next click “Register an application” link

  • Fill the form, it’s automatically accepted so Twitter guys probably don’t check it all, but still … keep it proffesional. One important thing here is to select “Read and Write” on “Default Access type”. Click “Register Application” and you’re done

  • Now you will need 4 keys to make your app work. Go to “View Your Applications” and then click “Edit details” on your newly created app. Scroll down and copy (somewhere) “Consumer Key” and “Consumer Secret”

  • Next in the right sidebar click link “My access token” and copy both: “Access Token (oauth_token)” and “Access Token Secret (oauth_token_secret)”


Abraham Twitter OAuth library(click the link to download the zip file of app). There few files in the archive, but we will need only two: twitteroauth/twitteroauth.php and twitteroauth/OAuth.php.
Twitter and PHP OAuth integration

Now let’s get straight to the actual code. The good news it’s there almost nothing to do: just include TwitterOAuth library, put keys and tokens you copied earlier into the script and you are done.
<?php
require_once 'TwitterOAuth.php';

define("CONSUMER_KEY", "XXXX");
define("CONSUMER_SECRET", "XXXX");
define("OAUTH_TOKEN", "XXXX");
define("OAUTH_SECRET", "XXXX");

$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_SECRET);
$content = $connection->get('account/verify_credentials');

$connection->post('statuses/update', array('status' => 'Test status message'));

Comments

Popular posts from this blog

How to check browser cookie enabled with php and javascript

cookie and subdomains

Output buffering in php