Simplest PHP example for retrieving user_timeline with Twitter API version 1.1
Asked Answered
R

14

304

Because of the Twitter API 1.0 retirement as of June 11th 2013, the script below does not work anymore.

// Create curl resource 
$ch = curl_init(); 
// Set url 
curl_setopt($ch, CURLOPT_URL, "http://twitter.com/statuses/user_timeline/myscreenname.json?count=10"); 
// Return the transfer as a string 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
// $output contains the output string 
$output = curl_exec($ch); 
// Close curl resource to free up system resources 
curl_close($ch);

if ($output) 
{
    $tweets = json_decode($output,true);

    foreach ($tweets as $tweet)
    {
        print_r($tweet);
    }
}

How can I get the user_timeline (recent statuses) with the least code possible?

I found this: https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline but I get the following error:

"{"errors":[{"message":"Could not authenticate you","code":32}]}"

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?

Reynaud answered 16/10, 2012 at 14:8 Comment(7)
I would KILL for the answer to this. Their documentation is horrifically bad.Auction
I'm new to the Twitter API and struggling a bit with it. I found myself using deprecated code.Scottie
Have a look at aamirafridi.com/twitter/…Birthwort
@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: #5444749Integration
i sthis still working on nov?2014 i think there changing their APIs?Subtemperate
I just wrote down solution with no CURL or any other extra libraries: #17050321Kamerun
@RauliRajande - your snippet is EXACTLY what I was looking for - DIY from scratch. The accepted answer by Jimbo is pretty awesome too, after I updated my certs. Thanks to both.Nissy
S
837

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

Enter image description here

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:

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

There's a little bit of information here on what these tokens for.

3. Create access tokens: You'll need these to make successful requests

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

Enter image description here

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.

Enter image description here

Choose the "Settings" tab near the top of the page.

Enter image description here

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: I've done most of it for you

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

This uses OAuth and the Twitter v1.1 API, and the class I've 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 we're 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 you've set up what you want to do with the API, it's 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, that's it!

For a GET request, it's a little different. Here's 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();  

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.

