Using Twitter with PHP to automatically post tweets

This is a cool little trick I used on my new site, Surl Mobile Bookmarks. Basically whenever someone adds a new bookmark, I want it to be tweeted. I searched around the web, and found an easy code snippet, that works like a charm.

For my site, when someone adds a bookmark, it posts their site title, description, and keywords into my database, and then adds it to the home page. While that code is happening, I simply use this Twitter PHP code to send the tweet.

First, you need this Twitter class, copy this code into your page:

class Twitter
{
   function Twitter() {
      die('Cannot instantiate this class(Twitter) in: '.__FILE__);
   }

   /**
    * Attempts to contact twitter and post a message
    *
    * @param string $uname         = Twitter User Name
    * @param string $pWord         = Twitter Password
    * @param string $message      = The message to post through the communication system
    * @param string $apiUrl      = Twitter API Url. (Optional - defaulted to standard XML API)
    * @return boolean
    **/
   function sendTwitter($message='',$apiUrl='http://twitter.com/statuses/update.xml')
   {
      $curl_handle = curl_init();
      curl_setopt($curl_handle, CURLOPT_URL, "$apiUrl");
      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=$message");
      curl_setopt($curl_handle, CURLOPT_USERPWD, "USERNAME:PASSWORD");
      //Attempt to send
      $buffer = curl_exec($curl_handle);
      curl_close($curl_handle);
      if(strpos($buffer,'<error>') !== false)
      {
         return false;
      }
      else
      {
         return true;
      }
   }
}

Where it says “USERNAME:PASSWORD” , put in your Twitter Username, and Twitter Password.

Then you simply put in this code after all of your PHP functions have happened.

$message = "http://surl.mobi New site posted at Surl.mobi";
$result = Twitter::sendTwitter($message);
   if($result)
   {
      echo "We've posted a tweet about your site entry!";
   }

That’s all there is to it! Now your web application can post directly to twitter, which can also help with traffic.

Articles, Code Snippets, Developers

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Leave Comment

You must be logged in to post a comment.