O'Reilly

Update Your Twitter Status Remotely Using PHP

By on  

The reason Twitter is so hugely popular is because their API allows for you to do almost anything. Here's how you can tweet remotely using PHP.

The PHP

/* settings */
$username = 'myUser';
$password = '**********';
$format = 'xml'; //alternative: json
$message = 'David Walsh\'s blog rocks! http://davidwalsh.name/';

/* work */
$result = shell_exec('curl http://twitter.com/statuses/update.'.$format.' -u '.$username.':'.$password.' -d status="'.str_replace('"','\"',$message).'"');
echo $result;

That's it! Note that you may direct Twitter to return a XML or JSON response. Here's what the responses look like:

The XML Response

<?xml version="1.0" encoding="UTF-8"?>
<status>
  <created_at>Tue Mar 17 14:45:05 +0000 2009</created_at>
  <id>1342408809</id>
  <text>David Walsh's blog rocks! http://davidwalsh.name/</text>
  <source>web</source>
  <truncated>false</truncated>
  <in_reply_to_status_id></in_reply_to_status_id>
  <in_reply_to_user_id></in_reply_to_user_id>
  <favorited>false</favorited>
  <in_reply_to_screen_name></in_reply_to_screen_name>
  <user>
    <id>15759583</id>
    <name>davidwalshblog</name>
    <screen_name>davidwalshblog</screen_name>
    <location>Madison, WI, US</location>
    <description></description>
    <profile_image_url>http://s3.amazonaws.com/twitter_production/profile_images/57860553/footer-logo_normal.jpg</profile_image_url>
    <url>http://davidwalsh.name</url>
    <protected>false</protected>
    <followers_count>960</followers_count>
  </user>
</status>

The JSON Response

{
	"user":
	{
		"profile_image_url":"http:\/\/s3.amazonaws.com\/twitter_production\/profile_images\/57860553\/footer-logo_normal.jpg",
		"description":"",
		"screen_name":"davidwalshblog",
		"url":"http:\/\/davidwalsh.name",
		"name":"davidwalshblog",
		"protected":false,
		"followers_count":960,
		"location":"Madison, WI, US",
		"id":15759583
	},
	"text":"David Walsh's blog rocks! http:\/\/davidwalsh.name\/",
	"in_reply_to_user_id":null,"in_reply_to_status_id":null,
	"created_at":"Tue Mar 17 14:45:05 +0000 2009",
	"in_reply_to_screen_name":null,
	"truncated":false,
	"favorited":false,
	"id":1342408809,
	"source":"web"
}

Depending on how critical this functionality is to your site, you may want to set up a system of retries if the first attempt fails.

O'Reilly Velocity Conference
Save 20% with discount code AFF20

Recent Features

Incredible Demos

  • MooTools Gone Wild: Element Flashing

    If you're like me and lay awake in bed at night, you've flipped on the TV and seen the commercials: misguided, attention-starved college girls fueled by alcohol ruining their futures by flashing lame camera-men on Spring Break. Why do they do it? Attention,...

  • MooTools Kwicks Plugin

    I wrote a post titled Get Slick with MooTools Kwicks ages ago. The post was quite popular and the effect has been used often. Looking back now, the original code doesn't look as clean as it could. I've revised the original...