Shameful answered 9/3, 2013 at 19:2 Comment(65)
How might you go about caching this locally? Caching would be a good addition as Twitter limits the number of requests. I'm newer to PHP so any help would be much appreciated! I came across this link, but cannot figure out how to implement it.Gravy
@Gravy 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.Shameful
@Gravy In any case, write out what you want to do in comments step by step, then code to your comments. So... (1) Check if text file exists. (2) If exists, get filename (the timestamp) (3) If the current time is greater than the timestamp, perform the request because it's past the cache time, and put the new data in the file, renaming it to the new time limit. (3) If text file doesnt exist, create it with current timestamp, then perform the API request. Something along those lines, pretty simple really.Shameful
I added a comment in another thread, but I just wanted to say a huge thank you for this. Finally I can access the API without authentication problems! Thanks so much!Dimarco
@jimbo - I know this is out of scope, but since you have been so amazingly helpful, can you point me in the right direction of finding out how I can modify this to work for other uses who give permission for the app?Dimarco
@Dimarco Not sure what you mean? You're making an app that requires users to give their permission to, say, post a tweet for them, for example? If so, looks like you need to implement a sign-in with twitter.Shameful
@jimbo - I think that is what I mean, yes. Do you know of any good tutorials? Ideally I'd like to provide a service that when someone gives permission for my app it would work on a schedule (for example scan their recent DMs for spam and delete them). Would this work?Dimarco
@Dimarco Yes, that seems about right. Unfortunately I can't point you toward any tutorials, however this underlying class is what you need to perform any sort of request to the 1.1 API, so you just need to figure out what you need to actually request. It's worth a google.Shameful
@Shameful - thanks, that is good to know. One step at a time- I have worked this out with your help. I'll leave the log in thing for another time! Thanks again.Dimarco
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...Strawboard
@Strawboard Do a json_decode() on it, then you can loop it with foreach() ;)Shameful
Hi @Jimbo, I am doing $twitter = new TwitterAPIExchange($settings); $twitter ->setGetfield($getfield) ->buildOauth($url, $requestMethod) ->performRequest(); $jsonData = json_decode($twitter); print_r($jsonData);Strawboard
@Strawboard No no, you don't decode the twitter object lol. See my example at the bottom of my post. Instead of the echo, do a $json =. Then var_dump(json_decode($json)); - for a few more examples, see this linkShameful
Great!! Sorry for the newbie question, i'm still very new to Objects. Thanks so much for the code and the help! :)Strawboard
Hi, @Jimbo. Just curious - here's my code. $twitter = new TwitterAPIExchange($settings); $response = $twitter->setGetfield($getfield) ->buildOauth($url, $requestMethod) ->performRequest(); var_dump(json_decode($response));?> It's dumping the timeline out with ALL the junk, but I'm wanting to iterate over it, and maybe style with CSS. Would I assign the var_dump to a variable? And how would I cycle through the tweets and access JUST the text?Penstock
@Penstock Yes, you'd assign this to, say, $posts and then iterate over it using a foreach(), extracting only the data you want.Shameful
Thank you, Twitter's documentation is a disorganized mess, this helped greatly.Benetta
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.Crabby
Thanks @MarkW - Yep, libcurl is a requirement. Have considered using Artax, but really, if you're a dev and can't get libcurl working, you won't have much luck with this :)Shameful
@Shameful 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.Crabby
@MarkW The class returns false? What about the check I put at the top looking for the libcurl extension to exist? That isn't hit?Shameful
@Shameful What you are referencing is in the constructor. I am talking about the line $json = curl_exec($feed); in the method performRequest that assigns the value "false" to $json in the event that the SSL certificate issue appears. Using curl_error ( $feed ), you can see that an issue may occur if you don't have the latest CA certs loaded in the php.ini file. I was just pointing this out in case anyone found that instead of a JSON object, he/she was getting returned just a Boolean.Crabby
+1 MarkW, this worked for me. I disabled SSL_VERIFY. $options = array( ... , CURLOPT_SSL_VERIFYPEER => false );Latashalatashia
CURLOPT_SSL_VERIFYPEER was removed completely from the code to prevent MitM attacks a while back :)Shameful
@MarkW - Using Xampp on Windows Curl was enabled but required the CA Certs. Simply saved link and hooked it up in php.ini: curl.cainfo = "C:\xampp\php\curl\cacert.pem"; Thanks for the infoCuyler
Ok @Jimbo, I understand what you are saying about looping through the data, but just give one working piece of code in a reply to help us. Example how to get the text out of the twitter data...Pavo
@Pavo foreach($data as $key => $value) { var_dump($value->element); // or var_dump($value['element']); } The former -> accesses object values whilst the latter [] accesses array values. var_dump() the data you have, figure out if it's an object or value, then loop through with a foreach and print out the object you want, then just chain them bit by bit until it's working: var_dump($data->element->value) or var_dump($data['element']['value']). This is, really, a fundamental coding question that you should google around for, how to loop arrays or how to loop objects in PHP :)Shameful
Hi, i used the above code but it;s not working.var_dmup showing boolean false.How i resolve this.Sybaris
Thanks Jimbo. A working example with complete code at johnbhartley.com/2013/twitter-feed-with-php-and-json-v1-1Pavo
@Shameful how easy it is to figure out list_id and slug for list api... i have no clue where to look for it... twitter doc is real mess..Loquitur
@Loquitur Have you considered retriving lists via GET lists/list first? These will have the ids you'll need. Got that from a 5 second google search.Shameful
@Shameful thanks.. i was trying a different search which was always leading me to the lists api... i figured out what is"slug" and i can pair it with user_id to make the call. Thanks for the response.Loquitur
@Jimbo: Can you please give clue for how to deal with situation where screen name is not known? Because when user comes on my page I dont know his name, so how to authenticate and get his most recent tweets,screen name?Awestricken
@Programming_crazy The class doesn't currently aim to handle authentication - it's just for getting details via the REST api.Shameful
You are a life saver. Simple solution. Worked for me straight away. p.s you need to update the screenshots (create tokens button for example is in different location on twitter site).Birthwort
Does this library require an update? I carried out all the steps as mentioned and I do not get back anything - var_dump(json_decode($response)) gives me NULL...Welt
@Welt No, that'll be an issue with the certification configuration on your machine. This may help you sort it out. I'm guessing you are on either Windows or Mac.Shameful
I wrote a blog about it. You can have a look aamirafridi.com/twitter/…Birthwort
I am having the same issue as @Welt and I don't think it's a certificate issue, I tested ricardroper's code and it worked perfectly. github.com/ricardoper/TwitterOAuth/blob/master/TwitterOAuth/… NOTE: I am using IISSennit
@Sennit Have you definitely tried adding CURLOPT_SSL_VERIFYPEER => false to the curl options in performRequest() of TwitterAPIExchange.php?Shameful
@Shameful That fixed it! Perhaps you should add that as additional instruction for IIS/Windows users?Sennit
@Sennit You haven't set up cURL properly. With that line you are open to MiTM attacks. It's a certificate issue - you need to sort out your certs according to the curl docs. If you remove the line again and var_dump curl_error, you'll see exactly whats going wrong with your configuration.Shameful
@Shameful does your lib handle calling the request_token endpoint needed for reverse_auth including generating the base signature string?Gunman
@Shameful I have been trying to use your api for getting reverse_auth token from this endpoint: api.twitter.com/oauth/request_token I have set the x_auth_mode = reverse_auth, but i keep getting message "failed to validate oauth signature and token""Gunman
@Gunman Nope, it's literally the base code to make the request - you should take a look at the source code (it's pretty simple tbh) and feel free to fork it to incorporate your own extra functionality :-)Shameful
@Shameful yes I was already tried to do that. But I get 401 Authorization required error, when I print the header, and the error message is - Failed to validate oauth signature and token". Strange as no token is needed to be passed for x_reverse_auth.Gunman
@Shameful ok I got it working. Here is the repo for anyone wanting to use twitter reverse auth.Gunman
@Gunman That's cool, but you didn't actually post the lib! Could you link it?Shameful
@Shameful Crazy I was sure I did post, anyway here it is: github.com/srinivasmangipudi/twitter-api-php Also please let me know if you think it can be improved.Gunman
If you are making a GET request, take note of the comment: Set the GET field BEFORE calling buildOauth(). Otherwise you will keep getting {"errors":[{"message":"Could not authenticate you","code":32}]}Durra
@Shameful To make it work (EasyPHP/Windows) I had to add "CURLOPT_SSL_VERIFYPEER => false" in the CURL options. But when you will update your library, I'll lose my changes every time...Isochroous
@Shameful Thx for your answer! Does that mean that I MUST purchase an SSL certificate?Isochroous
No, it just means you need to go on curl.haxx.se and set up the cert files from there properly.Shameful
Accessing dev.twitter.com/user/login says 'Access denied You are not authorized to access this page.' ?? What the heck ... How to authorize myself? I am logged in .. probably its not developer account. I hate all the docs, still not clear to meBighorn
There is no mention of how to get the oauth_access_token. This is baffing me out :OLymn
@JamieHutber It's actually right below the Consumer Keys box. There's a little tab labeled "Access Tokens" that lets you generate a new access token - that's your OAuth juice right there.Bunche
Does this solution support replying to tweets? I've tried adding the in_reply_to_status_id parameter to the $post_fields array as described here: dev.twitter.com/rest/reference/post/statuses/update but it doesn't work.Bacitracin
@Seano It certainly should do. If you open an issue on GitHub we can look at it together, although I'm sure others would have found the issue and reported it already if it didn't :/Shameful
What about getting all replies to a tweet?Bacitracin
@Seano Check out the twitter API docs - the library should perform all requests as twitter expects them. If it doesn't, feel free to open a Github issue.Shameful
@Shameful Twitter API docs don't help. At the moment there's no simple way to request all replies to a tweet, see twittercommunity.com/t/see-replys-to-a-tweet/6953 and quora.com/… to track the issue. The best way is to search for all mentions using a since_id parameter. Not exhaustive.Bacitracin
@Seano Yep, looks like this is an issue on their side (I checked a non-2011 post and it's still the same).Shameful
Please update this answer with verbiage about 'CURLOPT_SSL_VERIFYPEER' I just had my host fix this nasty issue. I thought I was doing something wrong, as I was getting no output. See also: Stop turning off CURLOPT_SSL_VERIFYPEER and fix your PHP configGeny
This works great, but is there a way to get images if tweets have them?Pubescent
@Pubescent That's a question for the API specifically not this SDK that talks to it - but yes, the tweets will likely have image urls in there.Shameful
S
141

Go to dev.twitter.com and create an application. This will provide you with the credentials you need. Here is an implementation I've 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
Scene answered 17/10, 2012 at 17:26 Comment(22)
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.Adversative
Thanks for this. Frustrating you can no longer get people's twitter feeds without setting up an App though (discounting the widget, as it's inflexible with CSS).Skipton
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.Ellata
This is great! If you don't mind, I'd like to include this as sample PHP code for my jQuery Twitter plugin.Chromatolysis
@zachary-kniebel Any thoughts on implementing caching support into your Github solution? From what I've read, it's a good idea to implement caching into API requests such as this. I'd help ya out, but I'm newer to PHP. I'd love to be able to use your solution, but am really wanting something that will cache locally. Not sure if this link helps or not, but let me know if you have any ideas on how to implement caching into your PHP script.Gravy
@Gravy - To be honest, I don't think caching with PHP in your site's code is what you are looking for. About a week ago, I calculated how many requests for user timelines I could make per rate period (5 min) without blowing the cap. Assuming that I am only querying from one site (i.e., inline page code, like what you are talking about) I could refresh my results for timelines approx. every 15 seconds and be only using about 1/2-2/3 of the max number of requests. The cache should be used for data that doesn't change (or, at least, not often) across pages and users.Chromatolysis
@Gravy - The problem would be that you would need to make sure that you are counting that 15 seconds starting from a specific time (i.e., not the time that the user visited the site). The problem here is that there is no locking system and if two users are visiting at once, they will both see that it is time to update the cache with Twitter data and will both make the request. This will blow your rate limit. What you want to do, instead, is make a web-service or have a separate service/back-end site (one that no one should be visiting) that holds your data in a database or anotherChromatolysis
@Gravy - system, and updates that database/system at the specified interval. You would then have your site's pages query said database/system every 15 seconds (again, starting from a specified time, though I suggest you add a second or two to the start time, just to give the query some wiggle room), either using a AJAX or a request from your PHP code. You can query that system as much as you want, as it will be completely independent from your number of users and your navigable site. If you have any more questions, write a comment on the GitHub page or email me ([email protected])Chromatolysis
The problem with this is that it's so rudimentary that anything above basic requests just fails. Try putting an @ at the beginning to send a tweet, for example. How about hashtags in post fields and geo queries with minus symbols and commas? In my post this is all fixed, and we can work together to make the library simple to use for everyone.Shameful
Is there a way i can specify some attributes for the request, like include_entities=false ?Worcester
This code works great! I'm trying to modify it to use the search/tweets.json api, but I'm always getting the response 'could not authenticate you' - any ideas?Chopper
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?Gametangium
Well you need to have curl installed on your server which comes standard for most PHP hosting platforms. Could you post your source code?Scene
How would an idiot like me call this in an HTML file to display the tweet? Or am I missing something?Ludwigshafen
I'm not understanding your question. You need php to use the implementation above. This can be a php file that prints html or you can call a php file with javascript.Scene
What I don't get is how is everybody getting the bloody $oauth_access_token = "YOURVALUE"; $oauth_access_token_secret = "YOURVALUE"; lol driving me nutsLymn
hmm this doesn't seem to work for me: PHP Notice: Use of undefined constant CURLOPT_HTTPHEADER - assumed 'CURLOPT_HTTPHEADER' in /home/jeff/twitter api/get_tweets.php on line 41 PHP Notice: Use of undefined constant CURLOPT_HEADER - assumed 'CURLOPT_HEADER' in /home/jeff/twitter api/get_tweets.php on line 43 PHP Notice: Use of undefined constant CURLOPT_URL - assumed 'CURLOPT_URL' in /home/jeff/twitter api/get_tweets.php on line 44 PHP Notice: Use of undefined constant CURLOPT_RETURNTRANSFER - assumed 'CURLOPT_RETURNTRANSFER' in /home/jeff/twitter api/get_tweets.php on line 45Again
@Scene this giving me warning message " Warning: rawurlencode() expects parameter 1 to be string, array given " in the return line of buildBaseString().. any solutions.. plsss. am new to all thisKermanshah
Does this code still work after most recent changes in twitter API? It doesn't work for me, but it's quite possible I did something stupid on the way.Pullman
I still use this same implementation. Tweet me @nickthedev for quickest responses.Scene
It worked for me 26 Oct 2016. The output was a bit more complex than I expected.Kehr
It sure does. @jeeScene
A
62

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:

