Monday 30 November 2009

Update Twitter Status with PHP

/* Function to update the twitter status, Update Twitter Status Using PHP */
function tweetMyMessage($tweetUsername = '', $tweetPassword = '', $tweetMessage = '') {
if (function_exists('curl_init')) {
$twitterUsername = trim($tweetUsername);
$twitterPassword = trim($tweetPassword);

if(strlen($tweetMessage) > 140) {
$tweetMessage = substr($tweetMessage, 0, 140);
}

$twitterStatus = htmlentities(trim(strip_tags($tweetMessage)));

if (!empty($twitterUsername) && !empty($twitterPassword) && !empty($twitterStatus)) {
$strTweetUrl = 'http://www.twitter.com/statuses/update.xml';

$objCurlHandle = curl_init();
curl_setopt($objCurlHandle, CURLOPT_URL, "$strTweetUrl");
curl_setopt($objCurlHandle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($objCurlHandle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($objCurlHandle, CURLOPT_POST, 1);
curl_setopt($objCurlHandle, CURLOPT_POSTFIELDS, "status=$twitterStatus");
curl_setopt($objCurlHandle, CURLOPT_USERPWD, "$twitterUsername:$twitterPassword");

$result = curl_exec($objCurlHandle);
$arrResult = curl_getinfo($objCurlHandle);

if ($arrResult['http_code'] == 200) {
echo 'Your Tweet has been posted for update.';
}
else {
echo 'Sorry, could not post your Tweet message to Twitter.';
}

curl_close($objCurlHandle);
}
else {
echo('Missing required parameters to submit your Twitter message.');
}
}
else {
echo('Curl Extension is not installed.');
}
}

$username = 'twitterUsername';
$password = '**********';
$message = 'update my twitter status.';
/* invoking the tweetMyMessage function to Post Twitter from PHP. */
tweetMyMessage($username, $password, $message);

No comments:

Post a Comment

Please post any queries and comments here.