Develop auto post publishing twitter app
Posted by mahmud ahsan on November 30, 2009 in
PHP, Twitter | 15 Comments
Twitter is a free social networking and micro-blogging service that enables its users to send and read messages known as tweets. Though according to CEO of Twitter he says “We think of Twitter as it’s not a social network, it is an information network. It tells people what they care about as it is happening in the world.” Though first people personally use twitter for their own purpose, but now twitter is very popular in business world. Many companies are using twitter to promote their business, inform people about their products, services.
In this article, I’ll show how you could develop a basic twitter application using php and twitter api, that will auto publish your predefined tweets. To develop this app we have to do the following tasks:
- Create an offline authentication system
- Develop an admin system to add posts in database
- Write a php script that will publish the posts in twitter
- Run the php script periodically using cron to auto publish the posts
Developing an offline authentication system: There is 2 ways, we can develop an offline authentication.
- User can give their username and password for offline access
- Using oAuth library user can only give permission to allow offline access
We can use the first solution, username and password. But keep in mind that, most of the users don’t like to give their username and password to a site/application. So we prefer to use oAuth library for twitter app.
OAuth is an authentication protocol that allows users to approve application to act on their behalf without sharing their password. To learn more about oAuth visit: http://oauth.net/
Check out the flow chart to learn how oAuth works with Twitter
Lots of talking
, now come to the point.
First visit http://twitter.com/oauth_clients and click Register a new App. Here you’ll see a page like this:
Now fill out this form. I assume that your web site link is: http://mysite.com . So we will create 4 files
- http://mysite.com/config.php
- http://mysite.com/twitter.php
- http://mysite.com/twitter_authorization.php
- http://mysite.com/twitter_cron.php
So in the form set Application Website ‘http://mysite.com/twitter.php’ . Set Callback Url ‘http://mysite.com/twitter_authorization.php’.
Submit the form and you’ll get a Consumer key, Consumer secret. Save this keys for future reference.
Now download oAuth php library for our app’s purpose. Download oAuth Library . Unzip it and save twitterOAuth folder in your project root folder.
Create a config.php file and place it in the root folder of your project. Write below code in config.php
<?php
$consumer_key = 'xxxxxxxxxxxxxxxxxxx'; //your app's consumer key
$consumer_secret = 'yyyyyyyyyyyyyyyyy'; //your app's secret key
include_once "model.php"; //model.php id described below
$model = new Model();
/* include the twitter OAuth library files */
require_once('twitterOAuth/twitterOAuth.php');
require_once('twitterOAuth/OAuth.php');
?>
Now write this code in twitter.php
<?php
session_start();
include_once "config.php";
/*
Create a new TwitterOAuth object, and then
get a request token. The request token will be used
to build the link the user will use to authorize the
application.
You should probably use a try/catch here to handle errors gracefully
*/
$to = new TwitterOAuth($consumer_key, $consumer_secret);
$tok = $to->getRequestToken();
$request_link = $to->getAuthorizeURL($tok);
$_SESSION['oauth_request_token'] = $tok['oauth_token'];
$_SESSION['oauth_request_token_secret'] = $tok['oauth_token_secret'];
header("Location: $request_link");
exit;
?>
For database usage I use a model.php file for database connection and insert/update/delete and query purpose.
<?php
/*
* @author: Md. Mahmud Ahsan
* @visit: http://thinkdiff.net
* @description: database functionalities
*/
class Model{
private $host = '';
private $user = '';
private $pass = '';
private $db = '';
function __construct($dbconfig){
$this->host = 'use your db host name'
$this->user = 'use your db user name';
$this->pass = 'use your db password';
$this->db = 'use your db name';
}
function connectDb(){
$link = mysql_connect($this->host , $this->user , $this->pass );
if (!$link){
die (mysql_error());
}
mysql_select_db($this->db);
}
function closeDb(){
mysql_close();
}
function query($sql){
$this->connectDb();
$data = array();
$result = mysql_query($sql);
if (!empty($result))
$rows = mysql_num_rows($result);
else
$rows = '';
if (!empty($rows)){
while ($rows = mysql_fetch_assoc($result)){
$data[] = $rows;
}
}
$this->closeDb();
return $data;
}
function insert($sql){
$this->connectDb();
$result = mysql_query($sql);
$this->closeDb();
return $result;
}
function insertAndGetId($sql){
$this->connectDb();
$result = mysql_query($sql);
$id = mysql_insert_id();
$this->closeDb();
return $id;
}
function update($sql){
$this->connectDb();
mysql_query($sql);
$this->closeDb();
}
function delete($sql){
$this->connectDb();
mysql_query($sql);
return mysql_affected_rows();
$this->closeDb();
}
}
?>
Create a database table, which table you’ll use for saving your apps configuration key for future purpose.
CREATE TABLE `options` ( `appid` INT UNSIGNED NOT NULL, `twitter_token` VARCHAR(200) NULL , `twitter_secret` VARCHAR(200) NULL , `created` DATETIME NULL , `updated` DATETIME NULL , PRIMARY KEY (`appid`) ) ENGINE = InnoDB
Now put below code in twitter_authorization.php.
<?php
session_start();
include_once "config.php";
if ((!isset($_SESSION['oauth_access_token'])) || ($_SESSION['oauth_access_token'])=='') {
$to = new TwitterOAuth($consumer_key, $consumer_secret, $_SESSION['oauth_request_token'], $_SESSION['oauth_request_token_secret']);
$tok = $to->getAccessToken();
/* Save tokens for later - might be wise to
* store the oauth_token and secret in a database, and
* only store the oauth_token in a cookie or session for security purposes */
$_SESSION['oauth_access_token'] = $token = $tok['oauth_token'];
$_SESSION['oauth_access_token_secret'] = $secret = $tok['oauth_token_secret'];
}
$to = new TwitterOAuth($consumer_key, $consumer_secret, $_SESSION['oauth_access_token'], $_SESSION['oauth_access_token_secret']);
$token = $_SESSION['oauth_access_token'];
$secret = $_SESSION['oauth_access_token_secret'];
//insert
$sql= "INSERT into options (appid, twitter_token, twitter_secret, created, updated)
values (1, '$token', '$secret', NOW(), NOW())";
$model->insert($sql);
?>
Now in your database the twitter app’s token and secret key is saved. we can use it for offline access. And we assigned ’1′ as our twitter app’s appid and saved it in database. You should develop a mechanism to dynamically generate and assign appid.
Now write the twitter_cron.php script that will auto publish your post.
<?php
include_once "config.php";
$sql = "SELECT * FROM options WHERE appid=1";
/*1 is your app you can dynamically map it for more than one application */
$result = $model->query($sql);
$token = $result[0]['twitter_token'];
$secret = $result[0]['twitter_secret'];
$status = "testing status";
/* you should make an admin from where you'll add status in database and retrieve those statuses and publish periodically */
//oAuth obj
try {
$to = new TwitterOAuth($consumer_key, $consumer_secret, $token, $secret);
$params = array('status' => $status);
$do_dm = simplexml_load_string($to->OAuthRequest('http://twitter.com/statuses/update.xml', $params, 'POST'));
}
catch(Exception $o ){
print_r($o);
}
?>
So this is the basic code. You have to set twitter_cron.php script as cron, so that it runs periodically. And please remember you’ve to make an admin from where you’ll add post in database, and you should update this twitter_cron.php code so that it should retrive a post automatically, publish it and make that published post in your database as status posted. Then same post will not publish again and again. I left the admin panel for your own purpose and I think it is very easy to develop an admin panel. Hope this tutorial will help you.
Related Posts
If you think this article kicked ass, subscribe to the RSS feed or follow me on Twitter! Share with your friends, or leave a comment below (or better still, do both!)Comments (15)