$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
           );
Afrikah answered 22/12, 2012 at 23:18 Comment(4)
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.Parol
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.Afrikah
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?Rutan
@Rutan 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.Afrikah
H
23

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

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;
}

function returnTweet(){
    $oauth_access_token         = "x";
    $oauth_access_token_secret  = "x";
    $consumer_key               = "x";
    $consumer_secret            = "x";

    $twitter_timeline           = "user_timeline";  //  mentions_timeline / user_timeline / home_timeline / retweets_of_me

    //  create request
        $request = array(
            'screen_name'       => 'budidino',
            'count'             => '3'
        );

    $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'
    );

    //  merge request and oauth to one array
        $oauth = array_merge($oauth, $request);

    //  do some magic
        $base_info              = buildBaseString("https://api.twitter.com/1.1/statuses/$twitter_timeline.json", '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 request
        $header = array(buildAuthorizationHeader($oauth), 'Expect:');
        $options = array( CURLOPT_HTTPHEADER => $header,
                          CURLOPT_HEADER => false,
                          CURLOPT_URL => "https://api.twitter.com/1.1/statuses/$twitter_timeline.json?". http_build_query($request),
                          CURLOPT_RETURNTRANSFER => true,
                          CURLOPT_SSL_VERIFYPEER => false);

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

    return json_decode($json, true);
}

and then just call returnTweet()

Haas answered 23/4, 2013 at 12:52 Comment(6)
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.Bark
@budidino dnt we need to include any library??Kuo
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.Ludwigshafen
@Desi, the result is array of tweets, you should handle how you display each of them. try print_r(returnTweet()) just to see what's inside. Check out this example of displaying all of the tweets: gist.github.com/budidino/9681764#file-stackoverflow-returntweetHaas
@budidino I tried print_r(returnTweet()) and a lot of text filled up the screen. Sorry, I'm a beginner with PHP. I just want to display the latest tweet. I checked the github link and tried putting that in the template but the latest tweet didn't display as well. It just outputted Tweet: Array. I'm sure this is basic stuff but can you please let me know what I need to put in my template for just the last tweet to display?Ludwigshafen
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_timelineHaas
K
17

Thank you Kris!

It worked for me without using parameters to the query, whenever I used more than one parameter it showed me the error: 32 Could not authenticate you.

The problem for me, was in the ampersand encoding. So in your code where it's the following line

$url .= "?".http_build_query($query);

I added the following line below:

$url=str_replace("&amp;","&",$url);

And it worked using two or more parameters like screen_name and count.

The whole code looks like this:

$token = 'YOUR TOKEN';
$token_secret = 'TOKEN SECRET';
$consumer_key = 'YOUR KEY';
$consumer_secret = 'KEY SECRET';

