Step 1
Get your application registered with twitter and get Consumer Key and Secret for that. Go to  for registering your application.

Step 2
Go to and download OAuth.php and twitteroauth.php . These are the library files we use for accessing the api.

Step 3
Create a file config.php



 * @file

 * A single location to store configuration.*/

define(‘CONSUMER_KEY’, ‘Your Consumer Key’);

define(‘CONSUMER_SECRET’, ‘Your Conumer Secret’);

//Place your callback URL here

define(‘OAUTH_CALLBACK’, ‘http://localhost/oauth2/callback.php’);

Step 4
Create a file to connect with twitter. This will connect with twitter for one time request token. You’ll get an authentication URL. By clicking on this it will take you to the twitter window. Where you’ll have to give your twitter username and password. Then it redirects you to your callback page say callback.php

TwitterAccess.php (For one time access token)


/* Start session and load library. */




/* Build TwitterOAuth object with client credentials. */

$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);

 /* Get temporary credentials. */

$request_token = $connection->getRequestToken(OAUTH_CALLBACK);

/* Save temporary credentials to session. */

$_SESSION[‘oauth_token’] = $token = $request_token[‘oauth_token’];

$_SESSION[‘oauth_token_secret’] = $request_token[‘oauth_token_secret’];

/* If last connection failed don’t display authorization link. */

switch ($connection->http_code) {

  case 200:

    /* Build authorize URL and redirect user to Twitter. */

    $url = $connection->getAuthorizeURL($token);

    echo “<a href='”.$url.“‘>Login With Twitter</a>”;



    /* Show notification if something went wrong. */

    echo ‘Could not connect to Twitter. Refresh the page or try again later.’;


Remember to assign oauth token and oauth token secret in session. We’ll need this in callback page.
Here is our callback page (callback.php)-





$oauth = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET,

$array=$oauth->getAccessToken($_GET[‘oauth_verifier’]) ;

/*Permanent access tokens*/





/* Connect with Twitter API for accessing services */ 

$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION[“access_token”],$_SESSION[“access_token_secret”]);

$parameters = array(‘status’ => “Hello World”);

$status = $connection->post(‘statuses/update’, $parameters);



In callback page we get permanent access token and access token secret. We should save them in session because they will be used for accessing all twitter services. They will act as twitter username and password.

In callback.php we call post status service, that post your message ‘Hello World’ to twitter.