I’m sure I’ve mentioned sometime before that I’m a big fan of Twitter. I think Twitter has done a great job with their API, and the documentation for their API. They’ve made it fairly simple for developers to create Twitter based applications without jumping through a lot of hoops.

Well below is a bit of code I’ve used in the past to make status updates to Twitter. If your familiar with cURL then you’ll see that its pretty straight forward. The end result examines the HTTP code to determine if the status update was successful or failed you can comment this part out if you wish.

But before you go plowing away with the code I think it would be a good idea if you make yourself familiar with their documentation. They have a few rules that could save you some heartache down the road.

== Twitter Documentation ==
http://apiwiki.twitter.com/Twitter-API-Documentation

== PHP Code To Post Twitter Status Updates ==

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?PHP

/* Post Twitter Status Update using PHP & cURL */

function postToTwitter($username,$password,$message){
 
   $username = $username;
   $password = $password;
   $twitterHost = "http://twitter.com/statuses/update.xml";
   $yourStatus = $message;
   $curl;
   
   $curl = curl_init();
   curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 2);
   curl_setopt($curl, CURLOPT_HEADER, false);
   curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
   curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($curl, CURLOPT_USERPWD, "$username:$password");
   curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
   curl_setopt($curl, CURLOPT_POSTFIELDS, "status=". urlencode(stripslashes(urldecode($yourStatus))));
   curl_setopt($curl, CURLOPT_URL, $twitterHost);
   
   $result = curl_exec($curl);
   $resultArray = curl_getinfo($curl);
   
   if ($resultArray['http_code'] == 200) {
   
   $twitterPostStatus = "Success";
   
   } else {
   
   $twitterPostStatus = "Failed";
   
   }
   curl_close($curl);
   
 return $twitterPostStatus;  
}

$username = 'username_here';
$password = 'password_here';
$message = "Working with the Twitter API";

$result = postToTwitter($username,$password,$message);

print_r($result);
?>