HOW TO: Update Twitter Using PHP

Twitter is growing rapidly these days, so I thought I would indulge on a post about talking to Twitter in PHP. Using this piece of code, you could place a “tweetThis” command in your page anywhere, and it would post a tweet. This could be handy for automatically tweeting your location when you are updating blogs, etc. Very fun stuff.

 140) {
        $strMessage = substr($strMessage, 0, 140);
      $twitterStatus = htmlentities(trim(strip_tags($strMessage)));
      if (!empty($twitterUsername) && !empty($twitterPassword) && !empty($twitterStatus)) {
        $strTweetUrl = '';
        $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';
        else {
          echo 'Could not post your Tweet to Twitter.';
      else {
        echo('Missing required information to submit your Tweet.');
    else {
      echo('Curl Extension is not installed.');

Here is a sample of how to use the code:

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>