How to Post on Twitter from your Website using OAuth

How to Post on Twitter from your Website using OAuth

27 354

Twitter crossposter with OAuth

Recently (seems in august of 2010) Twitter was changed, and now it doesn’t support basic authentication (as usual via CURL), all authentication is done via OAuth.  In this article I made tutorial how to create crossposter to Twitter (using Twitter OAuth).

Here are samples and downloadable package:

Live Demo

Ok, download the example files and lets start coding !


Step 1. HTML

As usual, we start with the HTML.

I prepared several templates which we will use. First template for guests only.

templates/twitter_login.html

<h3>Hell Guest, <a href="tw_login.php">Login to Twitter</a></h3>

Next template – post form for logged members.

templates/twitter_post.html

<h3>Hello @__twitter_name__</h3>
<hr />
<form method="post">
    <table>
        <tr>
            <td valign="top">What`s happening?</td>
            <td><textarea name="message" rows="4" cols="75" class="input_area"></textarea></td>
        </tr>
        <tr>
            <td></td>
            <td><small>(Twitter will trucate your tweet if your tweet size exceed 140 characters limit.)</small></td>
        </tr>
        <tr>
            <td></td><td><input type="submit" name="post" value="Tweet" /></td>
        </tr>
    </table>
</form>

And last one – nice twitter widget which allow us to see posts of members. We will use it to see out posts.

templates/twitter_widget.html

<img src="http://www.script-tutorials.com/logo-tuts.png" alt="logo">

<script src="http://widgets.twimg.com/j/2/widget.js"></script>
<script>
new TWTR.Widget({
  version: 2,
  type: 'profile',
  rpp: 10,
  interval: 6000,
  width: 'auto',
  height: 300,
  theme: {
    shell: {
      background: '#333333',
      color: '#ffffff'
    },
    tweets: {
      background: '#000000',
      color: '#ffffff',
      links: '#4aed05'
    }
  },
  features: {
    scrollbar: true,
    loop: false,
    live: false,
    hashtags: true,
    timestamp: true,
    avatars: true,
    behavior: 'all'
  }
}).render().setUser('__twitter_name__').start();
</script>

Step 2. SQL

We will need to execute next SQL in our database. In this case we will storing oauth info of members.

CREATE TABLE `atwitter_oauth_users` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `oauth_provider` varchar(10),
    `oauth_uid` text,
    `oauth_token` text,
    `oauth_secret` text,
    `username` text,
    PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

Step 3. PHP

Now is most interested, functional itself

Used libraries I put to ‘inc’ folder, this is OAuth.php and twitteroauth.php files. I don`t will include source code of these libraries in this article, here are many code, both libraries located in our package.

Our first file – just config file, containing Twitter consumer Key and Secret plus database details

Important, you will need to register your own application and obtain Twitter consumer key and secret code at http://dev.twitter.com/apps/new

