Develop auto post publishing twitter app

twitterTwitter 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:

  1. Create an offline authentication system
  2. Develop an admin system to add posts in database
  3. Write a php script that will publish the posts in twitter
  4. 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:

Check out the flow  chart to learn how oAuth works with Twitter


Lots of talking :P, now come to the point.

First visit 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: . So we will create 4 files


So in the form set Application Website ‘’ .  Set Callback Url ‘’.

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

$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 */


Now write this code in twitter.php


    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

     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");

For database usage I use a model.php file for database connection and insert/update/delete and query purpose.

         * @author: Md. Mahmud Ahsan
         * @visit:
         * @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());


    function closeDb(){

    function query($sql){
        $data      =  array();
        $result    =  mysql_query($sql);

        if (!empty($result))
        $rows      =  mysql_num_rows($result);
        $rows      =  '';

        if (!empty($rows)){
            while ($rows = mysql_fetch_assoc($result)){
                $data[]   = $rows;

        return $data;

    function insert($sql){
        $result    =  mysql_query($sql);
        return $result;

    function insertAndGetId($sql){
        $result    =  mysql_query($sql);
        $id        =  mysql_insert_id();
        return $id;

    function update($sql){
    function delete($sql){
        return mysql_affected_rows();

Create a database table, which table you’ll use for saving your apps configuration key for future purpose.

CREATE  TABLE `options` (
`twitter_token` VARCHAR(200) NULL ,
`twitter_secret` VARCHAR(200) NULL ,
`created` DATETIME NULL ,
`updated` DATETIME NULL ,
PRIMARY KEY (`appid`) )

Now put below code in twitter_authorization.php.


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'];

$sql=   "INSERT into options (appid, twitter_token, twitter_secret, created, updated)
 values (1, '$token', '$secret', NOW(), NOW())";

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.

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('', $params, 'POST'));
catch(Exception $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.

mahmud ahsan

Computer programmer and hobbyist photographer from Bangladesh, lives in Malaysia. My [Github | Business | Twitter | Linkedin | Youtube | Instagram | 500px]

You may also like


  • Tracee Hegre
    December 18, 2009 at 4:58 am

    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.

  • Donnie Evertsen
    December 20, 2009 at 4:35 am

    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!

  • Vladimir
    December 22, 2009 at 9:06 pm

    Thank you for useful information

  • buxscorner
    December 26, 2009 at 11:44 pm

    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

    • mahmud ahsan
      mahmud ahsan
      December 27, 2009 at 12:17 am

      @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.


      • sushanta sahoo
        April 24, 2012 at 4:38 pm

        hi aushan,
        how can i implement facebook login integration in mvc3.

  • Gaurav
    April 10, 2010 at 2:12 am

    Hey Ahsan,
    you are just amazing.

    Hats off to you!

  • prateek
    May 6, 2010 at 2:17 am

    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??

  • mahmud ahsan
    mahmud ahsan
    May 6, 2010 at 3:26 am

    @prateek, I wish I could help you, but for some months I was not in touch with twitter api.

  • james
    May 10, 2010 at 5:17 pm

    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 site..

  • mahmud ahsan
    mahmud ahsan
    May 10, 2010 at 11:45 pm

    @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

    $token = $oauth_access_token; //from database
    $secret= $oauth_access_token_secret; //from database
    $to = new TwitterOAuth($consumer_key, $consumer_secret, $token, $secret);

    Then you can easily get information from your user or can do other tasks behalf of user.

  • James
    May 11, 2010 at 3:15 pm

    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
    $to = new TwitterOAuth($consumer_key, $consumer_secret, $token, $secret);
            $to = new TwitterOAuth($consumer_key, $consumer_secret);
        //$to = new TwitterOAuth($consumer_key, $consumer_secret);
        $tok = $to-&gt;getRequestToken();
        $request_link = $to-&gt;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…

  • james
    May 11, 2010 at 6:40 pm

    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…

  • Fayyaz Ali
    June 29, 2010 at 5:10 am

    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..

    • mahmud ahsan
      mahmud ahsan
      June 29, 2010 at 10:24 am

      I left that security related code for you. That is your homework.

  • Auto Glass Shop
    July 30, 2010 at 5:28 pm

    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 ?

  • Neo
    September 24, 2010 at 11:45 pm

    Thank you, so helpful.

  • Rare Records
    October 21, 2010 at 6:06 pm

    Very nice, any way to do this with

  • Orval Rouhoff
    October 23, 2010 at 1:00 pm

    Thank you for taking this possibility to talk about this, I feel strongly about this and I make use of studying this subject. If at all, as you gain data, please update this site with new information. I have discovered it extremely useful.

  • Ronald
    November 23, 2010 at 12:30 pm

    I run in some problems. Everything seems to be correct, but nothing is posted!
    I added some echo commands for debugging in twitter_cron.php and run it directly from the web browser. The following lines produce the correct values:

    $status = “My status”;

    try {
    echo “status=$status”;
    echo “c_k=$consumer_key c_s=$consumer_secret

    $to = new TwitterOAuth($consumer_key, $consumer_secret, $token, $secret);

    $params = array(‘status’ => $status);
    $do_dm = simplexml_load_string($to->OAuthRequest(‘’, $params, ‘POST’));

    What do I miss?

    • Ronald
      November 24, 2010 at 8:38 am

      Anybody? I am still out of luck!

  • Andrew M
    November 24, 2010 at 2:53 am

    One thing to note also is the database connector class – model.php – should retain a pointer to the actual database connection socket ( $link ) as an instance variable, so when you later call the closeDb() function you can pass in the same connection that you just opened. Without that reference it just closes a random connection, and will leave many open connections. It is not noticeable unless the application is under load, but then rapidly completely falls apart.

  • jim fragile
    December 16, 2010 at 12:07 pm

    wow this is very useful. is this possible to integrate linkedin login into wordpress blog?thanks

  • subakar prabhu
    December 22, 2010 at 11:05 am

    Hello Mahmud!

    Really nice attempt….can i apply the same mechanism for facebook too?does it work?gonna to try….infact i looking for oauth2.0 manual to develop authentication for websits, but still i did get that one, If you havin plz send it to Hope you aware of facebook firm’s updation, now they migrate to Oauth2.0 protocol from present mechanism.

  • Steinar Knutsen
    January 7, 2011 at 7:56 am

    I keep getting this error when I load twitter.php:

    Parse error: syntax error, unexpected T_STRING in twitter.php on line 4

    Any idea why?

    • mahmud ahsan
      mahmud ahsan
      January 7, 2011 at 10:07 pm

      Steinar, did you correctly set the library path for twitter in config.php ?

      $config['twitter_library_path'] = 
  • shamsul nizam
    February 28, 2011 at 8:16 am

    I received OAUTH_TOKEN&OAUTH_VERIFIER but nothing happen after that.Could you explain the flow of access_token and how we can update statuses base on your automate apps to tweeter

  • Ronald
    March 14, 2011 at 9:26 pm

    I want to use the same program from multiple twitter accounts.

    Do I need to apply for each twitter account a consumer key/ secret for the same program (same program location) and then go for each one through the request of the authentication tokens?

    1. and click Register a new App

    -> ../twitter.php
    oauth_token= … & oauth_verifier= …

  • Peter
    March 14, 2011 at 9:36 pm

    I follow the instruction above and put all on my local machine, which I can reach as localhost or as…

    I key in the URL …twitter.php and get back:

    Warning: Missing argument 1 for Model::__construct(), called in /media/disk/websites/twitter/TwRo/config.php on line 6 and defined in /media/disk/websites/twitter/TwRo/model.php on line 13

    Warning: Cannot modify header information – headers already sent by (output started at /media/disk/websites/twitter/TwRo/model.php:13) in /media/disk/websites/twitter/TwRo/twitter.php on line 22

    I checked, the database is reachable with that credentials!

    What am I missing ???

    • Paddy O'Hanlon
      April 6, 2013 at 3:09 am

      This fixed it for me:

      function __construct($dbconfig=””)

  • Ronald
    March 15, 2011 at 5:07 pm

    I got everything working, except it is not posting ;-(

    How can I test if these lines are working:

    $twitter->host = “”;


    if(strlen($status) > 140) $status = substr($status, 0, 139);
    $twitter->post(‘statuses/update’, array(‘status’ => $status));

    CONSUMER_KEY, CONSUMER_SECRET I got when I applied for the api keys, these I put into twitter.php
    Then I called this twitter.php and it answered via twitterauthorization, and in the URL I found the

    Any ideas, please?

  • one2pret
    March 25, 2011 at 10:12 am

    thank..this is very help me… yours great… keep posting something nice.

  • y8
    April 3, 2011 at 11:56 pm

    Moving and powerful! You have certainly got a way of reaching people that I haven’t seen very often. If most people had written about this subject with the eloquence that you just did, I’m positive people would do much more than just read, they’d act. Fantastic material here. Remember to keep it up….

  • pradeep
    August 31, 2011 at 11:45 am

    hi ahsan,

    i want to post status on my friends profile without login. means first they will login in their profile to authenticate my app. and then next time i dont want to login them i will automatically post status(tweet) to their profile. do you have idea about this??


  • Majoka
    November 3, 2011 at 4:56 pm

    Great documentation and code.

    Thanks so much……………………………

  • Tiz
    December 30, 2011 at 8:07 pm

    When I run the scripts, Twitter gives me back a PIN that I don’t know how to us it. There is not any other way to make the things working

  • pian
    June 17, 2012 at 6:41 am

    req, how to connect dabr twitter client with facebook? help me?

  • Miguel Acuña
    July 20, 2012 at 11:14 pm

    Can you add a link to download a “DEMO” ?

  • Serg
    August 7, 2012 at 8:33 am

    Thanks for this. Please ca I make such for script like

  • Raka
    August 21, 2012 at 2:05 pm

    i still getting error, why? help me!

    Parse error: syntax error, unexpected T_VARIABLE in /home/********/public_html/twitterOAuth/model.php on line 15

  • Anikk Poddar
    September 21, 2012 at 6:11 pm

    Really beloved stuff! Really beloved this website and stuff, your website is one of my favourites. I like your web content, presented of articles and it has given me some sort of commitment to succeed for some reason, Web Solutions you have been carrying out a praiseworthy job.

  • Vivek
    April 19, 2013 at 8:51 pm

    I am also getting the same error.

    Any solution to it ?

  • Kim
    May 10, 2013 at 2:38 am

    Hi there, just became alert to your blog through Google, and found that it is really informative.
    I’m going to watch out for brussels. I’ll be grateful if you continue this in future.
    Numerous people will be benefited from your writing.

  • indi
    June 27, 2013 at 7:47 pm

    twitter released API Version 1.1 … all old Demo’s stopped working. ;(
    will it work?

  • Kizi 2
    July 15, 2013 at 2:01 am

    Having read this I thought it was extremely informative.
    I appreciate you taking the time and energy to put this short article together.
    I once again find myself spending a significant amount of time both reading and commenting.
    But so what, it was still worth it!

  • Nasser
    March 14, 2014 at 3:32 am

    Salam sir,

    Is there a way to keep my web page run automatically for auto tweet after i save the user information. I mean without visiting my page to fire the sending tweet.

    plz help

Comments are closed here.