Build Your First Twitter App Using PHP in 8 Easy Steps
In my last article, I explained the steps involved in setting up a developers' account at Twitter and registering your first app- making this as easy as possible. Well, it's time to get your hands dirty and actually build that app!
If you're not a developer, don't worry- I plan to make this as easy as possible. I passionately believe everyone should have the chance to play with this stuff and free their data.
I do make a few assumptions, however- you'll have a website and be able to upload files to it (preferably via FTP) and your website should have the server-side language PHP running. If you have a WordPress website then the answer to these questions should be yes. If this isn't the case, then I hope there is something you can still learn from this article.
1. Create Your First PHP File
I don't know what you use to edit text files on your computer. You might use Notepad or Text Editor something similar. I used to use Notepad++ or Dreamweaver but now use SublimeText. It doesn't matter, just load it up- we're going to write our first script and upload it onto your website. Usually, web pages are just sent from your website's servers as plain old HTML (the language used for web pages). However, servers can do some magical things before they get sent out by using server side languages. We'll be using PHP since it's probably the most popular.
We need to initiate PHP in the file so that your server knows what is coming is PHP and not plain old HTML. Firstly we'll give the file name the PHP extension ".php" as opposed to the standard ".html" one. We also need to tell the server when to start and stop reading as PHP. To do this we need to use opening and closing PHP tags like this:
<?php ?>
Anything that goes in between these tags is seen as PHP. That's where the magic starts. I'm not going to give a beginners tutorial on PHP here because there are plenty examples on the web- including a simple PHP intro on the PHP website and an introduction to PHP course on Udemy. For now, let's do something really simple, and output some text. To do this we will use the "echo" statement in PHP. We put the text in double quotes and we end the line with a semi-colon (PHP throws a toddler's tantrum if you forget to end a line with a semi-colon!).
<?php echo "<h2>Simple Twitter API Test</h2>"; ?>
Now, upload this up to your website. I'd recommend creating a folder or directory called something like "test". This is particularly important if your website runs WordPress as we don't want these files to get mixed up with your WordPress ones. Call the file littleApp.php and upload it. You can see my example here. It's not very exciting... not yet anyway!
2. Use a PHP Wrapper Script
Don't worry if you have no idea what a PHP Wrapper Script is. I am not sure I do either, but all will be revealed...
As I said in my previous article, an API (short for Application Programming Interface) is a system that allows other applications to talk to an application- receive information from it and send information to it. Twitter has had an API since 2006 (not long after it started). Initially, it was very easy for developers to use. However, over the years, that API has become more sophisticated and in June 2013, Twitter (in version 1.1 of its API) have forced all applications interacting with its API to authenticate themselves. Authentication basically means that if you want to connect to the API, you have to say who they are and to prove that you have the authority to access the data for that particular user.
The reason for forcing you to authenticate is because Twitter wants to control access to their data. This is partly for creating a more unified experience for end users, but also because they want to gain revenue from advertising and so need a strict control over the use of their data.
I hate when things are made difficult, so I was extremely glad when I came across an easy to understand article on the developers' forum, Stack Overflow on how retrieve data from Twitter using v1.1 of their API. The accepted answer to the Stack Overflow question was written by a developer called James Mallison (J7mbo) who has gone out of his way to explain how to do this. Huge thanks to him- as it is the reason this article is being written and also how my Twitter app, Twools (more about that later on), has been built.
Please Note It's best to run this on a web server (i.e. not locally) and you may need to check a few things with your host first. Firstly make sure you have a modern version of PHP. I have tested it using PHP 5.2 and above, but really your host should be using 5.4 or higher. You will also need to have cURL installed. Don't worry about what this is- but the wrapper script requires this to connect to the Twitter API. Most hosting environments should have this as standard- check with your host. You may also want to check that your host has the latest root certificates installed for cURL as I’ve had reports of some hosting hosts not bothering to do this. If Twools doesn’t work, you’ll need to ask your host! Thanks to Tyler Hakes for looking further into this!
James has developed a simple "PHP Wrapper" for calls to Twitter's API v1.1. With this wrapper, you can more easily make calls to the API and then interact with the data. You can view the file on this GitHub repository and download it from here.
GitHub
Once you've downloaded the file, unzip it and upload the file 'TwitterAPIExchange.php' to the same folder as your 'littleApp.php' file. Now we really are ready to create some Twitter API magic using PHP. Are you ready? Let's move on!
3. Enter Your Tokens
Now that you have the PHP Twitter Wrapper script in the same directory as your littleApp.php file, we can use it to help us access the Twitter API.
To do this, we need to include the Twitter wrapper script using the 'require_once' function. Once we've done that, we need to set our access tokens by adding it to the $settings array (remove the "YOUR_OAUTH_" etc bits and replace with your tokens). Don't worry too much about this for now- all you need to know is that the PHP wrapper will use these tokens to make the connection to the Twitter API. If you don't have your app access tokens, then have a read of my article on How to Create a Twitter App in 8 Easy Steps.
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" );
4. Decide what Call to Make!
Now we need to decide what information we want to request from Twitter. Do you want to get the tweets from your timeline? How about someone else's? Perhaps the tweets from one of your Twitter lists? Or even do a Twitter search? Well, it's all very easy- all you need to do is get the URL from the Twitter API documentation. At first, it can look a little daunting, so I've included a few here to get you started...
- User Timeline: https://api.twitter.com/1.1/statuses/user_timeline.json
All your tweets or the tweets of the user you specify. - Mentions: https://api.twitter.com/1.1/statuses/mentions_timeline.json
All the tweets in which another Twitter user mentions you. - Home Timeline: https://api.twitter.com/1.1/statuses/home_timeline.json
All the tweets from the people you follow - Twitter Search: https://api.twitter.com/1.1/search/tweets.json
A Twitter search with the query you specify.
We need to give the PHP Twitter wrapper the URL so it can make the correct API request for us. In order to do this, we will need to create a string with the URL in it. Let's call that string $url:
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
As well as the URL and your API tokens, Twitter sometimes needs a bit more information in order to proceed. That information depends on the Twitter resource you are requesting. If you don't specify any other information with the user timeline request then it will return your tweets. However, you can tell the Twitter API to return the tweets of another user by sending their ID or screen name.
5. To GET or to POST
When want to visit a website, your browser makes a request to the website's server. This type of request uses a way of connecting (or a "protocol") called "Hyper-Text Transfer Protocol" (or HTTP) which was first invented in the early 1990s by Tim Berners-Lee and his team. You don't really need to know this, but I think it's useful in understanding the different ways we can connect to the Twitter API. In HTTP we can request information in different ways.
The most popular one is "getting" information from a server using the "GET" method. With "GET" we request the information by sending the URL as well as other information. This other information can be added to the end of the URL by putting a question mark and stringing on the information after that. For example:
https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=iagdotme
We can also add more bits of information by using the ampersand symbol ("&")...
https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=iagdotme&count=50
The other popular method is called "POST" and is normally used when you submit a form. Because stringing all the information contained in a form to the end of an URL wouldn't be practical (just think how long the URL could be!), the extra information is sent separately to the URL.
There other methods which are used far less regularly- HEAD, OPTIONS, PUT, DELETE, TRACE and CONNECT- let's not worry about those for now.
Twitter accepts both the GET and POST methods, but generally, asks for read-only data (such as getting tweets) to be requested by the GET method and for writing data (such as sending a tweet) be done by the POST method. There is one exception in that, if your request string is going to be very long, you might want to use POST even though you are requesting read-only data. This is because the URL could end up being too long.
For this article, we are only going to be requesting information, so let's stick with GET.
So we've given the Twitter wrapper our access tokens and the URL for the API call- now we need to tell it we want to use the GET method. To do this, we set another variable so that the PHP Twitter wrapper can make the correct request. Let's call that string $requestMethod:
$requestMethod = "GET";
We also need to set the GET information too. We could append that to the URL, but for the PHP Twitter Wrapper, we are going to add that information separately. I recommend looking through each Twitter API resource in the documentation as each resource have different parameters you can add. For the user_timeline one, we could add screen_name and count. The screen_name parameter allows us to ask the Twitter API for the tweets from another user and the count parameter tells twitter how many results we want returned to us. In this case, we want to receive the last 20 tweets from the Twitter user, @iagdotme. In this case, the GET string would be:
?username=iagdotme&count=20
In order to hand this over to the PHP Twitter wrapper, let's set it in a string- $getString:
$getfield = '?screen_name=iagdotme&count=20';
Are you still following what I am saying? I hope so! Let's move on...
6. Connect to the Twitter API
I hope you're excited because we've now reached the point when we can make that call to Twitter!
Let's recap. We've...
- Uploaded the PHP wrapper and your test PHP file to a directory/folder on your website
- Included the PHP wrapper script at the start of your test PHP script
- Set your access tokens in the $settings array
- Set the URL for the API request
- Set the HTTP method for the request as GET
- Set the extra bits of information that Twitter needs for the request (screen name and count) in the $getfield String
Now we need to make the call using the PHP Twitter Wrapper. To do this and to output it, we evoke the TwitterAPIExchange class with the access tokens and give it all the extra bits of information ($getField, $url and $requestMethod)...
$twitter = new TwitterAPIExchange($settings); echo $twitter->setGetfield($getfield) ->buildOauth($url, $requestMethod) ->performRequest();
If you run this file from your browser, you'll see the request from Twitter. It's in a format called JSON. Don't worry about that for now- the main thing is that we've got the information.
Here is the code we've got so far. Feel free, to copy, upload and run.
<?php 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" ); $url = "https://api.twitter.com/1.1/statuses/user_timeline.json"; $requestMethod = "GET"; $getfield = '?screen_name=iagdotme&count=20'; $twitter = new TwitterAPIExchange($settings); echo $twitter->setGetfield($getfield) ->buildOauth($url, $requestMethod) ->performRequest(); ?>
You can see an example of the output here (please note this is just a cache of the output since I don't want to make an API call each time someone views the file).
7. Do Stuff with the Data
So, we've now got the data from Twitter. But what do we do with it? It's in this weird format called JSON! Well, some of you will have experience with JSON, but I know many of you won't. The reason Twitter chooses this over other formats (such as XML and RSS) is that it can be easier to work with and it allows more of a rich data set. That's definitely true- Twitter gives us lots of goodness in the JSON output, but it can be daunting at first.
Well, there is a PHP function which can come to our rescue called json_decode
. It converts or decodes a JSON string into an object or an array. For this exercise, we're going to convert the JSON string into an "associative array". An array is a special string that contains more than one value. In an associative array, you can give each value a name or key. This makes it easier to retrieve that value later. In our case, we can ask the array to give us the text of the tweet or the screen name. For more information, have a look at this simple article on arrays from W3 Schools.
So, instead of outputting the JSON string, let's convert it to an associative array using the json_decode function:
$string = json_decode($twitter->setGetfield($getfield) ->buildOauth($url, $requestMethod) ->performRequest(),$assoc = TRUE);
You'll notice that this is almost the same as before, except we've wrapped it with json_decode and set $assoc to TRUE so that we convert the JSON to an associative array.
We can't just output an array using echo since it has more than one value. For now, let's output the array using the print_r function. To make it easier to read, we'll wrap it in <pre>
tags so that it is pre-formatted text (i.e. fixed width).
Just in case Twitter returns an error, it's important to be notified of this. Twitter returns any errors in the error array, so we can check for that. If it exists, we can return the error message and stop the script. Thanks to Jay (in the comments) for an update on this line:
if(array_key_exists("errors", $string)) {echo "<h3>Sorry, there was a problem.</h3><p>Twitter returned the following error message:</p><p><em>".$string[errors][0]["message"]."</em></p>";exit();}
Here is the full code so far...
<?php 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" ); $url = "https://api.twitter.com/1.1/statuses/user_timeline.json"; $requestMethod = "GET"; $getfield = '?screen_name=iagdotme&count=20'; $twitter = new TwitterAPIExchange($settings); $string = json_decode($twitter->setGetfield($getfield) ->buildOauth($url, $requestMethod) ->performRequest(),$assoc = TRUE); if(array_key_exists("errors", $string)) {echo "<h3>Sorry, there was a problem.</h3><p>Twitter returned the following error message:</p><p><em>".$string[errors][0]["message"]."</em></p>";exit();} echo "<pre>"; print_r($string); echo "</pre>"; ?>
You can view an example of the output here.
8. Let's go all Loopy!
Now that we've got our data the way we want it, we can start to access the information about each tweet. One way to do that is to loop round the array and asking for each bit of information. Since this is our user timeline data, we can ask it for:
- created_at - Date and time of tweet
- favorited - Whether the tweet was favorited or not.
- id_str - The Id of the tweet
- text - The text of the tweet (only the first 140 characters)
- full_text - The text of the tweet (all 280 characters - but only if you use the tweet_mode=extended option in the query)
- retweet_count - How many times the tweet was retweeted
and about the user who tweeted the tweet:
- name - The name of the user
- profile_image_url - the URL of the the user's profile pic
- created_at - When their account was created (when they first joined Twitter)
- location - Their location (as set in their profile)
- url - The link in their profile
- name - Their full name (as listed in their profile)
- listed_count - How many Twitter lists they are in.
- followers_count - How many followers they have.
- protected - Are their tweets protected?
- statuses_count - How many tweets have they sent?
- friends_count - How many people do they follow (friends)
- screen_name - Their screen name.
That is not an exhaustive list- for all the entities, have a look at the Twitter documentation for user timelines.
For this exercise, we're going to loop around our associative array and output all the information. It's not going to look pretty, but that's not the point of this exercise.
PHP has a great little function to help us loop around an array. It is called foreach(). For our exercises we will use it like this:
foreach($string as $items) { // Do Stuff }
The foreach function loops through the array and each time sets $items to the current value. We can then do stuff with that value before the loop carries on. Because it is an associative array we can access the keys very easily using the keys that Twitter supplied (for example "text", "created_at", "location"). We can output the tweet information like this:
foreach($string as $items) { echo $items['created_at']."<br />"; echo $items['text']."<br />"; }
Information about the user who tweeted the tweet is stored in an array which we can access in the loop using $items['user']. For example if we want their screen name, we'd use $items['user']['screen_name']. Here is an expanded version of the above:
foreach($string as $items) { echo "Time and Date of Tweet: ".$items['created_at']."<br />"; echo "Tweet: ". $items['text']."<br />"; echo "Tweeted by: ". $items['user']['name']."<br />"; echo "Screen name: ". $items['user']['screen_name']."<br />"; echo "Followers: ". $items['user']['followers_count']."<br />"; echo "Friends: ". $items['user']['friends_count']."<br />"; echo "Listed: ". $items['user']['listed_count']."<br />"; }
Update - since Twitter moved from just 140 characters per Tweet to 280, you can't rely on getting the full Tweet from $items['text']
anymore. You'll need to use <code?$items['full_text']. But you only use this if you add tweet_mode=extended to the query string. So we'll add this to our $getstring:
$getfield = '?screen_name=iagdotme&count=20&tweet_mode=extended';
Thanks to Alexander (in the comments) for reminding me about this update!
Now, to be a bit more cunning, why don't we also allow you to show the tweets of another user? By adding the following line, we can check to see if you've added a string to the end of your URL (our little GET request!) to set a different screen name. And, because there are some nasty hackers out there, we'll also want to check and remove any non-alphanumeric characters that they may want to add.
if (isset($_GET['user'])) {$user = preg_replace("/[^A-Za-z0-9_]/", '', $_GET['user']);} else {$user = "iagdotme";}
If you append ?user=your_screen_name to the URL of your script, we can use that to set the screen name in our API request. If it is not set then it will use the default one (you'll have to change "iagdotme" above to your screen name). As well as that, we'll have to change another line in our script- the $getField string- so that we can set the user.
$getfield = "?screen_name=$user&count=$count&tweet_mode=extended";
Now, if you run the script as before, it will output your tweets. If you append ?user=lifehacker to the end of your URL, it will give you the tweets from @lifehacker.
Please note: I don't recommend setting these variables using the GET string on a public facing site. It could all to easily be abused by hackers. This will get you up and running quickly, but I recommend either hard-coding the variables, or doing some safety checks on the GET variables before you use them.
Here is the full version of our script:
<?php 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" ); $url = "https://api.twitter.com/1.1/statuses/user_timeline.json"; $requestMethod = "GET"; if (isset($_GET['user'])) {$user = preg_replace("/[^A-Za-z0-9_]/", '', $_GET['user']);} else {$user = "iagdotme";} if (isset($_GET['count']) && is_numeric($_GET['count']) {$count = $_GET['count'];} else {$count = 20;} $getfield = "?screen_name=$user&count=$count&tweet_mode=extended"; $twitter = new TwitterAPIExchange($settings); $string = json_decode($twitter->setGetfield($getfield) ->buildOauth($url, $requestMethod) ->performRequest(),$assoc = TRUE); if(array_key_exists("errors", $string)) {echo "<h3>Sorry, there was a problem.</h3><p>Twitter returned the following error message:</p><p><em>".$string[errors][0]["message"]."</em></p>";exit();} foreach($string as $items) { echo "Time and Date of Tweet: ".$items['created_at']."<br />"; echo "Tweet: ". $items['full_text']."<br />"; echo "Tweeted by: ". $items['user']['name']."<br />"; echo "Screen name: ". $items['user']['screen_name']."<br />"; echo "Followers: ". $items['user']['followers_count']."<br />"; echo "Friends: ". $items['user']['friends_count']."<br />"; echo "Listed: ". $items['user']['listed_count']."<br /><hr />"; } ?>
You can view the output of this script, here. I have also added it as a github repository called "My First Twitter App".
That's all folks!
So that's it. You've created your first Twitter app. OK, it's not the most elegant or useful- but it is a start. We're not going to end it all here, because in my next article I'll be showing you my first app, Twools, and I am really excited about it.
A massive thanks to James Mallison who developed the PHP Twitter Wrapper script and took the time to explain things on Stack Exchange. I hope you've been able to start your journey into the Twitter API world. Have fun!
This blog post is HUMAN CONTENT!
It's NOT been generated by any artificial intelligence (AI) tools. It's been authentically written by a human author (i.e. me!)
Comments are Temporarily Closed
We've closed the comments section on this blog due to spam, but we hope to reopen in the near future.