Discussion

  1. You should check for the php cURL functions to be present before executing a shell command. This makes your PHP more cross-platform friendly, enhances performance, allows you to manage timeouts and error handling, etc.

  2. Guillermo Rauch: I half agree, half don’t. I don’t think that adding code to do that is the way to go because it’s extra processing for each time you try to do this. I think doing a human check before implementing this system is the way to go.

  3. Like Guillermo Rauch says, i think is better to use the cURL function. You don’t know if the script run on a windows or *nix environement. And some hosting compagnies don’t allow to execute some commands. For the speed, i agree with David, you will not see the difference, and especially if the number of update you will do per hour are not too big, few extra-miliseconds for the processing with the shell command will not hurt anybody ^^

  4. httpwebwitch

    why use shell_exec(), when you can use the built-in curl functions?

        $curl = curl_init(); 
        curl_setopt($curl, CURLOPT_URL, 'http://twitter.com/statuses/friends_timeline.xml'); 
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
        curl_setopt($curl, CURLOPT_POST, 1); 
        curl_setopt($curl, CURLOPT_USERPWD, $twittername.":".$twitterpassword); 
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Expect:'));
    
        $xml = curl_exec($curl); 
    
  5. @David
    Aside from being more easily cross-platform, there’s no valid reason not to use PHP libcurl implementation. Currently, the command line curl is just a C program that acts as a wrapper to libcurl. If you can access the library directly, why would you chose to create a bridge instead ? Why concatenate and parse strings if you can use the more friendly http://php.net/curl_setopt ?

  6. I explored the curl_setopt() functionality but didn’t feel obligated to use it. I do like that it could prevent shell_exec permission issues on shared hosts though. In the end, I think it’s 6 of one and a half dozen of the other.

  7. If anyone is planning on using this in their PHP scripts to accept the $message variable through user interaction I would HIGHLY recommend sanitizeing it and possibly going through curllib instead of shell_exec as the combination would be extremely dangerous.

  8. onassar

    Should look into http://gnipcentral.com/ if you’re doing large scale integration. Changes the way you would integrate receiving updates (rather than polling twitter, it gets pushed to your server by Gnip)

  9. Tim Nicholson

    httpwebwitch, since your curl options tips were SO helpful to me I thought I’d post back the exact code to update twitter status using that message:

    $request = 'http://twitter.com/statuses/update.xml?status='.urlencode($status);
    $session = curl_init($request);
    curl_setopt($session, CURLOPT_HEADER, false);
    curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($session, CURLOPT_USERPWD, $twittername.':'.$twitterpassword);
    curl_setopt($session, CURLOPT_POST, 1);
    $response = curl_exec($session);
    curl_close($session);
    

    Does anyone know a quick way to check the status code to make sure the update was successful?

  10. @Tim Nicholson – I think this will work for you. I got it from BrownPHP.com – use-php-to-twitter-your-tweets

    $result = curl_exec($curl);
    $resultArray = curl_getinfo($curl);
    
    if ($resultArray['http_code'] == 200)
    echo ‘Tweet Posted’;
    else
    echo ‘Could not post Tweet to Twitter right now. Try again later.’;
    
    curl_close($curl);
    
  11. Thanks for sharing, I’m trying to use the update status code in the comments above but I’m getting a 401.
    Do you have to register somewhere?
    99% sure my twitter username and password are correct in the CURLOPT_USERPWD call.
    :(

  12. Thanks for sharing and contribute. Recently, I posted an related article related aricle and today I wrote about your post.

  13. nice tutorial, I am new using twitter, and I want to explore deeper about twitter,

  14. Hi! Great tut! How do I get this to post something else than “from web” ?

  15. i’am using this personal homepage to update twitter and facebook with one click. Also you can see if you got new messages on facebook or twitter from your homepage: http://www.isstarting.com

  16. jw

    How can I use the xml result that twitter sends me back?
    I would like to save the message id

  17. Im using Joomla+Adsmanager component. This code works with it if server supports exec() function:

    $twitter = 1;
    if($twitter == 1){
    $title = mosGetParam( $_POST, "ad_headline", "" );
    $twitter_username = "";
    $twitter_password = "";
    exec("curl -u $twitter_username:$twitter_password -d \"status=$title...\" http://twitter.com/statuses/update.xml");
    

    How to change this code, to get it work with curl function ?

  18. hi

    not work anymore … there is a new api :(

  19. Siemer

    Is this code using the ‘basic authentication’ method?
    Will this code stop working when Twitter drops the Basic Auth on the 30th of june? :(
    http://www.countdowntooauth.com/

  20. Will using curl to post to twitter stop working when twitter stops allowing basic authentication? I’ve been looking into oauth tuts but it seems complicated and overkill.

  21. @David Walsh: twitter is changing thier api . . . this code won’t work by next month . . . =o(

    do you think you cause update it with a simply methoid to tweet using oAuth?

  22. Can’t post by oauth methods, need your variant :(

  23. Can someone tell me about in PHP CURL is not working now. someone know what happend…..?

  24. Twitter changed their API, meaning you can’t use this code anymore. Same with Facebook a while back. I’m currently developing a CMS for my company and this feature is wanted by many of our clients. Does anyone know a function of class that will update twitter and/or Facebook?

  25. Thanks for this code!

  26. Now this method of authorization and posting works only: http://w3pro.ru/article/posting-v-twitter-s-pomoshchyu-php-twitter-api-oauth

  27. this post is not work at all any body know about update status on twitter with out using AOUTH API

  28. kanna

    Hi, im getting $resultArray[‘http_code’] as 400, wat it mean..? any one help me…..?

  29. this post is not work at all any body know about update status on twitter with out using AOUTH API

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!

Recently on David Walsh Blog

  • Prevent Chrome from Translating a Page

    A while back I shared my favorite Google Chrome extension:  Google Art Project.  I've enjoyed seeing beautiful art when I open a new tab -- it's brought genuine happiness to my day, however small that happiness may be.  About a week ago, however, the art presented had...

  • Create Any Type Of Website With These Multi-Purpose Themes

    We have selected what we believe are the very best multipurpose WordPress themes on the market today. Our list contains a number of best sellers, several newcomers that are proving to be highly popular, and a few themes that are ideal for creating the types of...

  • An Introduction to Static Site Generators

    Static site generators seem to have been becoming more and more popular recently, but they’re not one of those ephemeral novelty things that grow in popularity as quickly as they fall into oblivion shortly after. For over a decade, many different projects — 394 of...

  • Automated Tests for Visual Responsive Layouts

    Today it's all about testing. In 2015, many developers knows about TDD and I personally think that testing is one of the key for quality products. But what about testing in a Front-end environment? How do you guys write your tests for a responsive page or...

  • Getting Dicey With Flexbox

    What if you could build complex CSS layouts in minutes? Flexbox is a new CSS layout spec that makes it easy to construct dynamic layouts. With flexbox, vertical centering, same-height columns, reordering, and direction agnosticism are a piece of cake. There's a popular myth floating around that...