There are a lot of classes out there but after trying several none of them seem to work because of these updates at Twitter, plus some of them are pretty advanced classes with a lot of functionality that I don't really need.

What is the simplest/shortest way to get the recent user statuses with PHP?

@Mark Thanks Mark!! That was easy!! That didn't work for me initially. I'm running WAMP. I had to make a change to my php.ini in my Apache directory according to this thread: stackoverflow.com/questions/5444249/…
– Adlin LingJul 5 '14 at 7:49

14 Answers
14

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.

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 Twitter's v1.1 API.
You need to visit http://dev.twitter.com/apps and click the "Create Application" button.

On this page, fill in whatever details you want. For me, it didn't 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:

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

Click "create my access token" at the bottom. Then once you scroll to the bottom again, you'll 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 don't want read-only, do you?

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

I've 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.

@kaffolder The link on that page:profilepicture.co.uk/caching-api-responses-php suggests a simple way of doing it. You write your twitter data to a file, or database (MySQL or MongoDB) on first request, then every subsequent request you check current time against the time limit you want for the file (you could name the file as the time limit), and if the file exists and file name is within the time limit you want, then pull the data instead of performing the API request. If file exists but the time limit is passed, delete the file then perform the API request.
– JimboApr 8 '13 at 8:12

7

I can't figure out how to handle the json data once returned. I don't want to just echo it to the screen as in echo $twitter ->setGetfield($getfield) ->buildOauth($url, $requestMethod) ->performRequest(); APOLOGIES, I can't figure out how to do newlines! I want to do something like $jsonData = json_decode($twitter); but it doesn't work - I feel like i'm missing something fundamental but the penny isn't droppping...
– AshleyJun 17 '13 at 12:04

There are quite a few prerequisites to get this class working on Windows. You need to have a working version of cURL loaded in your php.ini file and also need to load the CA certs in your php.ini file using curl.cainfo = path\to\cacert.pem. You can get the CA certs here.
– Mark WJul 24 '13 at 15:21

4

@Jimbo I was just noting that some of the default cURL extensions are buggy in Windows and require replacement (hence the link to the "fixed" versions) and that without loading the CA certs, your class returns a false, as the curl_error () reports that ` SSL certificate problem, verify that the CA cert is OK`. This can be avoided by turning off CURLOPT_SSL_VERIFYPEER, but I thought I would include the basic instructions to actually using the CA certs. Just included this to potentially save some people a few minutes of searching.
– Mark WJul 24 '13 at 15:33

Thanks for the code snippet, work flawlessly. Only problem is I can't seem to figure out how to set the post count return. It only return 20 and I want to full amount which is 200 as per twitter limit.
– jskrwykNov 7 '12 at 9:44

23

How would you set the screen_name and count with this approach? I tried adding it to the $url variable but I got a "Could not authenticate you" error.
– Javier VillanuevaDec 13 '12 at 15:27

This post has been very helpful. My code doesn't seem to return from curl_init() though. I've looked at some examples and they look very simple and straightforward and exactly like this code here... Do I need to install something special?
– jessicaraygunOct 5 '13 at 6:04

1

It worked for me 26 Oct 2016. The output was a bit more complex than I expected.
– johncOct 26 '16 at 16:35

The code pasted by Rivers is great. Thanks a lot! I'm new here and can't comment, I'd just want to answer to the question from javiervd (How would you set the screen_name and count with this approach?), as I've 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:

I can't up vote this enough. On Twitter's API documentation, this stares you in the face, but it's never super 'obvious'. Does this approach mess with the buildAuthorizationHeader function? I implemented it separately.
– MoeDec 30 '13 at 12:52

I haven't worked with this for a long time so I don't remember, if you haven't solved your issue yet, I can look into it in the following days.
– lackovic10Jan 6 '14 at 14:27

I've been trying to adapt your solution to perform the POST on statuses/update.json without luck, do you have any idea how this could be achieved?
– perrohunterApr 29 '14 at 21:52

1

@perrohunter i have no idea would have to look more into this. If you don't find a way in a couple of days send me a msg i'll try to help you out.
– lackovic10Apr 29 '14 at 22:33