Hi – I don’t comment on many web sites but had to on yours. It’s really nice! I really like how you write – very to the point, unlike a lot of other blogs. I don’t have time to read everything here right now, I found your site while looking for something else on Yahoo. But I’ve bookmarked your homepage and will visit it regularly to read your latest postings. Thanks for having this site. I love reading sites about web development. I really like what you wrote in this post, and some of your other articles are interesting. I’ll have to read more. I have been learning JavaScript programming lately. It’s such an exciting area. I’ll bookmark it and visit regularly. Thanks again for a very informative site! Click here if you’d like to check out my site.
Hello! The articles here are great. Thanks for having this site. I have been learning Drupal lately on my own. Have you ever used Drupal? Any tips for me? I would appreciate any advice you have. Click here if you’d like to check out my site. Thanks again – great site!
Thank you for useful information
Thanks for share Md. Mahmud Ahsan , your great and smart enough for share this kind a little secret for someone like us to develop kind of this.
Here some my stupid question, actually i hate when Cron do this job on my online site, is it possible we are doing it by offline from our localhost server and send it directly to twitter by pass from our online site? thanks for your answer .. many thanks once again
@buxcorner: yeah, I think its possible. If you see my example twitter_cron.php look carefully the code. This is the cron script that publish post to twitter. Run this code in your localhost and in the place $to = new TwitterOAuth($consumer_key, $consumer_secret, $token, $secret); replace php variablea with hard-coded value. The value of consumer_key and consumer_secret are the keys you’ll get when you’ll register the app in twitter. And after some authentication you’ll see $token and $secret key will be saved in database if you follow my procedure. I think you have to just modify twitter_cron.php’s code for this purpose.
thanks
Hey Ahsan,
you are just amazing.
Hats off to you!
hey ahsan,
you are too good man!!
btw wanted a small help… can u tell me how can i publish tweets of my followers using Streaming API??
@prateek, I wish I could help you, but for some months I was not in touch with twitter api.
Hai…really great demo……
Can You show the code to automatically display profile information(twitter user) when he login to my site through his(user’s) previous oauth_access_token & oauth_access_token_secret which already save to database.
Only the Next time visitor(user)’s code.I mean How to use the oauth_access_token & oauth_access_token_secret of database reuse and display user infor with authenticate again…
Like ping.fm site..
@james, if you save user’s oauth_access_token and oauth_access_token_secret then next time you just need to set them to $token and $secret like
Then you can easily get information from your user or can do other tasks behalf of user.
Hi Dear,
I go the following ERROR… from your above code…
Woah there!
This page is no longer valid. It looks like someone already
used the token information you provided. Please return to the site that sent you to this page and try again … it was probably an honest mistake.
I modified the twitter.php… as following code
$token=$result[0]['twitter_token'];// retrieve token from DB $secret=$result[0]['twitter_secret'];// retrieve token secret from DB if($secret!=""){ $to = new TwitterOAuth($consumer_key, $consumer_secret, $token, $secret); } else{ $to = new TwitterOAuth($consumer_key, $consumer_secret); } //$to = new TwitterOAuth($consumer_key, $consumer_secret); $tok = $to->getRequestToken(); $request_link = $to->getAuthorizeURL($tok); $_SESSION['oauth_request_token'] = $tok['oauth_token']; $_SESSION['oauth_request_token_secret'] = $tok['oauth_token_secret']; header("Location: $request_link");Can you suggest me… where I caught as wrong…
Dear mahmud ahsan,
Sorry I was wrong!!!!
But When I tried it with your “twitter_cron.php”, as i execute the file I got the result…
really Nice Demo….
It appreciate me….
Anyway thanks Again………………. work so far..
Keep update new tutorials…
Hello Mahmud!
I am really impressed with your work.. you are awsome.. will keep my comments for later.
here i have some questions..
in the code below; do you have sql injection in mind? i dont think so.. i dont see any unescape_real_string like functions.. can you give the live web link for it to try some sql injection
.. just kidding..
also can you show us how to implement oauth in our own application.. or any secure authentication mechanism..
Thanks in advance..
I left that security related code for you. That is your homework.
Impressive ! I would like to attachenter a image to illustate your fantabulous article, but I don’t see how to do ? Can someone assist me ?