Monday, August 9, 2010

Post your Status in Twitter using PHP

t$twitter_api_url = "http://twitter.com/statuses/update.xml";
$twitter_data = "status=Visit http://anilkajadoo.blogspot.com/ for PHP tips and tutorials!";
$twitter_user = "your_user_name";
$twitter_password = "your_password";

The $twitter_data variable contains the message to be posted to Twitter, which you must ensure is 140 characters or less before posting. You could use strlen() function to do so when you ready the data to be sent, and truncate it if it’s too long by using substr() function. The status= before the message is the POST variable, the parameter for the API.


To send the request, we will use cURL, which is included on most servers. First we initiate cURL and pass it the URL we will be sending the request to:

$ch = curl_init($twitter_api_url);

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $twitter_data);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERPWD, "{$twitter_user}:{$twitter_password}");//Twitter Username & Password are used to post the status


$twitter_data = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

All that’s left really is to see whether it worked or not. Since we have our handy $httpcode variable, we can just run a conditional statement to see if the response code is equal to 200 (which means everything went okay).

if ($httpcode != 200) {
     echo "The tweet wasn't posted correctly. ";
}

         

No comments: