Twitter API Programming Tutorial With PHP – Intro

picture-15

I have recently started using Twitter and completely fell in love with it. Being a programming, this naturally made me want to develop applications for interfacing with it. So, I scoured the internet (checking Twitter’s website as well) to find good *simple tutorials for doing this. After searching for a while, I couldn’t really find any. Ok, I lied, I found a few but they were terrible. I hate tutorials that assume the reader knows more than they actually do.

So, I am taking it upon myself to write a series of comprehensive tutorials for interfacing with Twitter. I will first do them all in PHP and then maybe in some other languages. I may even do some in Objective-C to be implemented on the iPhone. These would be written of course at iCodeBlog.com ;) .

Let’s just jump right in. Twitter offers a few ways to interface with their web services, which are all documented on their API Wiki. The documentation is great, assuming you know the code to get connected and make the calls. So, let’s skip all of the nerdy low level stuff and write an application.

Today, I will be teaching you how to simply connect to Twitter and update your status. This will be pretty straight forward and require very little PHP code. So, grab some coffee, open up your favorite PHP editor (notepad?).

Ok, so let’s start by wrapping our code into an easy to call function. We don’t want to have to copy and paste our Twitter interface code every time we need it in a project. Wouldn’t it be nice if we could just call it like this

1
updateTwitter("Just Rockin Out")

So let’s begin by declaring a function called updateTwitter. Type the following code

1
2
3
4
5
<?php 
function updateTwitter($status){ 
	// Twitter login information 
	$username = "TwitterUsername"; 
	$password = "TwitterPassword";

Our function begins with a declaration of a username and password. This will be your Twitter login information. Every Twitter API call requires that you authenticate yourself. Make sure you update the code to include your username and password/

Next, we will add the following code to initialize the variables needed to make our Twitter API call. Continue by adding the following code.

1
2
3
4
5
6
7
8
	// The url of the update function 
	$url = 'http://twitter.com/statuses/update.xml'; 
	// Arguments we are posting to Twitter 
	$postargs = 'status='.urlencode($status); 
	// Will store the response we get from Twitter 
	$responseInfo=array(); 
	// Initialize CURL 
	$ch = curl_init($url);

One thing I want to point out is the URL. Notice the update.xml at the end of it. This is telling the Twitter API we want to call the update function and we expect to receive xml back. You could also change it to be update.json if you want to receive json data back.

The next variable postargs is simply the arguments we will pass to the update function. Since these arguments get appended to the URL, they need to be urlencoded. The responseInfo array will contain the return data from the cURL request to Twitter. Finally, we just initialize a new cURL session. cURL is just a protocol for transferring data. You can read up on it on Wikipedia if you feel so inclined.

Next, we need to tell cURL to do a POST rather than a GET and pass it our argument string

1
2
3
4
	// Tell CURL we are doing a POST 
	curl_setopt ($ch, CURLOPT_POST, true); 
	// Give CURL the arguments in the POST 
	curl_setopt ($ch, CURLOPT_POSTFIELDS, $postargs);

The next part is where the magic happens. Here is the next bit of code (I’ll explain it below)…

1
2
3
4
5
6
7
8
9
10
11
12
13
	// Set the username and password in the CURL call 
	curl_setopt($ch, CURLOPT_USERPWD, $username.':'.$password); 
	// Set some cur flags (not too important) 
	curl_setopt($ch, CURLOPT_VERBOSE, 1); 
	curl_setopt($ch, CURLOPT_NOBODY, 0); 
	curl_setopt($ch, CURLOPT_HEADER, 0); 
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1); 
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
	// execute the CURL call 
	$response = curl_exec($ch); 
	// Get information about the response 
	$responseInfo=curl_getinfo($ch); 
	// Close the CURL connection curl_close($ch);

Wow! that looks like a lot of nerdy code. Good thing you only have to write it once and don’t have to understand it (unless you want to). The first line sets the username and password fields in our cURL call. When we first connect with the Twitter API, it will prompt for a username and password. cURL will automatically feed the username and password to the API. The next few lines are not super important. If you one of those people that get hung up on that sort of thing, you can read about them here. We’re almost done, I promise… Finally, we make the cURL call itself by calling curl_exec. This will return a response from Twitter which will contains some XML if your call completed successfully. The next line, gets the http response (makes sure you were able to connect to Twitter). If it is anything other than 200 (HTTP OK), it means your cURL request never even reached Twitter. Here is the last bit of code

1
2
3
4
5
6
7
8
9
10
	// Make sure we received a response from Twitter 
	if(intval($responseInfo['http_code'])==200){ 
		// Display the response from Twitter 
		echo $response; 
	}else{ 
		// Something went wrong 
		echo "Error: " . $responseInfo['http_code']; 
	} 
} 
?>

All this code really does is makes sure we got a 200 code (successfully reached Twitter). If so, it prints out the XML that Twitter returned to us. Now you have a handy-dandy function you can call whenever we want to update your Twitter status from your website. Simply type

1
updateTwitter("Just finished a sweet tutorial on http://brandontreb.com")

and like magic, your Twitter status will be updated. This has many different uses as you can imagine. Join me next time when I will be putting this code into a PHP class as well as implementing the rest of the Twitter API functions. We will then be able to use this Twitter class in a variety of PHP applications. So , be sure to subscribe to my RSS feed and feel free to ask me any questions in the comments section of this post. You can also download the source code of this tutorial here… (insert clever tag line here (iCodeBlog’s is happy iCoding, I need a new one)).

