Post to Twitter From a PHP Script: 2013 Edition

Back in 2009, I wrote a post on how to write a simple PHP script to call on the Twitter API and update your status. Despite its popularity, the information hasn’t been relevant in some time. (Things certainly have changed since then!) The Twitter API has changed a lot over the years, and it’s not so simple that you can get a newbie up and running with a few lines of code.

The mandatory usage of OAuth tokens, rather than a simple username and password combination, for API requests has greatly strengthened account security, but it’s one of the prime hurdles complicating the process. More recently, XML support was removed in favor of JSON, URL structures changed to include an API version, and authentication is now required for every request.

Fortunately, you don’t have to deal with the little details. You can use a library that does the heavy lifting for you, rather than reinventing the wheel. Sure, there are resources to learn how to do it the hard way, but I assume that you want a quicker solution if you’re reading this.

Step 1: Download tmhOAuth

Download the tmhOAuth library from GitHub. This package will handle interactions with the Twitter API once you include it from your script. (It requires at least PHP 5.1.2 and the cURL extension.)

Download tmhOAuth

Step 2: Include the Library in Your Project

First, drop the required files into your project folder. You could simply move the entire download in and rename it, or if you just want the essentials, the required files are tmhOAuth.php and cacert.pem.

Including tmhOauth

Now, you need to include the files in your PHP script. All you need is an include line at the top.

include 'tmhOAuth/tmhOAuth.php';

Step 3: Get Your Tokens

We need to make a short detour, now. In order to give your script permission to update your status, you need to generate some authorization tokens for it. Head over to dev.twitter.com/apps and log in to your Twitter account.

Click the big “Create a new application” button and fill in the required fields on the resulting screen. All you need is an application name to identify your script, a brief description, and the URL it will reside at.

Once you agree to the terms of service and submit the form, select the Settings tab on the resulting screen. Change the access type from Read Only to Read and Write before saving the settings.

Flipping back to the Details tab, you now need to scroll down to the OAuth settings section. You will need the consumer key and consumer secret, as well as the access token and access secret from the following section.

After the include lines, you need to instantiate the tmhOAuth class with the tokens, like so:

$tmhOAuth = new tmhOAuth(array(
  'consumer_key' => 'THE_CONSUMER_KEY',
  'consumer_secret' => 'THE_CONSUMER_SECRET',
  'token' => 'THE_ACCESS_TOKEN',
  'secret' => 'THE_ACCESS_TOKEN_SECRET',
));

This readies tmhOAuth to interact with the API through your account. (Allowing other Twitter users to log in and grant permission is beyond the scope of this tutorial. But Tuts+ has you covered if you want a more advanced tutorial.)

Step 4: Sending the Tweet

To send a tweet, all you have to do now is call the request method and pass the required arguments.

$response = $tmhOAuth->request('POST', $tmhOAuth->url('1.1/statuses/update'), array(
  'status' => 'Test message. Lorem ipsum.'
));

You can, of course, replace the message with anything you want (providing it’s under 140 characters) and even use a dynamic variable instead of a static string.

Step 5: Verify Success

Now let’s see if Twitter accepted the request and successfully updated your status.

if ($response != 200) {
	//Do something if the request was unsuccessful
	echo 'There was an error posting the message.';
}

Conclusion

