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: http://oauth.net/

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

oauth_sign_in_with_twitter

Lots of talking :P, 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:

twitter_new_app

Now fill out this form. I assume that your web site link is: http://mysite.com . So we will create 4 files

  1. http://mysite.com/config.php
  2. http://mysite.com/twitter.php
  3. http://mysite.com/twitter_authorization.php
  4. 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.

About mahmud ahsan

Founder And Lead Programmer at iThinkdiff.net

, , ,

46 Responses to Develop auto post publishing twitter app

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

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

  3. Vladimir December 22, 2009 at 9:06 pm #

    Thank you for useful information

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

      thanks

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

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

  5. Gaurav April 10, 2010 at 2:12 am #

    Hey Ahsan,
    you are just amazing.

    Hats off to you!

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

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

  8. 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 ping.fm site..

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

  10. 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
    
    
    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-&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…

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

  12. 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 June 29, 2010 at 10:24 am #

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

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

  14. Neo September 24, 2010 at 11:45 pm #

    Thank you, so helpful.

  15. Rare Records October 21, 2010 at 6:06 pm #

    Very nice, any way to do this with ping.fm?

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

  17. 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
    t=$token
    s=$secret”;

    $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’));
    }

    What do I miss?

    • Ronald November 24, 2010 at 8:38 am #

      Anybody? I am still out of luck!

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

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

  20. 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 psubakar@gmail.com. Hope you aware of facebook firm’s updation, now they migrate to Oauth2.0 protocol from present mechanism.

  21. 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 January 7, 2011 at 10:07 pm #

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

      $config['twitter_library_path'] = 
      
  22. 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

  23. 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. http://twitter.com/oauth_clients and click Register a new App

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

  24. 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 xxx.dyndns.org/…

    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=””)

  25. 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 = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
    $twitter->host = “https://api.twitter.com/1/”;

    error_reporting(E_ALL);

    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
    ACCESS_TOKEN, ACCESS_TOKEN_SECRET as
    oauth_token=yyyyyyyyyyy
    oauth_verifier=xxxxxxxxx

    Any ideas, please?

  26. one2pret March 25, 2011 at 10:12 am #

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

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

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

    thanks

  29. Majoka November 3, 2011 at 4:56 pm #

    Great documentation and code.

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

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

  31. pian June 17, 2012 at 6:41 am #

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

  32. Miguel Acuña July 20, 2012 at 11:14 pm #

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

  33. Serg August 7, 2012 at 8:33 am #

    Thanks for this. Please ca I make such for Status.net script like Identi.ca???

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

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

  36. Vivek April 19, 2013 at 8:51 pm #

    I am also getting the same error.

    Any solution to it ?

  37. 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.
    Cheers!

  38. indi June 27, 2013 at 7:47 pm #

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

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

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