$host = 'api.twitter.com';
$method = 'GET';
$path = '/1.1/statuses/user_timeline.json'; // api call path

$query = array( // query parameters
    'screen_name' => 'twitterapi',
    'count' => '2'
);

$oauth = array(
    'oauth_consumer_key' => $consumer_key,
    'oauth_token' => $token,
    'oauth_nonce' => (string)mt_rand(), // a stronger nonce is recommended
    'oauth_timestamp' => time(),
    'oauth_signature_method' => 'HMAC-SHA1',
    'oauth_version' => '1.0'
);

$oauth = array_map("rawurlencode", $oauth); // must be encoded before sorting
$query = array_map("rawurlencode", $query);

$arr = array_merge($oauth, $query); // combine the values THEN sort

asort($arr); // secondary sort (value)
ksort($arr); // primary sort (key)

// http_build_query automatically encodes, but our parameters
// are already encoded, and must be by this point, so we undo
// the encoding step
$querystring = urldecode(http_build_query($arr, '', '&'));

$url = "https://$host$path";

// mash everything together for the text to hash
$base_string = $method."&".rawurlencode($url)."&".rawurlencode($querystring);

// same with the key
$key = rawurlencode($consumer_secret)."&".rawurlencode($token_secret);

// generate the hash
$signature = rawurlencode(base64_encode(hash_hmac('sha1', $base_string, $key, true)));

// this time we're using a normal GET query, and we're only encoding the query params
// (without the oauth params)
$url .= "?".http_build_query($query);
$url=str_replace("&amp;","&",$url); //Patch by @Frewuill

$oauth['oauth_signature'] = $signature; // don't want to abandon all that work!
ksort($oauth); // probably not necessary, but twitter's demo does it

// also not necessary, but twitter's demo does this too
function add_quotes($str) { return '"'.$str.'"'; }
$oauth = array_map("add_quotes", $oauth);

// this is the full value of the Authorization line
$auth = "OAuth " . urldecode(http_build_query($oauth, '', ', '));

// if you're doing post, you need to skip the GET building above
// and instead supply query parameters to CURLOPT_POSTFIELDS
$options = array( CURLOPT_HTTPHEADER => array("Authorization: $auth"),
                  //CURLOPT_POSTFIELDS => $postfields,
                  CURLOPT_HEADER => false,
                  CURLOPT_URL => $url,
                  CURLOPT_RETURNTRANSFER => true,
                  CURLOPT_SSL_VERIFYPEER => false);

// do our business
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);

$twitter_data = json_decode($json);

Hope It helps somebody with the same problem I had.

Karlsruhe answered 5/4, 2013 at 17:50 Comment(6)
thanks a lot, your code improvement works well! One question re: "// a stronger nonce is recommended". What could that be? time()?Garnishee
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.Rafter
receiving error 32. Could not authenticate you.. any help please??? i've used your above codeKermanshah
@frewuill, your are great bro, its working me like a charm, thanks.Hemmer
@frewuill THIS was the best answer, it is working with parameters as well and I can confirm it works even with the new 2.0 Twitter API!Trimetallic
If you want to use field with commas in query, then add also this line (not nice but it works): $url = str_replace( "%252C", ",", $url );Trimetallic
R
9

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:

$token = 'YOUR TOKEN';
$token_secret = 'TOKEN SECRET';
$consumer_key = 'YOUR KEY';
$consumer_secret = 'KEY SECRET';

$host = 'api.twitter.com';
$method = 'GET';
$path = '/1.1/statuses/user_timeline.json'; // api call path

$query = array( // query parameters
    'screen_name' => 'twitterapi',
    'count' => '2'
);

$oauth = array(
    'oauth_consumer_key' => $consumer_key,
    'oauth_token' => $token,
    'oauth_nonce' => (string)mt_rand(), // a stronger nonce is recommended
    'oauth_timestamp' => time(),
    'oauth_signature_method' => 'HMAC-SHA1',
    'oauth_version' => '1.0'
);

