by Flo Preynat

If you do read my blog, you would have noticed a post on the retirement of Twitter API v1, the launch of v1.1, and the subsequent [new] way of retrieveing the latest tweets of a given user.

This post was all about getting a twitter user timeline without having to dig deep into authentication. Today, I’m going to show you how to do the same thing with authentication.

What is OAuth?

Twitter uses OAuth to provide authorized access to its API, giving its users a secure way to connect their Twitter accounts with 3rd party apps without having to share their passwords, and providing them in the same time with a wide range of libraries.

Twitter Application

In order to get started, let’s first connect our twitter account to the Twitter Developers interface and create a new application.
Give it a name, a description, fill in your website url, leave the callback url blank, tick the terms and conditions checkbox, fill in the captcha, and create your app.

Twitter Application

Once created, request your access tokens by clicking on the blue button at the bottom. This is basically all you need to access the API with authentication. And if you do take a look at the details of the app, you’ll understand you’ll be needing all four tokens present on the page (ie the consumer key, the consumer secret, the access token, and the access token secret).

TwitterOAuth PHP Library

Now, you’ll need a php library to work with Twitter’s OAuth API. If you google twitteroauth, you’ll find quite a few of libraries to use. The one we are going to use here is Abraham’s.

Download all files, and copy the twitteroauth folder into your project folder, as you won’t be needing the rest of the files.

Connection

Start with a blank html5-ready index.php file such as the following one:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

    </head>
    <body>
    </body>
</html>

In the body, start coding your php. We are going to require twitteroauth.php (and its mate OAuth.php) we have just donwloaded. Note that you don’t need to call both of them, twitterouath.php is enough.

require_once("twitteroauth/twitteroauth.php");

Create a few variables to hold you app’s consumer key, consumer secret, access token, and access token secret. Create as many parameter variables as you wish. To give you a head start, we are going to use GET statuses/user_timeline and all parameters are listed in there.

For our example, I created a couple of variables sunch as $nb_of_tweets (which is going to do – well – exactly what it says on the tin), and an $include_rts to include or exclude the RTs from your timeline.

$consumer_key = 'xxxxxxxxxxxxxxxxxxxxxx';  
$consumer_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$access_token = 'xxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$access_token_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$nb_of_tweets = 5;
$include_rts = false;

Note that RTs can be excluded with a ‘false’ value, but they will still count toward both the maximal length of the timeline and the slice selected by the count parameter. So it says on the user_timeline spec page.

Connect to the API using the get(‘statuses/user_timeline’) command, and run a loop to display your tweets in an unordered list.
Kudos to Kevin who commented below and added his two cents to helps us improve hyperlink display.

And a shit lot more kudos to him again as he also fixed our @mentions and #hashtags links, as I kindly asked him to. [Brilliant mate!]

Full code looks a lot like:

    <?php require_once("twitteroauth/twitteroauth.php");
        $consumer_key = 'xxxxxxxxxxxxxxxxxxxxxx';                               // Put your consumer key here
        $consumer_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';         // Put your consumer secret here
        $access_token = 'xxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';   // Put your access token here
        $access_token_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';   // Put your access token secret here
        $nb_of_tweets = 5;                                                      // Nb of tweets to be displayed
        $include_rts = false;                                                   // true to include RT's or false to exclude them
                     
        $connection = new TwitterOAuth($consumer_key,$consumer_secret,$access_token,$access_token_secret);
                     
        $tweets = $connection->get('statuses/user_timeline', array('count' => $nb_of_tweets, 'include_rts' => $include_rts)); 
                ?>
        <ul>
            <?php  foreach ($tweets as $key => $tweet): ?>
                <li><?php 

                    //links
            $tweet = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]","<a target='_blank' href=\"\\0\">\\0</a>",  $tweet->text); 
            //#
            $tweet = preg_replace('/(^|\s)#(\w*[a-zA-Z_]+\w*)/', '\1<a target="_blank" href="https://twitter.com/search?q=%23\2&src=hash">#\2</a>', $tweet);
            //@
            $tweet = preg_replace('/[@]+([A-Za-z0-9-_]+)/', '<a target="_blank" href="http://twitter.com/$1" target="_blank">@$1</a>', $tweet );
                    
                    echo $tweet;

                ?></li>
            <?php endforeach ?>
        </ul>

Refresh your page, you should be getting your latest tweets listed nicely in an unordered list.

Twitter Timeline

Note that GET statuses/user_timeline has got limitations. For example, the maximum number of requests allotted per user is currently set to 180 per 15 minute window. Therefore, if you do get a lot of trafic on your site, it would be wise to optimize all this by setting some kind of cache and avoid reaching the 180 request limit.

For people testing this out, make sure you run your test in a local environment (using MAMP, or xampp for windows users).

Last, but not least, I added a Github repo so you can have a go at this API in no time. You just need to replace the tokens by your owns.

So long.

My name is Flo Preynat and I am the freelance webdesigner and developer behind shoogle designs. I live in France and specialize in responsive web design. Give me a shoogle or get in touch with me on twitter.

Most Recent Posts

Special Recent Posts

Make Google Charts responsive

Make Google Charts responsive

March 19th, 2014

A quick blog post on how to make Google Charts play nicely in responsive mode. Nothing close to rock[...]

Codekit 2 : even more steroids for us web developers

Codekit 2 : even more steroids for us web developers

March 17th, 2014

I was on holiday when Bryan released the new version of Codekit and never had the chance to to check[...]

Open terminal from folder in finder

Open terminal from folder in finder

January 27th, 2014

A quick one nudged my way by Adrien Joly this morning. You can now open a terminal window from a [...]