If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!

Tags: , ,

27 comments

  1. This looks great and I’ll definitely be giving it a go! Also wanted to look into http://framework.zend.com/manual/en/zend.service.twitter.html since I use Zend for most of my projects.

  2. @jasondtaylor
    Holy Crap Brandon. i guess i feel about how you would if i were to do a tutorial on score writing a modern 12-tone concerto or something. WOW. I wish I knew how to do all this stuff…but on second though am glad that you do and that you are so willing to share it with everyone. Keep it up my man!

  3. @jasondtaylor

    haha, thanks man. I really enjoy writing these nerdy tutorials. It helps me learn the subject that I am teaching on. I just wish I had more time to post more often.

  4. Hey, Brandon. Neat stuff. I’m an Epidemiologist with the Maryland Department of Health and Mental Hygiene, and I’m trying to show folks around here how useful Twitter can be to track disease in the community by tracking for certain “key terms” in Twitter updates. Is there a useful tutorial to polish up my programming skills to create a “dashboard”-like site where folks can just click on an icon and read the tweets on a particular disease. This is to prevent them from going to the search and doing a long search themselves. Any ideas would be greatly appreciated… Please feel free to e-mail me to discuss this further, if you have time. Thanks!

  5. Brandon, you, sir, are a genius. I thank you SO much for this tutorial, you’ve really saved me from hours of struggling! :D

  6. Tutorial was very well done, better than all those others that are just like, hey, copy this, then don’t fricking bug me ever again.

  7. Steve Wanless

    Great tutorial.

    Question – if you look at the twitter API it has more things you can set on a status update then just the text of the status. (http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses%C2%A0update).

    How can I use your method and set things like ‘in_reply_to_status_id’ and ‘source’??

  8. strange I’m just getting a white page?? I’m guessing this is what happens if it doesn’t return a response of 200?? I followed exactly as above…and I have curl installed on my server… any clues?

  9. Wow, this is what I am looking for… thanks for the great tutorial.. it worked perfect!

  10. @Steve Wanless

    There are four possible fields:

    status
    in_reply_to_status_id
    lat
    long

    To utilize these three additional fields, make the following changes:

    1.) Update the parameters of the function:

    function updateTwitter($status,$reply_id,$lat,$long){

    2.) Now update the $postargs variable like so:

    $postargs = ‘status=’.urlencode($status).’&in_reply_to_status_id=’.$reply_id.’&lat=’.$lat.’&long=’.$long;

    You can also tell the function to return an OK or Error code by replacing the echo statements at the bottom with return statements instead.

    When you make the status update call, make sure to pass all of the new parameters, ie:

    $tw_response = updateTwitter(‘This is a test response’,’100593049′,’43.399295′,’-122.493094′);

  11. Why do I get Error 0? need help… thanks

  12. nice work will give it a try http://guymix.com

  13. Funny, I get a Error 400, but that means:
    400 Bad Request: The request was invalid. An accompanying error message will explain why. This is the status code will be returned during rate limiting.

    But I did not do anything else on twitter to be over the rate limit…

    Any ideas?

  14. Hi Brandon, above was cool explanation of implementing twitter in a website. But can u provide any help of how to get the latest reply for the question that i m posting to twitter. That is what exactly I want. Thanks in advance.

  15. I am an eighth grade teacher and I am trying to create a form that will submit my “week at a glance” (Monday-Friday) to a MySql database as well as Twitter. Is that possible using the postToTwitter function or will the API not let me submit 5 items that quickly? I want to enter the assignments for the week on Friday the week before and have it go to both places. I appreciate any knowledge you would be willing to send my way. Thanks so much.

  16. @esnod,

    I had the sample problem (error 400) with the code provided, when I commented out the extra header settings

    //curl_setopt($ch, CURLOPT_NOBODY, 0);
    //curl_setopt($ch, CURLOPT_HEADER, 0);
    //curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
    //curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    it worked for me.

  17. hey man,

    thanks a million .. ist is working on my site.
    still one thing: twitter response with an
    xml output. can i suppress that in any way?

    i tried something like
    suppress_response_codes=true

    but did not work..

  18. thank you thank you thank you!!!!! I will be following you on twitter

  19. Wow that was useful and simple. Been trying to find this for several hours, thanks.

  20. It was a nice tutorial.
    I want to make a page where I could get latest tweets from twitter & than categorize them also. And I want to do it like user do not need to log into their twitter account but it is shown as service on the web page displaying this continuously. Can someone help me about it.
    thanks in advance.

  21. OK, I find that hashtags are used to figure out ‘category’ of post. But I am unable to find any help how to use hasttag using php. Can anyone help ?

  22. Hi,

    using this now for our companys feed.
    Because our internal Intranet Server is located behind a proxy I added some more lines:

    curl_setopt($curl_conn, CURLOPT_PROXY, http://our.proxy.com:8080“);
    curl_setopt($curl_conn, CURLOPT_PROXYPORT, 8080); curl_setopt ($curl_conn, CURLOPT_PROXYUSERPWD, “proxyUser:proxyPassword”);

    Works really nice ;-)

Leave a comment