It ‘s quite simple to create a Twitter API PHP script what can post to twitter auto without too much work. In this tutorial I will show you step by step doing it.
Step 1 – Register your application to use Twitter API
You can register new application here http://dev.twitter.com/apps/new . Please notice that you need to log in to Twitter at the start of the Application registration process. The account that you’re logging in to, is naturally also the twitter account that you’re application can post tweets to.
Filling in the form is pretty straightforward.
The only special requirement for our purpose is set Default Access type to “Read & write”, so your application is allowed to post tweets to twitter
Step 2 – Consumer secret and Consumer key for Twitter API
When your application is registered by Twitter, you also have all the required keys for your script.
You find the consumer keys here:
View Your Applications -> Edit Details
The consumer keys can be found at the last part of the page
Step 3 – Access token and Access token secret for Twitter API
You find the Access token and Access token secret by clicking on the “My Access token” link in the right menu.
When you have the four keys/tokens:
- Consumer secret
- Consumer key
- Access token
- Access token secret
- You’re ready to proceed
Step 4 – Twitter OAuth class in Twitter API
To connect to twitter using OAuth we’ll be using the brilliant Abraham Twitter OAuth class. The Abraham twitter OAuth class has a lot of overhead enabling more advanced authentication than is required for this script. You only need the two files “OAuth.php” and “twitteroauth.php”.
You can download 2 files here: http://tips4php.net/docs/twitteroauth.zip
When you have downloaded the files, and uploaded them on your server, you’re ready for the last step
Step 5 – Post to twitter script api
Having the required access tokens, keys and the Twitter OAuth class, it’s a piece of cake to build a script that posts messages to twitter.
You just need to insert the required keys and the path to the twitteroauth.php file in the script below, and then you’re up and running.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php $consumerKey = '<insert your consumer key'; $consumerSecret = '<insert your consumer secret>'; $oAuthToken = '<insert your access token>'; $oAuthSecret = '<insert your token secret>'; require_once($_SERVER['DOCUMENT_ROOT'].'/<insert path to twitteroauth>/twitteroauth.php'); // create a new instance $tweet = new TwitterOAuth($consumerKey, $consumerSecret, $oAuthToken, $oAuthSecret); //send a tweet $tweet->post('statuses/update', array('status' => 'Hello World')); ?> |
Conclusion
The process for getting this script up and running might be a little complex, but you only have to go through the process once, and then you have a very simple to use script for sending tweets to twitter from a PHP script.