A look back at Wordcamp Paris 2014

A look back at Wordcamp Paris 2014

January 22nd, 2014

I went to Wordcamp Paris last week. The event was held On Friday 17th January at MAS Paris and Satur[...]

Gruntjs Boilerplate: my dummy-proof step-by-step guide

Gruntjs Boilerplate: my dummy-proof step-by-step guide

January 14th, 2014

Right so I've made the leap. After quite a ride, and some cool adventures with Codekit, I've deci[...]

Comments

  1. kevin says:

    Thanks for the post, that solved my problem. I was trying with Andrew Biggart’s solution (https://github.com/andrewbiggart/latest-tweets-php-o-auth) but with not luck.

    Small tip, i did a small change within the foreach to get the links back as html tags:
    echo ereg_replace(“[[:alpha:]]+://[^[:space:]]+[[:alnum:]/]”,”\“, $tweet->text);

    Cheers.

  2. John Wooten says:

    How can add support for links? The tweets are showing up, however links are showing up as plain text and not clickable links.

    Thanks so much!!!

    -John

  3. SEBAS says:

    Thanks Flo, this is awesome!

    Is there any chance of linking hash tags and @mentions as well? Any tips would be much welcome.

  4. John Wooten says:

    Awesome! Got it working…thank you!!! =)

  5. Martin Oxby says:

    Looks like this will do just the trick. I came over from CSS Tricks, so thanks for the useful blog comment over there :)

    Just waiting for a client’s Twitter login to be able to implement this, but seems spot on – thanks!

  6. kevin says:

    Sorry about the mess in my previous comment, here’s a pastebin: http://pastebin.com/TZ9rXnDX

    Btw, can we use ‹pre› or ‹code› tags here?

  7. Martin Oxby says:

    No bother – I managed to stop it from running into the sea on its arrival at Inverness!

    Just implemented this onto their in-development website and it’s all good, working absolutely fine – just simple logical steps and running well.

    Thanks!

  8. Jamie says:

    I spent two days and went over at least ten tutorials on how to get twitter posts into my site. Yours is the first to pull it off for me. The tutorial was almost perfect. You just left out what to do with the last bit of code to get the tweets into your page. It’s working for me and now that the itch has been scratched, I can go enjoy the start of my weekend. Thanks!

  9. R.J. says:

    I am getting a warning that ereg is deprecated…

    Is there a fix? I changed it to preg_replace but then the + sign is giving me an issue.

    Any ideas?

  10. Ashleigh says:

    Thank you so much! I have been trying to figure out how to get this up, your tutorial has been the most successful! Now on to the css part :D

  11. Taoufik says:

    Hi Flo,

    I got the php working in less than 2 minutes, however i have issues calling it from my html (i have html main page and not php)

    any help to call php output from my html will be appreciated,

    Thank you

  12. Rob says:

    Hi,

    Great tutorial, is there any simple way to pull profile images and embedded images (from the tweet) into the timeline?

    I’ve checked my requests with https://apigee.com and it’s returning values for profile_image_url and profile_image_url_https but i cant figure out how to echo them into the page?

    Thanks in advance.

    Rob

    • Hi Rob,
      you could use:

      $content = $connection -> get('account/verify_credentials');
      $img = $content -> profile_image_url_https;
      

      and then echo it:

      <img src ="<?php echo $img ;?>" />
      

      Can you check whether it works?

  13. Rob says:

    Hello mate, thanks for the quick response….

    The code seems to pull in my twitter image rather than the image of the user tweeting…

    The example is here – http://testing.ftistaging.com/twitter/new/

    And i’ve dumped my code here (just in case im doing something stupid) – http://pastebin.com/1VvnGWaR

    Thanks again for your help, much appreciated!

    Rob

  14. Rob says:

    I’m using the ‘statuses/home_timeline’ instead of the ‘statuses/user_timeline’ which should pull the timeline that i see when i log into twitter (and it works!)… just very odd i cant seem to pull the URL from the request… even tho i can see it’s there… very frustrating!

    Thanks for your help either way… I think im getting somewhere… slowly! lol

  15. Rob says:

    Hello mate, small update – I figured out how to do it!… Here’s the code to display your own home timeline with user pic, name and @name should anyone else need it….

    $connection = new TwitterOAuth($consumer_key,$consumer_secret,$access_token,$access_token_secret); 
    
    $tweets = $connection->get('statuses/home_timeline', array('count' => $nb_of_tweets, 'include_rts' => $include_rts, 'include_entites' => $include_entities)); 
    
    ?>
         
    <!-- run loop --> $tweet): ?>  
    <!-- print profile image --> <img src ="user->profile_image_url_https; ?>" />
    <!-- print user name --> user->name; ?>
    <!-- print @name --> <a href="user->screen_name; ?>">(@user->screen_name; ?>)</a>
    
    <?php 
    
    //links
    $tweet = ereg_replace("[[:alpha:]]+://[^
    
    [:space:]]+[[:alnum:]/]","
    <a href="\" rel="nofollow">
    \
    </a>
    ",  $tweet->
    text); 
    //#
    $tweet = preg_replace('/(^|\s)#(\w*[a-zA-Z_]+\w*)/', '\1
    <a href="https://twitter.com/search?q=%23\2&src=hash" rel="nofollow">
    #\2
    </a>
    ', $tweet);
    //@
    $tweet = preg_replace('/[@]+([A-Za-z0-9-_]+)/', '
    <a href="http://twitter.com/$1&quot; rel="nofollow">
    @$1
    </a>
    ', $tweet );
    
    echo $tweet;    
    ?>
    			  <!-- end loop -->
    

    Thanks again for your help!