22 May, 2010

Send Tweets to twitter using curl

Its quite easy to post message i.e. tweets to twitter using curl in php. Following code is used to
post tweet to twitter using curl in php.

//add tweet to the twitter using curl in php
$login = "twitterusename"; //twitter username
$passwd = "twitterpassword"; //twitter password
//url for posting status i.e. message
$url = "http://www.twitter.com/statuses/update.xml";
//message to ne posted
$status = "Test Tweet";
//initialize the curl
$ch = curl_init();
//set url for posting message
curl_setopt($ch, CURLOPT_URL, "$url");
//return the response as string so that it can be displayed
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//set the option to curl to indicate we are doing POST
curl_setopt($ch, CURLOPT_POST, 1);
//set the fields for POST
curl_setopt($ch, CURLOPT_POSTFIELDS, "status=$status");
//provide password and username for logging in
curl_setopt($ch, CURLOPT_USERPWD, "$login:$passwd");
//execute the curl
$response = curl_exec($ch);
//get the http code to check for status success or failure
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//check the http code returned in the response
//if code is 200 then succeed else error
if($httpCode == 200) {
echo "Tweet posted successfully.";
}
else {
echo "Some error occured while posting the tweet.";
}
?>

No comments: