Simplest PHP example for retrieving user_timeline with Twitter API version 1.1

Simplest PHP example for retrieving user_timeline with Twitter API version 1.1

Important Note: As of mid-2018, the process to get twitter API tokens became a lot more bureaucratic. It has taken me over one working week to be provided a set of API tokens, and this is for an open source project for you guys and girls with over 1.2 million installations on Packagist and 1.6k stars on Github, which theoretically should be higher priority.

If you are tasked with working with the twitter API for your work, you must take this potentially extremely long wait-time into account. Also consider other social media avenues like Facebook or Instagram and provide these options, as the process for retrieving their tokens is instant.


So you want to use the Twitter v1.1 API?

Note: the files for these are on GitHub.

Version 1.0 will soon be deprecated and unauthorised requests wont be allowed. So, heres a post to help you do just that, along with a PHP class to make your life easier.

1. Create a developer account: Set yourself up a developer account on Twitter

You need to visit the official Twitter developer site and register for a developer account.
This is a free and necessary step to make requests for the v1.1 API.

2. Create an application: Create an application on the Twitter developer site

What? You thought you could make unauthenticated requests? Not with Twitters v1.1 API.
You need to visit http://dev.twitter.com/apps and click the Create Application button.

Enter

On this page, fill in whatever details you want. For me, it didnt matter, because I just wanted to make a load of block requests to get rid of spam followers. The point is you are going to get yourself a set of unique keys to use for your application.

So, the point of creating an application is to give yourself (and Twitter) a set of keys. These are:

  • The consumer key
  • The consumer secret
  • The access token
  • The access token secret

Theres a little bit of information here on what these tokens for.

3. Create access tokens: Youll need these to make successful requests

OAuth requests a few tokens. So you need to have them generated for you.

Enter

Click create my access token at the bottom. Then once you scroll to the bottom again, youll have some newly generated keys. You need to grab the four previously labelled keys from this page for your API calls, so make a note of them somewhere.

4. Change access level: You dont want read-only, do you?

If you want to make any decent use of this API, youll need to change your settings to Read & Write if youre doing anything other than standard data retrieval using GET requests.

Enter

Choose the Settings tab near the top of the page.

Enter

Give your application read / write access, and hit Update at the bottom.

You can read more about the applications permission model that Twitter uses here.


5. Write code to access the API: Ive done most of it for you

I combined the code above, with some modifications and changes, into a PHP class so its really simple to make the requests you require.

This uses OAuth and the Twitter v1.1 API, and the class Ive created which you can find below.

require_once(TwitterAPIExchange.php);

/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
    oauth_access_token => YOUR_OAUTH_ACCESS_TOKEN,
    oauth_access_token_secret => YOUR_OAUTH_ACCESS_TOKEN_SECRET,
    consumer_key => YOUR_CONSUMER_KEY,
    consumer_secret => YOUR_CONSUMER_SECRET
);

Make sure you put the keys you got from your application above in their respective spaces.

Next you need to choose a URL you want to make a request to. Twitter has their API documentation to help you choose which URL and also the request type (POST or GET).

/** URL for REST request, see: https://dev.twitter.com/docs/api/1.1/ **/
$url = https://api.twitter.com/1.1/blocks/create.json;
$requestMethod = POST;

In the documentation, each URL states what you can pass to it. If were using the blocks URL like the one above, I can pass the following POST parameters:

/** POST fields required by the URL above. See relevant docs as above **/
$postfields = array(
    screen_name => usernameToBlock, 
    skip_status => 1
);

Now that youve set up what you want to do with the API, its time to make the actual request.

/** Perform the request and echo the response **/
$twitter = new TwitterAPIExchange($settings);
echo $twitter->buildOauth($url, $requestMethod)
             ->setPostfields($postfields)
             ->performRequest();

And for a POST request, thats it!

For a GET request, its a little different. Heres an example:

/** Note: Set the GET field BEFORE calling buildOauth(); **/
$url = https://api.twitter.com/1.1/followers/ids.json;
$getfield = ?username=J7mbo;
$requestMethod = GET;
$twitter = new TwitterAPIExchange($settings);
echo $twitter->setGetfield($getfield)
             ->buildOauth($url, $requestMethod)
             ->performRequest();     