That wasn’t too difficult, was it? While it’s a simple example, it should help you get started in the right direction. The tmhOAuth library can handle just about any Twitter API request you may need to make, and the GitHub repository includes plenty of examples to browse through.

  • http://redkeycode.com Randy

    Thank you so much for taking the time to post this information. Works perfect!

  • http://www.phronzs.com Virneto

    I’ve been searching for this information for a while. Thank you very very much!!!
    You’ve surelly made it simple for me!!

    Best Regards!!

    Virneto

  • JearryFen

    Hello. Do anyone know what is all about this cookie acceptation thing? Is it safe?

    Thanks for answer

  • http://bestjewelry.jigsy.com/entries/diamond/why-is-jewelry-essential-to-our-lifestyles- http://bestjewelry.jigsy.com/entries/diamond/why-is-jewelry-essential-to-our-lifestyles-

    I don’t even know how I ended up here, but I thought this post was great. I don’t know who you are but
    definitely you are going to a famous blogger if you are not already
    ;) Cheers!

  • tutless

    got 400 error response

  • rick

    I get a 401 error. :(

  • rick

    D’oh! Forgot to re-create my tokens after changing the access level to read/write. Now works fine. THANK YOU.

  • mvincisgrassi

    many thanks

  • Mayank Patel

    I got 403 error, so please guide me for right way

  • Mayank Patel

    Once i got a success message. But then after i got this above 403 error.

  • Mayank Patel

    I got solution for the above 403 error.
    403 ERROR arise in case when same text post twice in a row.

    Thank You

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

      Twitter does this intentionally. They throw a 403 error if you try to post a duplicate message, because they don’t want duplicates.

  • Gareth

    I’m getting an error when running this. It loads the contents of tmhOAuth.php into the webpage and displays this error at the end:

    Fatal error: Class ‘tmhOAuth’ not found in /home/cliftont/public_html/discount.php on line 6

    The file does exist at the required location. Any help would be apreciated.

  • http://www.kbve.com/c/ Admin KBVE

    Amazing guide! I would love getting permission to show this to my cs class? Would that be okay?

    • Aaron

      Hey Admin KBVE,

      You might want to check out my post below for the recent changes to the tmhOAuth library and hence this tutorial :)

      Cheers!

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

      Sure, go ahead. My goal is to spread knowledge, after all. :)

  • Aaron

    Hey Matt (and everyone else on here),

    I’m not sure if you’ve updated this elsewhere Matt, but you should note that the tmhOAuth library has been updated yesterday (14-06-2013). There are two differences from your tutorial:

    1) It doesn’t have tmhOAuthUtilies.php anymore, so you don’t need to ‘include’ it now.

    2) ‘user_token’ has been changed to ‘token’ & ‘user_secret’ has been changed to ‘secret’

    Here’s an image of my working php script – http://bit.ly/19COdhw for reference (ignore the commented out bits!) :)

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

      Thanks for the info, I’ll try to find the time to update the post soon.

  • http://www.dinelogik.co/ Ted Bradley

    so awesome! never would have guessed i could be posting to twitter via php in 5min. thanks.

  • http://www.Sutihadi.com Suti hadi

    I tried using this, with the updated token and secret stuff mentioned above after trying as is from download and copy/paste from above etc.

    Nothing works, all that happens is load the page and it instantly redirects to my twitter page.

    Any advice?

  • Tim Church

    Relative newbie on php here. Trying this but not sure where to put the four keys/tokens/secrets, etc in both programs ( my calling prog and the tmhOAuth one ). Get “There was an error posting the message. Response: 0″. Would have thought that a response of 0 was okay but what is needed is a response of 200. Also, not sure what you want in the link above. Any help would be appreciated. All the best, Tim

    • bala

      That happens if your php version is not supporting!!
      For that you must edit tmhOAuth.php file.
      Edit the following things

      ‘curl_cainfo’ => ‘path of cacert.pem in your server’,
      ‘curl_capath’ => ‘folder path ‘,
      for example: if your cacert.pem file path is var/www/html/abc/cacert.pem then,

      ‘curl_cainfo’=>’var/www/html/abc/cacert.pem’,
      ‘curl_capath’ => ‘var/www/html/abc/’

      • Tim Church

        Hi bala, sorry about the long delay for reply – work – have done what you said but still getting the same error ( have changed some other stuff previously ): Fatal error: Uncaught exception ‘TwitterException’ with message ‘Server error #410′ in Z:\Inetpub\vhosts\lutonchurchestogether.org.uk\httpdocs\php\twitter.class.php:238 Stack trace: #0 Z:\Inetpub\vhosts\lutonchurchestogether.org.uk\httpdocs\php\twitter.class.php(104): Twitter->request(‘statuses/update’, Array) #1 Z:\Inetpub\vhosts\lutonchurchestogether.org.uk\httpdocs\php\tweet.php(59): Twitter->send(‘I am fine’) #2 {main} thrown in Z:\Inetpub\vhosts\lutonchurchestogether.org.uk\httpdocs\php\twitter.class.php on line 238
        Any ideas?

  • Marc

    Hey there,

    How would I code so it will be possible to tweet from a .txt file?

    Marc

  • http://arhab.org Keith

    the file tmhUtilities.php was not in the download, any idea where I can get it? Does it still need that file at all?

  • http://hotcosta.com Pete Clark

    I suspect that this no longer works with the latest version of Twitter – I found that does work with the current version of Twitter 30 June 2013

    http://phpfashion.com/twitter-for-php

  • http://apps1.info URL Shortener

    When someone writes an piece of writing he/she
    maintains the idea of a user in his/her brain
    that how a user can understand it. Thus that’s why this post is amazing. Thanks!

  • wxmanajb

    Was using this OAuth script as a part of a much larger script with tremendous success (thank you for simplifying the implementation process). However, at some point in the last couple weeks, it stopped working. When trying to make a test script to see if it’s something on my end, I began receiving a 500 error:

    Internal Server Error

    The server encountered an internal error or misconfiguration and was unable to complete your request.

    Please contact the server administrator, webmaster@ajburnettonline.net and inform them of the time the error occurred, and anything you might have done that may have caused the error.

    More information about this error may be available in the server error log.

    Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.

    Any ideas?

  • E Paisley

    This may be the dumbest question ever but…WHO sends the tweet? There’s no login information in this script, right? No user/password. Is this script only usable by the actual account that created the CONSUMER/ACCESS keys? My understand was that the point of creating those keys was so that multiple users could use the same app, right? So how would one use those keys but tweet from a different account?

    Thanks and, again, sorry if this is easy and obvious, I’m new to PHP/Twitter API and there’s painfully little about posting tweets (or multiuser OAuth) out there.

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

      This script is designed for one user, and the second pair of access tokens represents the user that the tweet will come from. (It’s the account of the user setting this all up.) The first pair of tokens authorizes the application.

      Multi-user setups are a bit more work, but there’s a tutorial here if you need one.

  • Antonio Rojilla

    Amazing! Thank you! After 2 days reading and testing, and testing, I was about to give up trying to update a twitter account from a site but with your post and just 5 minutes, 5!, when my game started today its associated twitter account (@PS4Quest) was updated just in time! A million thanks! BTW, allow me to post here these words for those that may be searching what I was: “update twitter status with codeigniter” or “codeigniter twitter status” (hopefully this will bring you here some traffic and they will find an extremely easy and working solution… both parties win!). Again, a million thanks!

  • Arfan

    i got this error

    There was an error posting the message.

    any one can told me please about this error

  • 9 de novembre

    Thanks for the info.
    I’ve made it work once, but if I try again I see the “There was an error posting the message.” message.
    Any idea?

  • http://www.mynoblecare.com/ Usama Ejaz

    Thats good :)

  • Luis M

    Thank you for this post. Found it very informative.
    Yonkers Court Reporters