Home Page

  • September 30, 2023, 10:40:50 PM *
  • Welcome, Guest
Please login or register.

Login with username, password and session length
Advanced search  


Official site launch very soon, hurrah!

Author Topic: Using Twitter API v1.1  (Read 6370 times)


  • Programmer Person
  • Administrator
  • Hero Member
  • *****
  • Posts: 528
    • View Profile
    • Dakusan's Domain
Using Twitter API v1.1
« on: August 06, 2013, 02:03:50 PM »

Original post for Using Twitter API v1.1 can be found at https://www.castledragmire.com/Posts/Using_Twitter_API_v1.1.
Originally posted on: 08/06/13

Twitter recently turned off their v1.0 API which broke a multitude of applications, many of which are still broken today. I had the need to immediately update at least one website to the new Twitter v1.1 API, but I could not find a simple bare bones example on the internet. Pretty much all the code/libraries out there I could find for the new API version were hundreds to thousands of lines long, or didn’t work >.<; . So anywho, here is the simple PHP code I put together to make API calls.

This code requires certain consumer/authentication keys and secrets. You can find how to generate them elsewhere online.

//OAuth Request parameters
$ConsumerKey='FILL ME IN';
$ConsumerSecret='FILL ME IN';
$AccessToken='FILL ME IN';
$AccessTokenSecret='FILL ME IN';

function EncodeParam($input) { return strtr(rawurlencode($input), Array('+'=>' ', '%7E'=>'~')); }
function SendTwitterRequest($RequestURL, $Params=Array())
   //Compile the OAuth parameters
   global $ConsumerKey, $ConsumerSecret, $AccessToken, $AccessTokenSecret;
      Array('oauth_version'=>'1.0', 'oauth_nonce'=>mt_rand(), 'oauth_timestamp'=>time(), 'oauth_consumer_key'=>$ConsumerKey, 'oauth_signature_method'=>'HMAC-SHA1'),
      isset($AccessToken) ? Array('oauth_token'=>$AccessToken) : Array()
   uksort($Params, 'strcmp'); //Must be sorted to determine the signature
   foreach($Params as $Key => &$Val) //Create the url encoded parameter list
   $Params=implode('&', $Params); //Combine the parameter list
   $Params.='&oauth_signature='.EncodeParam(base64_encode(hash_hmac('sha1', 'GET&'.EncodeParam($RequestURL).'&'.EncodeParam($Params), EncodeParam($ConsumerSecret).'&'.EncodeParam($AccessTokenSecret), TRUE)));

   //Do the OAuth request
      curl_setopt($CurlObj, $Key, $CurlVal);
   return $Result;

If you don’t have an AccessToken and AccessSecret yet, you can get them through the following code:

parse_str($OAuthResult, $OauthRet);
   throw new Exception("OAuth error: $OAuthResult");

Here is an example to pull the last 4 tweets from a user:

$Result=json_decode(SendTwitterRequest('https://api.twitter.com/1.1/statuses/user_timeline.json', Array('screen_name'=>$UserName, 'count'=>4)));
   throw new Exception($Result->{'errors'}[0]->{'message'});
foreach($Result as $Tweet)

print implode('
', $Tweets);