Update Twitter Tweet
Posted by Pete | Posted in PHP Functions | Posted on 12-10-2009-05-2008
0
So in my previous tutorial you have learnt how to get the latest twitter status well now we will learn how to update the twitter status with a random predefined message.
So here is the function that we will use to update the twitter.
function update_twitter($msg) // Start Update Twitter Function { $username = "TWITTER USERNAME"; // Twitter Username. $password = "TWITTER PASSWORD"; // Twitter Password. $url = "http://twitter.com/statuses/update.xml"; // Twitter Update URL API. $curl_handle = curl_init(); // Start CURL. curl_setopt($curl_handle, CURLOPT_URL, $url); // Url to connect to. curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2); // Stop if unable to connect in 2 seconds. curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1); // Return the information given. curl_setopt($curl_handle, CURLOPT_POST, 1); // Set the method as a post. curl_setopt($curl_handle, CURLOPT_POSTFIELDS, "status=" . $msg); // Put post fields together. curl_setopt($curl_handle, CURLOPT_USERPWD, $username . ":" . $password); // Login to update area. $response = curl_exec($curl_handle); // Run Curl and assign output to $response. curl_close($curl_handle); // Close Curl. if (empty($response)) // If $response is empty. { echo "fail"; // It failed to update twitter. } else { echo "success"; // Else show success message. } }
As you can see it is using curl and is fairly straight forward. First we get the information we need from the variables then we start the curl and set a few options to allow us to process the information to twitter. Finally we check to see if it was successful or not.
So lets use it.
<?php /** FUNCTION HERE **/ /** * Put the messages you want to be added in an array. * Leaving the first column blank allows PHP to put a incrementing ID in automatically. * So each message has a unique array id. */ $tweets[][txt] = "Hello This Is Twitter Bot Created By PK-Tuts."; $tweets[][txt] = "Visit PK-Tuts.co.uk for Website Development Tutorials."; $total = count($tweets); // Count total tweets $random = rand(0, $total); // Choose a random number from 0 to total tweets echo update_twitter($tweets[$random]["txt"]); // Run function with random tweet then echo the response. ?>
This will now add a random predefined message everytime the page is run. This can be used with a cronjob to add a random message every hour etc. Or it can also be used to integrate with wordpress etc so when a new post has been submitted it tells them on twitter. Well I will leave it upto you
So that’s it any questions please leave a comment. Thanks


