Update Twitter using PHP
So, we have recently started posting our blog headers to Twitter so that people can follow the threads more easily. To do so, instead of constantly updating our content in two places, we modified our wordpress blog to post directly to Twitter when we publish new articles to the tech blog.
I would say that it took about 6 minutes to integrate the code and test the new addition. You should be able to do the same in no time!
This code helps you to do 1) build a tinyURL so that any links you require are short; and 2) post content to your Twitter status updates using the Twitter API.
function add_to_twitter($link, $status){
$tinyURL = $this->get_tiny_url($link);
// Set username and password
$username = 'username';
$password = 'password';
// The message you want to send
$status = $status . " " . $tinyURL;
// The twitter API address
$url = 'http://twitter.com/statuses/update.xml';
// Alternative JSON version
// $url = 'http://twitter.com/statuses/update.json';
// Set up and execute the curl process
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, "$url");
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_POST, 1);
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, "status=$status");
curl_setopt($curl_handle, CURLOPT_USERPWD, "$username:$password");
$buffer = curl_exec($curl_handle);
curl_close($curl_handle);
// check for success or failure
if(empty($buffer)){
echo "bad post";
}else{
echo "success";
}
}
//gets the data from a URL
function get_tiny_url($url){
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,'http://tinyurl.com/api-create.php?url='.$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
Great post. Looking forward to reading more about this.
Great post. I love reading this kind of information. Keep it up!