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.


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

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


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.


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)); 
            <?php  foreach ($tweets as $key => $tweet): ?>

            $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="\2&src=hash">#\2</a>', $tweet);
            $tweet = preg_replace('/[@]+([A-Za-z0-9-_]+)/', '<a target="_blank" href="$1" target="_blank">@$1</a>', $tweet );
                    echo $tweet;

            <?php endforeach ?>

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

Sip: a color picker refreshingly simple indeed

Sip: a color picker refreshingly simple indeed

July 10th, 2014

I've just discovered Sip, a color picker app for Mac users. "Just discovered" since it's been around[...]

Perch – the CMS that does not pollute your web design workflow

Perch - the CMS that does not pollute your web design workflow

July 7th, 2014

I have recently finished a project based on Perch, the clever 'little' CMS created by edgeofmyseat.c[...]

Responsive video code snippet

Responsive video code snippet

June 29th, 2014

More of a reminder than a pure detailed blogpost, this code snippet will be my go-to resource when I[...]

Project Naphta: a nifty extension to play with text embedded in images

Project Naphta: a nifty extension to play with text embedded in images

June 9th, 2014

We've all been there. You want to select a good chunk of text on a website, only to realise you can'[...]

Free photos for your web design projects

Free photos for your web design projects

June 4th, 2014

Nothing beats using a real professional photographer when working on a cool project. You can be the[...]


  1. kevin says:

    Thanks for the post, that solved my problem. I was trying with Andrew Biggart’s solution ( 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);


  2. 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!!!


  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. Awesome! Got it working…thank you!!! =)

  5. 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:

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

  7. 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.


  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:


    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 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.


    • 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 –

    And i’ve dumped my code here (just in case im doing something stupid) –

    Thanks again for your help, much appreciated!


  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>
    $tweet = ereg_replace("[[:alpha:]]+://[^
    <a href="\" rel="nofollow">
    ",  $tweet->
    $tweet = preg_replace('/(^|\s)#(\w*[a-zA-Z_]+\w*)/', '\1
    <a href="\2&src=hash" rel="nofollow">
    ', $tweet);
    $tweet = preg_replace('/[@]+([A-Za-z0-9-_]+)/', '
    <a href="$1" rel="nofollow">
    ', $tweet );
    echo $tweet;    
    			  <!-- end loop -->

    Thanks again for your help!

  16. Fergus says:

    Thanks for this, really useful.
    Does anyone know a way to display the time / date of each tweet please?

  17. Dhaya says:

    Hi Friends,

    Is there any possible display the latest tweets using screen name or username using in this code….?