Post to Twitter From a PHP Script

If you’ve used Twitter for long, you’re probably aware of their impressive API. Nearly any day-to-day task that you can perform on Twitter.com can be done programmatically via the API. (This enables us to have useful applications like Twhirl.)

Now, suppose you would like to enhance a website with some sort of automatic Twitter alerts. A blog automatically tweeting new posts is one obvious example.

The Twitter API Wiki contains all the documentation for the API. It’s best to read up on how it all works before you get started with too much API work. If you head over to the REST API page, the part we’re mainly interested is the statuses/update function. To make use of it, we need to send an HTTP POST request to http://twitter.com/statuses/update.format. The format part would be replaced with either xml or json, depending on the format we want the response to be in. Let’s go with XML.

The update function accepts two parameters in the request, status, which is the message to be posted, and the optional in_reply_to_status_id, which is used when the tweet to be posted is a reply to a user.

First, let’s prepare the necessary information and store it in variables.

$twitter_api_url = "http://twitter.com/statuses/update.xml";
$twitter_data = "status=Visit http://www.webmaster-source.com for PHP tips and tutorials!";
$twitter_user = "your_user_name";
$twitter_password = "your_password";

The $twitter_data variable contains the message to be posted to Twitter, which you must ensure is 140 characters or less before posting. You could use strlen() to do so when you ready the data to be sent, and truncate it if it’s too long. The status= before the message is the POST variable, the parameter for the API.

You’ll want to fill-in your Twitter username and password into the $twitter_user and $twitter_password variables, so the script can login and post to your account.

To send the request, we will use cURL, which is included on most servers. First we initiate cURL and pass it the URL we will be sending the request to:

$ch = curl_init($twitter_api_url);

Next we set the cURL options for the request. CURLOPT_POST to specify a POST request, CURLOPT_POSTFIELDS to set the data to be sent, CURLOPT_USERPWD to authenticate, and a few others that are necessary.

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $twitter_data);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERPWD, "{$twitter_user}:{$twitter_password}");

Next we execute the request, capture the HTTP response code, and close our cURL session.

$twitter_data = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

All that’s left really is to see whether it worked or not. Since we have our handy $httpcode variable, we can just run a conditional statement to see if the response code is equal to 200 (which means everything went okay).

if ($httpcode != 200) {
echo "<strong>Don't Panic!</strong> Something went wrong, and the tweet wasn't posted correctly.";
}

This is a fairly simplistic example. Obviously you would have to expand upon it to make it useful. You’ll need to prepare and pass data to it in some way, for one. If your messages will be accompanied by links, you’ll want to run them through a URL shortener first (Bit.ly has an API that you can use in a similar manner to Twitter’s to programmatically shorten URLs).

