Skip to content

Posting to Twitter with PHP and OAuth class

Needed a bit of an update on a font site I threw up a few years ago. Specifically I wanted to put a script together to tweet a random font each day. Should have been easy since I already had a script that tweeted new fonts, although it’s been a bit behind since I haven’t been updating the site like I needed.

Realized that the old script wasn’t working though since Twitter switched to OAuth and the class my old script was using didn’t use OAuth.

Came across this post which lead me to a Twitter OAuth class which made the whole process dead easy.

Step 1 – Create a Twitter application

First thing you’ll need to do is create a Twitter application. Follow the link and go through the steps and you’ll get 4 bits of information you’ll need for the code: a consumer key, consumer secret, OAuth token, and OAuth secret.

Step 2 – Download the classes

Head to GitHub to download the two classes you’ll need. Get OAuth.php and twitteroauth.php, both in the twitteroauth folder. Both should go in the same folder as the script you’ll write.

Step 3 – The code

Here’s a mini version of the code I used. The real thing pulls from a database and uses a bit.ly class to shorten links.

include('twitteroauth.php');
define('CONSUMER_KEY', '**YOUR CONSUMER KEY**');
define('CONSUMER_SECRET', '**YOUR CONSUMER SECRET**');
define('OAUTH_TOKEN', '**YOUR OAUTH TOKEN**');
define('OAUTH_SECRET', '**YOUR OAUTH SECRET**');

$message = 'Whatever you want to tweet';

$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_SECRET);
$content = $connection->get('account/verify_credentials');
$connection->post('statuses/update', array('status' => $message);

That’s it.

I run this through a cron job so that a new font is pulled each day.

Published inProgramming

2 Comments

  1. Mumin Mumin

    Thanks for the informatiıon. Did you publish the code you use? Not the mini one. I want to do something similar to this. If you published, I would like to check.

    • I didn’t, and actually don’t use it anymore. The site that was using it switched over to WordPress and I’m using TwitterFeed instead to pull the RSS feed from WordPress and put in into the Twitter feed.

      I’ll dig around a bit and see if I can find what I was using though. Mostly it was just doing a database query, pulling either a record dated today or a random record – it tweeted both, and pushed it to Twitter.

Leave a Reply

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