$oauth = array_map("rawurlencode", $oauth); // must be encoded before sorting
$query = array_map("rawurlencode", $query);

$arr = array_merge($oauth, $query); // combine the values THEN sort

asort($arr); // secondary sort (value)
ksort($arr); // primary sort (key)

// http_build_query automatically encodes, but our parameters
// are already encoded, and must be by this point, so we undo
// the encoding step
$querystring = urldecode(http_build_query($arr, '', '&'));

$url = "https://$host$path";

// mash everything together for the text to hash
$base_string = $method."&".rawurlencode($url)."&".rawurlencode($querystring);

// same with the key
$key = rawurlencode($consumer_secret)."&".rawurlencode($token_secret);

// generate the hash
$signature = rawurlencode(base64_encode(hash_hmac('sha1', $base_string, $key, true)));

// this time we're using a normal GET query, and we're only encoding the query params
// (without the oauth params)
$url .= "?".http_build_query($query);

$oauth['oauth_signature'] = $signature; // don't want to abandon all that work!
ksort($oauth); // probably not necessary, but twitter's demo does it

// also not necessary, but twitter's demo does this too
function add_quotes($str) { return '"'.$str.'"'; }
$oauth = array_map("add_quotes", $oauth);

// this is the full value of the Authorization line
$auth = "OAuth " . urldecode(http_build_query($oauth, '', ', '));

// if you're doing post, you need to skip the GET building above
// and instead supply query parameters to CURLOPT_POSTFIELDS
$options = array( CURLOPT_HTTPHEADER => array("Authorization: $auth"),
                  //CURLOPT_POSTFIELDS => $postfields,
                  CURLOPT_HEADER => false,
                  CURLOPT_URL => $url,
                  CURLOPT_RETURNTRANSFER => true,
                  CURLOPT_SSL_VERIFYPEER => false);

// do our business
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);

$twitter_data = json_decode($json);
Rafter answered 14/3, 2013 at 1:23 Comment(0)
A
5

If you have the OAuth PHP library installed, you don't have to worry about forming the request yourself.

$oauth = new OAuth($consumer_key, $consumer_secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
$oauth->setToken($access_token, $access_secret);

$oauth->fetch("https://api.twitter.com/1.1/statuses/user_timeline.json");
$twitter_data = json_decode($oauth->getLastResponse());

print_r($twitter_data);

For more information, check out The docs or their example. You can use pecl install oauth to get the library.

Auriferous answered 18/3, 2013 at 18:19 Comment(0)
L
5

First of all I wanted to thank jimbo and (his post / twitter-api-php simple library).

If you are going to use the GET search/tweets API with "twitter-api-php" PHP library (TwitterAPIExchange.php):

First, you have to just comment "Perform a POST request and echo the response " code area.

Just use "Perform a GET request and echo the response" code and echo the response and change these two lines:

$url = 'https://api.twitter.com/1.1/followers/ids.json';
$getfield = '?screen_name=J7mbo';

to

$url = 'https://api.twitter.com/1.1/search/tweets.json';
$getfield = '?q=J7mbo';

(Change screen_name to q, that's it :)

Lowenstern answered 17/6, 2013 at 6:4 Comment(1)
I still have not luck :/Anurous
A
2

You'll need a to create an "app" on Twitter (and you need a Twitter account to do this).

Then, you need to use OAuth to make an authorized request to Twitter.

You can use the GET statuses/user_timeline resource to get a list of recent tweets.

Antonelli answered 16/10, 2012 at 18:48 Comment(3)
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.Auction
github.com/abraham/twitteroauth/blob/master/test.php seems to have a lot of examples!Antonelli
@MatthewRapati Page is missing.Pekan
B
0

Here's a brief one for getting a specified number of tweets from your timeline. It basically does the same thing as the other examples, only with less code.

Just fill in the keys and adjust $count to your liking:

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

$oauth = array('count' => $count,
               'oauth_consumer_key' => '[CONSUMER KEY]',
               'oauth_nonce' => md5(mt_rand()),
               'oauth_signature_method' => 'HMAC-SHA1',
               'oauth_timestamp' => time(),
               'oauth_token' => '[ACCESS TOKEN]',
               'oauth_version' => '1.0');

$oauth['oauth_signature'] = base64_encode(hash_hmac('sha1', 'GET&' . rawurlencode($url) . '&' . rawurlencode(implode('&', array_map(function ($v, $k) { return $k . '=' . $v; }, $oauth, array_keys($oauth)))), '[CONSUMER SECRET]&[ACCESS TOKEN SECRET]', true));

$twitterData = json_decode(file_get_contents($url . '?count=' . $count, false, stream_context_create(array('http' => array('method' => 'GET',
                                                                                                                           'header' => 'Authorization: OAuth ' 
                                                                                                                                       . implode(', ', array_map(function ($v, $k) { return $k . '="' . rawurlencode($v) . '"'; }, $oauth, array_keys($oauth))))))));

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

Bearish answered 13/1, 2015 at 13:51 Comment(0)
H
-1

From their signature generator, you can generate curl commands of the form:

curl --get 'https://api.twitter.com/1.1/statuses/user_timeline.json' --data 'count=2&screen_name=twitterapi' --header 'Authorization: OAuth oauth_consumer_key="YOUR_KEY", oauth_nonce="YOUR_NONCE", oauth_signature="YOUR-SIG", oauth_signature_method="HMAC-SHA1", oauth_timestamp="TIMESTAMP", oauth_token="YOUR-TOKEN", oauth_version="1.0"' --verbose
Hifalutin answered 21/3, 2015 at 21:36 Comment(0)
V
-2
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET);

$timelines = $connection->get('statuses/user_timeline', array('screen_name' => 'NSE_NIFTY', 'count' => 100, 'include_rts' => 1));
Vistula answered 23/6, 2014 at 7:26 Comment(1)
Please include an explanation about what this code does, so the OP can learn from it.Mascara
L
-2

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

<?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;
}

