Sep 13, 2011 -
Development
No Comments
Development
No Comments How To Post to Twitter (tweet) from PHP

Tweeting to your account from PHP. I’m fresh off of adding this feature to another one of my sites so I thought I’d document the process for people as it’s not so obvious. I post important events to Twitter that happen on the website based on user interaction. I do not use this to allow users to post to THEIR Twitter accounts. So I’m posting events like “New Lost Dog Added” or “New Naming Assignment”, etc. So I’m only posting to MY Twitter account.
- Download the TwitterOAuth library for PHP from http://github.com/abraham/twitteroauth/downloads and upload it to your website in a new directory /twitter.
- Visit https://dev.twitter.com/ and click Create an App. You will be asked to sign in as the Twitter account you will bill posting to.
- The Create an App wizard is pretty straight forward, except that the default rights are Read-Only. You have to go back and edit the rights to be Read/Write and resave the settings.
- Back on your website in the Twitter library code you will need to copy/paste the correct keys into the twitter/config.php file. You get these keys from the Twitter developer page for your new application. Twitter allows you to generate the keys on the dev site that you need for the OAuth keys on the config file. You have to click a button on the bottom of the details page to create the OAuth keys you will need. Note that if you change the application permissions (Read-Only, etc) the OAuth keys change and need to be re-copied. So copy the 4 keys to the appropriate constants in the config file.
- Also edit the callback URL to be example.com/twitter/callback.php.
- Load the twitter/index.php page from your website in your browser, click Sign In, and see that you get a long response from the API with a bunch of text that you don’t need to read. The error responses are short and sweet, so if you get a full array of data as a response then it signed in correctly. Now you know your sign-in works, just time to set up tweeting. If this step doesn’t work then re-check the config file, make sure you have the correct callback URL, etc.
- Create a function for tweeting:
function tweet($text)
{
include(‘twitter/twitteroauth/twitteroauth.php’);
include(‘twitter/config.php’);$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, OAUTHTOKEN, OAUTHSECRET);
$content = $connection->get(‘account/verify_credentials’);
return $connection->post(‘statuses/update’, array(‘status’ => $text));
} - Now add tweet($text) at important parts in your PHP code. Make sure you’re tweeting relevant information about events on your website.