Twitter API 101 – Authentication with PHP and cURL

January 23, 2009

Stop right there! I wrote this post back in January 2009, a lot has changed since then, and in case you haven’t heard basic authentication is a no go. I haven’t written any OAuth tutorials yet, so if you’re looking for some help check out the following links

How to Authenticate Users With Twitter OAuth

How to quickly integrate with Twitter’s OAuth API using PHP

Now that I’m in the process of writing a simple twitter application, I want to share with you some of the steps that might help you save some time and grief in the future.

In this post I’ll show you how to connect securely to Twitter, authenticate, make a query and return a particular users’ followers as a string using PHP and cURL.

//Create the connection handle

$curl_conn = curl_init();

//Set up the URL to query Twitter
$user_followers = “https://twitter.com/statuses/followers/”username.xml”;

//Set cURL options

curl_setopt($curl_conn, CURLOPT_URL, $user_followers); //URL to connect to
curl_setopt($curl_conn, CURLOPT_GET, 1); //Use GET method
curl_setopt($curl_conn, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); //Use basic authentication
curl_setopt($curl_conn, CURLOPT_USERPWD, ‘username:password’); //Set u/p
curl_setopt($curl_conn, CURLOPT_SSL_VERIFYPEER, false); //Do not check SSL certificate (but use SSL of course), live dangerously!
curl_setopt($curl_conn, CURLOPT_RETURNTRANSFER, 1); //Return the result as string

// Result from querying URL. Will parse as xml
$output = curl_exec($curl_conn);

// close cURL resource. It’s like shutting down the water when you’re brushing your teeth.
curl_close($curl_conn);

Explanation

The first step is to decide the type of query to use. For more information see the API wiki. Then you will set up all the options for cURL. In PHP these are set up one by one using curl_setopt(). If you don’t need a particular option, you can comment it out.  Each option is explained as a comment, but there are some areas that grant a bit more explanation.

Twitter uses basic authentication for their services.  This is only needed for certain parts of the API, but more than likely you’ll end up having to authenticate at some point.

Use HTTPS if possible, otherwise credentials would be sent in clear text and it would be fairly easy to intercept and read.

Lastly,  execute cURL. This is when the connection happens, until now we have only set options, but haven’t actually attempted a connection. Now that we have a string back, we can convert it to an XML object and parse it for any information we need.

Tags: , , ,

17 Responses to “Twitter API 101 – Authentication with PHP and cURL”

Speak up

CommentLuv Enabled