Final code example: For a simple GET request for a list of my followers.

$url = https://api.twitter.com/1.1/followers/list.json;
$getfield = ?username=J7mbo&skip_status=1;
$requestMethod = GET;
$twitter = new TwitterAPIExchange($settings);
echo $twitter->setGetfield($getfield)
             ->buildOauth($url, $requestMethod)
             ->performRequest();  

Ive put these files on GitHub with credit to @lackovic10 and @rivers! I hope someone finds it useful; I know I did (I used it for bulk blocking in a loop).

Also, for those on Windows who are having problems with SSL certificates, look at this post. This library uses cURL under the hood so you need to make sure you have your cURL certs set up probably. Google is also your friend.

Go to dev.twitter.com and create an application. This will provide you with the credentials you need. Here is an implementation Ive recently written with PHP and cURL.

<?php
    function buildBaseString($baseURI, $method, $params) {
        $r = array();
        ksort($params);
        foreach($params as $key=>$value){
            $r[] = $key= . rawurlencode($value);
        }
        return $method.& . rawurlencode($baseURI) . & . rawurlencode(implode(&, $r));
    }

    function buildAuthorizationHeader($oauth) {
        $r = Authorization: OAuth ;
        $values = array();
        foreach($oauth as $key=>$value)
            $values[] = $key= . rawurlencode($value) . ;
        $r .= implode(, , $values);
        return $r;
    }

    $url = https://api.twitter.com/1.1/statuses/user_timeline.json;

    $oauth_access_token = YOURVALUE;
    $oauth_access_token_secret = YOURVALUE;
    $consumer_key = YOURVALUE;
    $consumer_secret = YOURVALUE;

    $oauth = array( oauth_consumer_key => $consumer_key,
                    oauth_nonce => time(),
                    oauth_signature_method => HMAC-SHA1,
                    oauth_token => $oauth_access_token,
                    oauth_timestamp => time(),
                    oauth_version => 1.0);

    $base_info = buildBaseString($url, GET, $oauth);
    $composite_key = rawurlencode($consumer_secret) . & . rawurlencode($oauth_access_token_secret);
    $oauth_signature = base64_encode(hash_hmac(sha1, $base_info, $composite_key, true));
    $oauth[oauth_signature] = $oauth_signature;

    // Make requests
    $header = array(buildAuthorizationHeader($oauth), Expect:);
    $options = array( CURLOPT_HTTPHEADER => $header,
                      //CURLOPT_POSTFIELDS => $postfields,
                      CURLOPT_HEADER => false,
                      CURLOPT_URL => $url,
                      CURLOPT_RETURNTRANSFER => true,
                      CURLOPT_SSL_VERIFYPEER => false);

    $feed = curl_init();
    curl_setopt_array($feed, $options);
    $json = curl_exec($feed);
    curl_close($feed);

    $twitter_data = json_decode($json);

//print it out
print_r ($twitter_data);

?>

This can be run from the command line:

$ php <name of PHP script>.php

Simplest PHP example for retrieving user_timeline with Twitter API version 1.1

The code pasted by Rivers is great. Thanks a lot! Im new here and cant comment, Id just want to answer to the question from javiervd (How would you set the screen_name and count with this approach?), as Ive lost a lot of time to figure it out.

You need to add the parameters both to the URL and to the signature creating process.
Creating a signature is the article that helped me. Here is my code:

$oauth = array(
           screen_name => DwightHoward,
           count => 2,
           oauth_consumer_key => $consumer_key,
           oauth_nonce => time(),
           oauth_signature_method => HMAC-SHA1,
           oauth_token => $oauth_access_token,
           oauth_timestamp => time(),
           oauth_version => 1.0
         );

$options = array(
             CURLOPT_HTTPHEADER => $header,
             //CURLOPT_POSTFIELDS => $postfields,
             CURLOPT_HEADER => false,
             CURLOPT_URL => $url . ?screen_name=DwightHoward&count=2,
             CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false
           );

Leave a Reply

Your email address will not be published.