function returnTweet(){
    $oauth_access_token         = "2602299919-lP6mgkqAMVwvHM1L0Cplw8idxJzvuZoQRzyMkOx";
    $oauth_access_token_secret  = "wGWny2kz67hGdnLe3Uuy63YZs4nIGs8wQtCU7KnOT5brS";
    $consumer_key               = "zAzJRrPOj5BvOsK5QhscKogVQ";
    $consumer_secret            = "Uag0ujVJomqPbfdoR2UAWbRYhjzgoU9jeo7qfZHCxR6a6ozcu1";

    $twitter_timeline           = "user_timeline";  //  mentions_timeline / user_timeline / home_timeline / retweets_of_me

    //  create request
        $request = array(
            'screen_name'       => 'burownrice',
            'count'             => '3'
        );

    $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'
    );

    //  merge request and oauth to one array
        $oauth = array_merge($oauth, $request);

    //  do some magic
        $base_info              = buildBaseString("https://api.twitter.com/1.1/statuses/$twitter_timeline.json", '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 request
        $header = array(buildAuthorizationHeader($oauth), 'Expect:');
        $options = array( CURLOPT_HTTPHEADER => $header,
                          CURLOPT_HEADER => false,
                          CURLOPT_URL => "https://api.twitter.com/1.1/statuses/$twitter_timeline.json?". http_build_query($request),
                          CURLOPT_RETURNTRANSFER => true,
                          CURLOPT_SSL_VERIFYPEER => false);

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

    return $json;
}

$tweet = returnTweet();
echo $tweet;

?>
Lourielouse answered 3/7, 2014 at 23:29 Comment(0)
S
-2

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.

The "tweets" table where store them:

CREATE TABLE IF NOT EXISTS `tweets` (
  `tweet_id` int(11) NOT NULL auto_increment,
  `id_tweet` bigint(20) NOT NULL,
  `text_tweet` char(144) NOT NULL,
  `datetime_tweet` datetime NOT NULL,
  `dayofweek_tweet` char(3) NOT NULL,
  `GMT_tweet` char(5) NOT NULL,
  `shorturl_tweet` char(23) NOT NULL,
  PRIMARY KEY  (`tweet_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=83 ;

get_tweets.php:

<?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;
}

function returnTweets($last_id) {
    $oauth_access_token         = "2687912757-vbyfJA483SEyj2HJ2K346aVMxtOIgVbsY4Edrsw";
    $oauth_access_token_secret  = "nIruzmR0bXqC3has4fTf8KAq4pgOceiuKqjklhroENU4W";
    $api_key                    = "ieDSTFH8QHHPafg7H0whQB9GaY";
    $api_secret                 = "mgm8wVS9YP93IJmTQtsmR8ZJADDNdlTca5kCizMkC7O7gFDS1j";
    $twitter_timeline           = "user_timeline";  //[mentions_timeline/user_timeline/home_timeline/retweets_of_me]
    //create request
    $request= array(
        'screen_name'       => 'runs_ES',
        'count'             => '3',
        'exclude_replies'   => 'true'
        );
    if (!is_null($last_id)) { //Add to the request if it exits a last_id
        $request['since_id']= $max_id;
    }
    $oauth = array(
        'oauth_consumer_key'        => $api_key,
        'oauth_nonce'               => time(),
        'oauth_signature_method'    => 'HMAC-SHA1',
        'oauth_token'               => $oauth_access_token,
        'oauth_timestamp'           => time(),
        'oauth_version'             => '1.0'
        );
    //merge request and oauth to one array
    $oauth= array_merge($oauth, $request);
    //do some magic
    $base_info=                 buildBaseString("https://api.twitter.com/1.1/statuses/$twitter_timeline.json", 'GET', $oauth);
    $composite_key=             rawurlencode($api_secret).'&'.rawurlencode($oauth_access_token_secret);
    $oauth_signature=           base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
    $oauth['oauth_signature']=  $oauth_signature;
    //make request
    $header= array(buildAuthorizationHeader($oauth), 'Expect:');
    $options= array(CURLOPT_HTTPHEADER => $header,
                    CURLOPT_HEADER => false,
                    CURLOPT_URL => "https://api.twitter.com/1.1/statuses/$twitter_timeline.json?". http_build_query($request),
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_SSL_VERIFYPEER => false);
    $feed= curl_init();
    curl_setopt_array($feed, $options);
    $json= curl_exec($feed);
    curl_close($feed);
    return $json;
}

function parse_tweettext($tweet_text) {
    $text= substr($tweet_text, 0, -23);
    $short_url= substr($tweet_text, -23, 23);
    return array ('text'=>$text, 'short_url'=> $short_url);
}

function parse_tweetdatetime($tweetdatetime) {
    //Thu Aug 21 21:57:26 +0000 2014 Sun Mon Tue Wed Thu Fri Sat
    $months= array('Jan'=>'01', 'Feb'=>'02', 'Mar'=>'03', 'Apr'=>'04', 'May'=>'05', 'Jun'=>'06', 
                    'Jul'=>'07', 'Aug'=>'08', 'Sep'=>'09', 'Oct'=>'10', 'Nov'=>'11', 'Dec'=>'12');
    $GMT= substr($tweetdatetime, -10, 5);
    $year= substr($tweetdatetime, -4, 4);
    $month_str= substr($tweetdatetime, 4, 3);
    $month= $months[$month_str];
    $day= substr($tweetdatetime, 8, 2); 
    $dayofweek= substr($tweetdatetime, 0, 3);
    $time= substr($tweetdatetime, 11, 8);
    $date= $year.'-'.$month.'-'.$day;
    $datetime= $date.' '.$time;
    return array('datetime'=>$datetime, 'dayofweek'=>$dayofweek, 'GMT'=>$GMT);
    //datetime: "YYYY-MM-DD HH:MM:SS", dayofweek: Mon, Tue..., GMT: +####
}

//First check in the database the last id tweet:
$query= "SELECT MAX(tweets.id_tweet) AS id_last FROM tweets;";
$result= exec_query($query);
$row= mysql_fetch_object($result);
if ($result!= 0 && mysql_num_rows($result)) { //if error in query or not results
    $last_id= $row->id_last;
}
else {
    $last_id= null;
}

$json= returnTweets($last_id);
$tweets= json_decode($json, TRUE);

foreach ($tweets as $tweet) {
    $tweet_id= $tweet['id'];
    if (!empty($tweet_id)) { //if array is not empty
        $tweet_parsetext= parse_tweettext($tweet['text']);
        $tweet_text= utf8_encode($tweet_parsetext['text']);
        $tweet_shorturl= $tweet_parsetext['short_url'];
        $tweet_parsedt= parse_tweetdatetime($tweet['created_at']);
        $tweet_datetime= $tweet_parsedt['datetime'];
        $tweet_dayofweek= $tweet_parsedt['dayofweek'];
        $tweet_GMT= $tweet_parsedt['GMT'];
        //Insert the tweet into the database:
        $fields = array(
            'id_tweet' => $tweet_id,
            'text_tweet' => $tweet_text,
            'datetime_tweet' => $tweet_datetime,
            'dayofweek_tweet' => $tweet_dayofweek,
            'GMT_tweet' => $tweet_GMT,
            'shorturl_tweet' => $tweet_shorturl
            );
        $new_id= mysql_insert('tweets', $fields);
    }
} //end of foreach
?>

The function to save the tweets:

function mysql_insert($table, $inserts) {
    $keys = array_keys($inserts);
    exec_query("START TRANSACTION;");
    $query= 'INSERT INTO `'.$table.'` (`'.implode('`,`', $keys).'`) VALUES (\''.implode('\',\'', $inserts).'\')';
    exec_query($query);
    $id= mysql_insert_id();
    if (mysql_error()) {
        exec_query("ROLLBACK;");
        die("Error: $query");
    }
    else {
        exec_query("COMMIT;");
    }
    return $id;
}
Star answered 31/12, 2015 at 14:38 Comment(2)
'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 DBPullman
Also you have made all your keys and tokens public so don't be surprised if somebody takes it and hacks your twitter account!Verret

© 2022 - 2024 — McMap. All rights reserved.