During registering you will need point to callback url (http://www.yoursite.com/tw_login.php), also select ‘Read & Write’ to allow posting to your twitter, next fields like application URL can be like http://www.yoursite.com/

Here are my result with these settings:
settings

inc/header.php

$sConsumerKey    = 'YOUR_TWITTER_CONSUMER_KEY';
$sConsumerSecret = 'YOUR_TWITTER_CONSUMER_SECRET';

$sDbName = 'YOUR_DATABASE_NAME';
$sDbUserName = 'YOUR_DATABASE_USERNAME';
$sDbUserPass = 'YOUR_DATABASE_USER_PASS';

Next file – our main file. This file will draw ‘Hello guest’ for guests, and when we logged it it will show our posts from Twitter plus form where we can Tweet out thoughts. Hope that code very understandable

index.php

// set error reporting level
if (version_compare(phpversion(), "5.3.0", ">=") == 1)
  error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
else
  error_reporting(E_ALL & ~E_NOTICE);

require_once('inc/header.php');

session_start();

echo '<link rel="stylesheet" href="templates/css/main.css" type="text/css" />';

// cross posting
if($_POST['post']) {
    $sPostingRes = "<h3><div class='success'>Your tweet not posted to Twitter (error happen)</div></h3>";

    $bPostRes = performTwitterPost($_POST['message']);

    if ($bPostRes) {
        $sPostingRes = "<h3><div class='success'>Your tweet has posted to Twitter</div></h3>";
    }
    echo $sPostingRes;
}

if ($_SESSION['oauth_username'] != '') {

    $aTmplWidgValues = array(
        '__twitter_name__' => $_SESSION['oauth_username']
    );
    $sFileWidgContent = file_get_contents('templates/twitter_widget.html');
    $aWidgKeys = array_keys($aTmplWidgValues);
    $aWidgValues = array_values($aTmplWidgValues);
    echo str_replace($aWidgKeys, $aWidgValues, $sFileWidgContent); // draw widget

    $aTmplFormValues = array(
        '__twitter_name__' => $_SESSION['oauth_username']
    );
    $aFormKeys = array_keys($aTmplFormValues);
    $sFileFormContent = file_get_contents('templates/twitter_post.html');
    $aFormValues = array_values($aTmplFormValues);
    echo str_replace($aFormKeys, $aFormValues, $sFileFormContent); // draw posting form

} else {
    require_once('templates/twitter_login.html'); // draw login
}

function performTwitterPost($sMessage) {
    global $sConsumerKey, $sConsumerSecret;

    require_once('inc/twitteroauth.php');
    $oTweet = new TwitterOAuth($sConsumerKey, $sConsumerSecret, $_SESSION['oauth_token'], $_SESSION['oauth_secret']);
    $oTweet->post('statuses/update', array('status' => $sMessage));
    return true;
}

Next two files we will using for authentication of members using TwitterOAuth

tw_login.php

require_once('inc/header.php');
require_once('inc/twitteroauth.php');

global $sConsumerKey, $sConsumerSecret;

session_start();

$oTwitterOauth = new TwitterOAuth($sConsumerKey, $sConsumerSecret);
$aRequestToken = $oTwitterOauth->getRequestToken('http://www.yoursite.com/tw_oauth.php'); // getting authentication tokens

// saving token params into the session
$_SESSION['oauth_token'] = $aRequestToken['oauth_token'];
$_SESSION['oauth_token_secret'] = $aRequestToken['oauth_token_secret'];

if($oTwitterOauth->http_code==200) { // in case of success
    $sUrl = $oTwitterOauth->getAuthorizeURL($aRequestToken['oauth_token']); // generate authorization url
    header('Location: '. $sUrl); // redirecting
} else {
    die('Error happened due authorization');
}
require_once('inc/header.php');
require_once('inc/twitteroauth.php');

global $sConsumerKey, $sConsumerSecret;

session_start();

if (! empty($_GET['oauth_verifier']) && ! empty($_SESSION['oauth_token']) && ! empty($_SESSION['oauth_token_secret'])) {
} else { // some params missed, back to login page
    header('Location: http://www.yoursite.com/tw_login.php');
}

$oTwitterOauth = new TwitterOAuth($sConsumerKey, $sConsumerSecret, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);

$aAccessToken = $oTwitterOauth->getAccessToken($_GET['oauth_verifier']); // get access tokens

$_SESSION['access_token'] = $aAccessToken; // saving access token to sessions

$oUserInfo = $oTwitterOauth->get('account/verify_credentials'); // get account details

if(isset($oUserInfo->error)){
    header('Location: http://www.yoursite.com/tw_login.php'); // in case of any errors - back to login page
} else {

    global $sDbName, $sDbUserName, $sDbUserPass;
    $vLink = mysql_connect('localhost', $sDbUserName, $sDbUserPass);
    mysql_select_db($sDbName);

    $vOAuth1 = mysql_query("SELECT * FROM `atwitter_oauth_users` WHERE `oauth_provider` = 'twitter' AND `oauth_uid` = '{$oUserInfo->id}'"); // searching for user in database
    $aOauthUserInfo = mysql_fetch_array($vOAuth1);

    if (empty($aOauthUserInfo)) { // if user info not present - add them into database
        mysql_query("INSERT INTO `atwitter_oauth_users` (`oauth_provider`, `oauth_uid`, `username`, `oauth_token`, `oauth_secret`) VALUES ('twitter', {$oUserInfo->id}, '{$oUserInfo->screen_name}', '{$aAccessToken['oauth_token']}', '{$aAccessToken['oauth_token_secret']}')");
        $vOAuth2 = mysql_query("SELECT * FROM `atwitter_oauth_users` WHERE `id` = '" . mysql_insert_id() . "'");
        $aOauthUserInfo = mysql_fetch_array($vOAuth2);
    } else {
        mysql_query("UPDATE `atwitter_oauth_users` SET `oauth_token` = '{$aAccessToken['oauth_token']}', `oauth_secret` = '{$aAccessToken['oauth_token_secret']}' WHERE `oauth_provider` = 'twitter' AND `oauth_uid` = '{$oUserInfo->id}'"); // update tokens
    }

    $_SESSION['oauth_id'] = $aOauthUserInfo['id'];
    $_SESSION['oauth_username'] = $aOauthUserInfo['username'];
    $_SESSION['oauth_uid'] = $aOauthUserInfo['oauth_uid'];
    $_SESSION['oauth_provider'] = $aOauthUserInfo['oauth_provider'];
    $_SESSION['oauth_token'] = $aOauthUserInfo['oauth_token'];
    $_SESSION['oauth_secret'] = $aOauthUserInfo['oauth_secret'];

    mysql_close($vLink);

    header('Location: http://www.yoursite.com/index.php');
}

if(!empty($_SESSION['oauth_username'])){
    header('Location: http://www.yoursite.com/index.php'); // already logged, back to our main page
}

Make attention, that in my article I used ‘http://www.yoursite.com/’, of course you will need apply your own URL


Live Demo

Conclusion

Today we learn not very easy lesson, but very useful. Now we will able to implement this tool into our projects to make it more friendly with another networks like Twitter. Good luck!


27 COMMENTS

  1. Hi, I keep getting these errors. Any suggestions?

    Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/HOMEHERE/public_html/twitter/tw_oauth.php on line 32

    Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/HOMEHERE/public_html/twitter/tw_oauth.php on line 37

    Warning: Cannot modify header information – headers already sent by (output started at /home/HOMEHERE/public_html/twitter/tw_oauth.php:32) in /home/keymessa/public_html/twitter/tw_oauth.php on line 51

    • Hello buddy,
      I advice you to check your database connection in inc/header.php file
      plus check, are you using localhost or some external sql server?
      It seems that in your version you was not successfully connected to database.

  2. Thanks for the great script. I am a newbie to php and was wondering if its possible to put tweets in a mysql database and tweet from there through a cron.

    • Yes, of course possible, but, possible twitter have own spam protection, and after X addings you will ban. I not sure, but this is possible too.
      firstly – you will need to create cron-php-sctipt.

  3. There is a limit of 12 updates per hour and 350 oauth requests. Many sites are providing these services but for a price, can you help me build one just for my twitter accounts? Thank you

  4. hello Admin,

    Thanks for the nice script, as am a newbie i have some question to ask?

    1) Twitter provides two types of Key set i) Comsumer Key and consumer secrectkey ii) Access Token (oauth_token) and AccessToken Secret ( oauth_token_secret). Now My Question is where to put the Access Token . can any body explain?
    2) next question is there is no logout in this script? after posting is there any way to logout the script or simple close the window?

    Hoping your kind perusal
    Thaks in advance

    Manik Das
    India

    • Hello Manik,
      1. We don`t will using access token and its secret. We will allow to anybody using our crossposter. So, visitor will login using own details, then, twitter will verify him and give him temp access token and secret code (this information even will saved in your database). So we don`t need using your own access token & secret.
      2. For what? Visitor will like to continue posting, isn`t it? If you want to force logout – you can cleanup its SESSIONS params

  5. Thanks. I understood

    thanks again for the nice script.

    Now a small request for future, can we see any mobile & desktop application like this

    Thanks and regards
    Manik Das

  6. Hi
    I setup the script and received the “Error happened due authorization” when I click to “Hell Guest, Login to Twitter”

    php-error log shows following record:

    PHP Notice: Undefined index: oauth_token in …\tweet\inc\twitteroauth.php on line 82
    PHP Notice: Undefined index: oauth_token_secret in …\tweet\inc\twitteroauth.php on line 82
    PHP Notice: Undefined index: oauth_token in …\tweet\tw_login.php on line 14
    [25-Apr-2011 14:33:59] PHP Notice: Undefined index: oauth_token_secret in …\tweet\tw_login.php on line 15

    Any help is appreciated. Thanks.

  7. 2Sait
    Firstly you can set custom php warning level inside tw_login.php file (in beginning):
    // set error reporting level
    if (version_compare(phpversion(), ’5.3.0′, ‘>=’) == 1)
    error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
    else
    error_reporting(E_ALL & ~E_NOTICE);

    also, try to ping twitter server too, maybe it unavailable to you?

  8. It’s no longer working, twitter must have changed their oath system. Awesome script anyways, just a few lines that need to be changed.

    • Hi,
      Yes, you are right, they could change a lot of inner things in their API, so I suppose that before you use our demo – it is better to update codes (to use the most fresh versions)

  9. Bro i downloaded your script but its not working it showing me an error of
    Fatal error: Call to undefined function curl_init()
    resovle it bro

  10. Hello Admin,

    Your demo project is not working.Please let me know that what error in the code causing this problem.Because i want to integrate this in my website.Please be fast to answere.

    Thanking You

    Regards!
    Afzal

    • Hi Afzal,
      I fixed our work, however, it was related with the fact that Twitter updated their API from v1 to v1.1.
      I had to modify the twitteroauth.php file to get it works with Twitter API v1.1 (instead of making changes in this file, you may just download it from twitter)

  11. HI,

    Thank you for the amazing script, however, I am facing an issue. I downloaded the code and updated config file to include my app consumer key and secret. I also updated the php files to replace yourwebsite with correct url. However, when I run the script, I get this error:
    PHP Parse error: syntax error, unexpected $end, expecting ‘(‘ in /twitterlogin/inc/OAuth.php

    I have not modified the OAuth.php and I have no idea why I see this error. Please help.

    Thanks!

  12. Hello,

    My apologies. Please remove the comment – the error was on my part. However, I have a new issue: The table is not getting updated/inserted. I have replaced localhost with my hosting company\’s provided server but nothing is happening. I dont even see SQL errors. I am truly lost and would really appreciate some help.

    Thanks

    • Please remove my above two comments. After 4 hours of debugging, this is the real issue that broke my page and caused mysql not to work. {$oUserInfo->id} and {$oUserInfo->screen_name} are returning no values and are being stored in the database. Can you please help me? Please please please…

      My apologies for so many comments…

      • Hello AG,
        Don’t worry, that’s good that you share your own process with us. Try to check your twitter api credentials: make sure that it doesn’t contain any extra blank spaces. You can also print_r all params from $_GET (tw_oauth.php)

  13. Does this tutorial still work? When I put it on my site and replace the URLs and Keys with my own, it doesn’t work anymore. Help please!

    • Hello Tomi,
      You need to share the post to unlock the package. Please find the corresponding section in the beginning of this tutorial
      What sharing method did you use?

Leave a Reply