Like stated in other answers, create a Twitter app to get the token, key and secret.
Using the code bellow, you can modify request parameters from one spot and avoid typos and similar errors (change $request array in returnTweet() function).

Awesome job @budidino! Created the application on dev.twitter.com/apps and filled your x's with the oauth_access_token, oauth_access_token_secret, consumer_key, consumer_secret. * note * that you need to press "create my access token" and it takes a few seconds to be generated so please wait for it.
– TheoNov 24 '13 at 20:37

@budidino dnt we need to include any library??
– anamJan 24 '14 at 6:33

I filled out the keys, added this to my functions.php file in WordPress, put <?php echo returnTweet(); ?> in an HTML file, and it outputs the word "Array" and nothing else.
– J82Mar 20 '14 at 21:38

If you want to fetch just the latest tweet you should modify the $request array and set count to 1. Let's say that you use $tweet = returnTweet(); then if you want to display the latest tweet (in this case the only one), you could write something like this: echo "latest tweet:" .$tweet[0]["text"]; Be sure to check out the structure of twitter's returned if you want to pull out more than just the text of the tweet (example $userProfileImageURL = $tweet[0]["user"]["profile_image_url"]). dev.twitter.com/docs/api/1.1/get/statuses/user_timeline
– budidinoMar 21 '14 at 8:56

thanks a lot, your code improvement works well! One question re: "// a stronger nonce is recommended". What could that be? time()?
– SebastianJul 22 '13 at 21:09

Thanks for pointing that out. Sebastian: a nonce is a single-use token that should be cryptographically secure. mt_rand() is both too short (32 bits) and not a cryptographic PRNG. In theory, this makes the oauth token weak, but for the sake of simplicity in my original example code, I wanted to use something that was to-hand in PHP and readily comprehensible.
– Kris ReevesJun 16 '15 at 21:49

This question helped me a lot but didn't get me all the way in understanding what needs to happen. This blog post did an amazing job of walking me through it.

Here are the important bits all in one place:

As pointed out above, you MUST sign your 1.1 API requests. If you are doing something like getting public statuses, you'll want an application key rather than a user key. The full link to the page you want is: https://dev.twitter.com/apps

You must hash ALL the parameters, both the oauth ones AND the get parameters (or POST parameters) together.

You must SORT the parameters before reducing them to the url encoded form that gets hashed.

You must encode some things multiple times - for example, you create a query string from the parameters' url-encoded values, and then you url encode THAT and concatenate with the method type and the url.

I sympathize with all the headaches, so here's some code to wrap it all up:

Please, for us stupid folks, explain. You're giving as much insight, if not less, than the documentation. Do you use PHP's HttpRequest() function for step 2? There is Abraham's TwitterOAuth PHP - github.com/abraham/twitteroauth - library that is supposed to do this as well, but an example of how to implement it isn't really provided.
– RCNeilOct 16 '12 at 19:40

Sorry, I'll add a code example when I get a chance.
– Matthew RapatiOct 16 '12 at 21:00

This one uses anonymous functions and file_get_contents instead of the cURL library. Note the use of an MD5 hashed nonce. Everyone seems to be going along with the time() nonce, however, most examples on the web concerning OAuth use some kind of encrypted string (like this one: http://www.sitepoint.com/understanding-oauth-1/). This makes more sense to me too.

Further note: you need PHP 5.3+ for the anonymous functions (in case your server/computer is in some cold war cave and you can't upgrade it).

Thanks to this thread, and especially budidino because his code is what drove it home for me.
Just wanted to contribute how to retrieve the JSON data from a request.
Make changes to "//create request" request array part of the code to perform different requests. Ultimately, this will output the JSON onto the browser screen

If it is useful for anyone...
In my blog I've implement the following PHP code in order to retrieve the last tweets, extract their most relevant data and then saved them into a MySQL database.
It works because I got it in my blog.

'It works because I got it in my blog' is one of my favourites. Your post doesn't answer the actual question. Also php code you are using have bad quality. Read a bit here phptherightway.com . Especially about DB
– Maciej PaprockiSep 15 '16 at 14:28

Also you have made all your keys and tokens public so don't be surprised if somebody takes it and hacks your twitter account!
– garrettlynchJun 24 at 13:12

Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).