Update: This post is a bit out of date. For a more modern approach, that works with the changes Twitter has made to their API, see Post to Twitter From a PHP Script: 2013 Edition.

  • http://ineeddiscipline.com/2008/07/04/19-blog-review-networks/ Dean Saliba

    Sounds interesting.

    I've been looking for some kind of script to produce tweets in the sidebar of my blog.=, maybe this is the answer.

  • Pingback: abcphp.com

  • http://news.runtowin.com Blaine Moore

    Wow, that's ridiculously easy. I hadn't looked into hooking into the API myself yet, but I can already think of a few uses for that for automated websites…thanks for the heads up.

  • http://www.theworldallaround.com Benjamin Gray

    This was fantastic of you to write up. Thanks a ton.

  • http://intensedebate.com/people/redwall_hp redwall_hp

    It is easy. The only real problem is the security issue of storing peoples' Twitter usernames and passwords for things. Not something I generally like to do, for several reasons. (People don't seem to mind that much for some reason, though.) OAuth mitigates the problem, but it's a lot more complicated.

  • http://www.supadupawebdesign.co.uk David

    Fantastic! And it works a dream. Nice and bare-bones code which can easily be modified to do anything.

  • Curt

    I've ported this code over to use in ColdFusion and it's worked just fine for several weeks. Suddenly, without any changes to my code, posts have stopped appearing. I'm still getting a "200 OK" as a return code. Any ideas?

    • http://intensedebate.com/people/redwall_hp redwall_hp

      I'm not sure… I don't have any ColdFusion experience. Did any of your server configurations change, possibly?

  • Curt

    I'm on a shared hosting plan. To the best of my knowledge, nothing has changed.

    • http://intensedebate.com/people/redwall_hp redwall_hp

      Your host could have changed something, Twitter could have changed something, or there could have been something a bit flaky in your code. I'm not fluent in CF, but if you post it here I could have a quick look just to see if anything jumps out at me…

      • Curt

        Appreciate the help so far. Here's the snippet:

        <CFHTTP url="http://twitter.com/statuses/update.xml&quot; method="POST" username="useridhere" password="passwordhere" charset="UTF-8">
        <CFHTTPPARAM type="FORMFIELD" name="user" value="useridhere">
        <CFHTTPPARAM type="FORMFIELD" name="password" value="passwordhere">
        <CFHTTPPARAM type="FORMFIELD" name="status" value="#form.ttext#">
        </CFHTTP>
        <CFOUTPUT>#cfhttp.StatusCode#</CFOUTPUT>

        • http://intensedebate.com/people/redwall_hp redwall_hp

          Nothing glaringly obvious, though as I mentioned I don't really have any CF experience. Have you tried hard-coding the values to be sent (e.g. the username and password, then try the status) and running the script so you can see if the request will complete.

          That way you can eliminate the possibility that it's a problem with the input not being passed properly to Twitter.

          • Curt

            Will have to experiment a bit. Of course, today it worked. First time in nearly a month. Hiccup? No changes on my end…

          • http://intensedebate.com/people/redwall_hp redwall_hp

            Weird.

  • http://shizkit.com/ Ryan Boylett

    Thanks so much for this.
    Solved all my twitter-PHP-related problems :D
    Is there any way to change the "via API" bit that appears next to the new status?
    Cheers

    • http://intensedebate.com/people/redwall_hp redwall_hp

      Not using basic authentication. If you go the OAuth route, which is a lot more complicated to setup, the via field will update to be the name of the registered OAuth application.

      • http://shizkit.com/ Ryan Boylett

        Cool, I'll read into it
        Thanks very much!

  • http://sitejunction.awardspace.com/vbscript_tweets/ Erick

    This can also be done from a VbScript or HTA file. Tracking your followers is also an option with the Twiiter API.

    There is more about this on http://sitejunction.awardspace.com/vbscript_tweet

  • http://twitter.com/stuhar @stuhar

    Should this work using https in the $twitter_api_url?

    • http://intensedebate.com/people/redwall_hp redwall_hp

      I *think* so. Give it a try.

  • http://www.dreamzsop.com Mithilesh

    Wow thats really very nice i use to mange many website and i need to login to twitter to post the updates not i can do it easily.

  • http://www.sasaandjelic.com Sasa

    Thanks very much! I can’t describe how grateful I am for this tutorial. This was exactly what I needed and worked at first try.

    Thanks!!

  • http://twitter.com/chummydog Chummy Dog

    Many thanks!! Simple but effective twitter update PHP script.

  • Rich

    Great work! Thank you!

  • http://tips4php.net Jorgen Nicolaisen

    Nice article with a very good explanation of the implementation steps. If you’re interested in another angle on publishing from php to twitter, you can find script, that includes bit.ly url shortening, and content shortening here: http://tips4php.net/2010/03/au.....n-twitter/

  • http://freeprintablecouponsonline.blogspot.com/ Gary Farnam

    Pretty awesome post. I think I’m going to have a simple text file of tweets that I write ahead of time, and have a cron job run this script (modified) from my godaddy hosting account at various times of the day. Thanks for the info!

  • adydoang

    how i can make my own update.xml?? can you give me the script update.xml?

  • http://ibuyfrom.com Dan

    THANK YOU! That just saved me a huge amount of time!!

  • mungo

    Excellent, thank you.

    Unfortunately, this will break on 16-Aug-10 when Twitter stop Basic Auth from working, and force everyone to use OAuth. What’s the easiest way of doing this kind of thing with OAuth?

  • Nino

    Is there such a thing for Facebook as well?

  • http://d3in.com/ Conrad Warhol

    This is great! Thank you man!

  • Krishna

    $twitter_api_url = “http://twitter.com/statuses/update.xml”;
    $twitter_data = “status=hi guys”;
    $twitter_user = “username”;
    $twitter_password = “password”;
    $ch = curl_init($twitter_api_url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $twitter_data);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_USERPWD, “{$twitter_user}:{$twitter_password}”);
    $twitter_data = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    //print_r($httpcode);
    if ($httpcode != 200) {
    echo “Don’t Panic! Something went wrong, and the tweet wasn’t posted correctly.”;
    }
    else
    {
    echo ‘Congrats it is succesfully posted’;
    }
    hi any one help me. I have used the above code for posting a message in twitter but it is not posting. It is returning $httpcode as 401. Please help me.

  • JXR

    401 is probably because this method is depricated

  • karthick

    I’m also getting same error(401)!! Pls any one can help me
    karthickv08@gmail.com

    • http://www.webmaster-source.com Matt

      Twitter no longer supports basic authentication. You need to use the more advanced OAuth technique in order to update statuses via the API.

  • http://www.neatstat.com Pummy Manku

    is there any new modern script out there? post the code or any link.

    thanks

  • http://ayauho.com ayauho

    Fast and easy way to update status in twitter with PHP in 2 steps – http://ayauho.com/~ay

    • Tiz

      I tried the script in three files.
      When I connect twitter it tells me a PIN that I have nto clue where to put it.

  • http://www.raincreatives.com Urvisha

    This code is not at all working for me. i have used this code in facebook application. then i have tried also in local but not working.Can anyone help me to sort out this.

    • http://www.webmaster-source.com Matt

      As I said previously:

      “Twitter no longer supports basic authentication. You need to use the more advanced OAuth technique in order to update statuses via the API.”

      This tutorial is out-of-date.

  • http://www.neatstat.com Pummy Manku

    Hello Matt,

    Maybe this tutorial out-of-date but it helps me to find the automated way to add the tweets automatically :)

    I added my twitter info (name+pass) in my google feedburner account and now google is adding my tweets via my site’s RSS into twitter and its 100% automatic.. saves lots of time of mine.

    If you have an google account, just add your twitter info and you are done.

    Regards,
    Pummy Manku, Admin of Neatstat.com & Nicestat.com

  • Deepak

    Hi All,
    i m not able to execute this script.

    $twitter_api_url = “http://twitter.com/statuses/update.xml”;
    $twitter_data = “status=Visit http://www.webmaster-source.com for PHP tips and tutorials!”;
    $twitter_user = “your_user_name”;
    $twitter_password = “your_password”;

    $ch = curl_init($twitter_api_url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $twitter_data);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_USERPWD, “{$twitter_user}:{$twitter_password}”);

    $twitter_data = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpcode != 200) {
    echo “Don’t Panic! Something went wrong, and the tweet wasn’t posted correctly.”;
    }

    can someone give me correct code ?

  • Kim Josephs

    @Deepak – twitter is using now OAuth so the script is not working anymore

    Now I use a good app in my opinion called Automatic Rss to Twitter – you can find out more from their website http://bncscripts.com/bnc-auto.....hp-script/

  • Matt

    @Kim Josephs

    or if you need a hosted script you can try http://engator.com/

  • Pingback: Post to Twitter From a PHP Script: 2013 Edition