9lessons programming blog
Loading Search
Friday, February 26, 2010

Connect Twitter API with OAuth using PHP.

Few days back I had connected labs.9lessons application to twitter API via OAuth (open protocal secure authorization). In this post I want to explain how to store twitter oauth_token and secret values in to database and how to update status with your own web application.

Connect Twitter API with OAuth using PHP.

Download Script     Live Demo

Database
Here storing twitter authorization token keys. MySQL users table columns uid, uname, passcode, oauth_token, oauth_token_secret
CREATE TABLE users
(
uid INT PRIMARY KEY AUTO_INCREMENT,
uname VARCHAR(50) UNIQUE,
passcode VARCHAR(50),
oauth_token VARCHAR(90),
oauth_token_secret VARCHAR(90)
);


How it works at labs.9lessons
Take a look at this video.

confirm.php
Callback URL - return to after successfully authentication?
include 'db.php';
include 'EpiCurl.php';
include 'EpiOAuth.php';
include 'EpiTwitter.php';
include 'secret.php';
$Twitter = new EpiTwitter($consumerKey, $consumerSecret);
if(isset($_GET['oauth_token']) || (isset($_COOKIE['oauth_token']) && isset($_COOKIE['oauth_token_secret'])))
{
// Twitter  user accepted access
if( !isset($_COOKIE['oauth_token']) || !isset($_COOKIE['oauth_token_secret']) )
{
// user comes from twitter
$Twitter->setToken($_GET['oauth_token']);
$token = $Twitter->getAccessToken();
setcookie('oauth_token', $token->oauth_token);
setcookie('oauth_token_secret', $token->oauth_token_secret);
$Twitter->setToken($token->oauth_token, $token->oauth_token_secret);
}
else
{
// user switched pages and came back or got here directly, stilled logged in
$Twitter->
setToken($_COOKIE['oauth_token'],$_COOKIE['oauth_token_secret']);
$user= $Twitter->get_accountVerify_credentials();
$oauth_token=$_COOKIE['oauth_token'];
$oauth_token_secret=$_COOKIE['oauth_token_secret'];

// Storing token keys
$sql=mysql_query("update users SET oauth_token='$oauth_token',
oauth_token_secret='$oauth_token_secret' where username='$user_session'");
header('Location: abc.php'); //Redirecting Page
}
echo "Please re-connect once again <a href=''start.php">click here</a>";
}

This below status(tweet) updated with labs.9lessons.info
update.php
Here $message="Your Status update";
include 'db.php';
include 'EpiCurl.php';
include 'EpiOAuth.php';
include 'EpiTwitter.php';
include 'secret.php';
$tw_sql=mysql_query("select oauth_token,oauth_token_secret from users where user='$user_session'");
$row=mysql_fetch_array($tw_sql);

$oauth_token=$row['oauth_token'];
$oauth_token_secret=$row['oauth_token_secret'];

if(strlen($oauth_token)>0 || strlen($oauth_token_secret)>0 )
{
$Twitter = new EpiTwitter($consumerKey, $consumerSecret);
$Twitter->setToken($oauth_token,$oauth_token_secret);
//$message Status update
$status=$Twitter->post_statusesUpdate(array('status' => $message));
$status->response;
}

If any queries just ask me at facebook.com/srinivas.tamada

db.php
PHP database configuration file
<?php

$mysql_hostname = "Host name";
$mysql_user = "UserName";
$mysql_password = "Password";
$mysql_database = "Database Name";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database, $bd) or die("Could not select database");
?>

Why OAuth
At the time of developing I found some better Twitter API tutorials. Very nice explanation with illustrations
Other technologies code here Oauth.net Code

Book : Twitter API: Up and Running: Learn How to Build Applications with the Twitter API


Join test king for quality web designing online training with testking 640-802 demos and testking 350-001 tutorials to explain how to stock up twitter oauth_token in to database.
Sponsored Links

Share this post

Comments
{ 65 comments }
victor said...

Thanks, awesome!

UrbanTwitch said...

Very nice, as always.

Reequest to be the Facebook connect tutorial. I heard it boosts registration by 15%! A lot of people sign up using Facebook connect if it's on their profile. :-P

Nonetheless, you're amazing. I am gonna subscribe to you in every way possible! Twitter, Facebook, this, RSS, etc.

Keep rocking,
UrbanTwitch

Motyar said...

Again a useful post Sri congrats , which library you are using for it??

Karthik said...

Awesome, thanks a lot.. I will try.. btw, u r using IE? cant believe..

Karthik said...

I want to use Facebook connect thru PHP. Please provide some tutorial on that, if possible. it will be of great use.. Thanks.

Anonymous said...

Great post and very usefull,thank you!

sid said...

Hi, why do not use Abraham Twitteroauth library ?
Epi*.php is better ?

Najeeb Puthiyallam said...

An awesome tut !!!

Siddharth said...

grt :) thanks for posting this :)

organicit said...

Very cool. Even more so that I show up in your friends list in the youtube.

shivani said...

- How can I get list of (the people I follow) && (who have authorized this API) ?

Marius said...

Can you make an full user system based on this? I have a script called Zubee Tube wich we'll badly need this!

Vijay said...

hi srinivas, thanks for the wondeful post.
but, unfortunately it is giving me an error.
Even in the live demo on your site getting the same error. After I click on the "Allow" green button it is taking me to the following url: http://twitter.com/oauth/authorize and getting "temporarly down" error. If I refresh I am getting the below effort.
"Woah there!
This page requires some information that was not provided. Please return to the site that sent you to this page and try again … it was probably an honest mistake."

Really thanks for this srinivas.

Srinivas Tamada said...

@Vijay

Try once again.

Vijay said...

Wow...it actually worked. I didn't change anything I believe. But I am trying from work this time.

Thank you so much, Srinivas.

BTW, in confirm.php I don't see Insert code so added

mysql_query("insert into twitter_user(uname,oauth_token,oauth_token_secret)values('vj','$oauth_token','$oauth_token_secret')");
But, trying to make update.php to work for posting a test message.

Thank you once again :)

kuldeep singh sadioura said...

nice post bro i have also created one without oauth and needs no user password just the username try this out..that script is just for getting timeline of that profile check it out here

http://phpprogs.blogspot.com/2010/05/getting-twitter-homeline-using.html

ebottabi said...

@Srinivas Tamada, what do one has to do in order to keep the user's data, such that we don't have to get to twitter everytime to authenticate, just like it happens on the labs.9lessons.info section, i tried everytime i have to get to twitter for oauth authentication..
thanks for the help

Marius Patrascu said...

I wanna backup @ebottabi ... how do you setup an local cookie for an user that has authentificated trought Twitter?

Anonymous said...

uhm...i got a error message.
"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."

What is it?

Hariez said...

thank you, this is very nice tutorial. and i like it.
But I still do not understand about oauth_token and oauth_token_secret which had been entered into the database. is it the same between oauth_token with consumer_key and consumer_secret with oauth_token_secret?

thank you and so sorry if my english is bad,
:(
i use google translate to translate my language to english, i'm from indonesia. thank you..

Akram Quraishi said...

@Hariez

consumer_key and consumer_secret is the access credentials for your App on Twitter. Where as the oauth_token and oauth_token_secret is the credentials for the twitter user that is return by Twitter after authentication.

Every time when you have to push a status update for a user, u don't need his username/password u have to use the oauth_token and oauth_token_secret.

Srinivas, Thanks a bunch. You saved me a lot of time.

Regards,
Akram

Anonymous said...

Thanks a lot. This is very helpful; greatly appreciated!!

Thomas van Broekhoven said...

Hi,

It works almost fine. There is only one problem; As soon as I go to confirm.php my website lost all the sessions, so I can't put the oauth_token and oauth_token_secret in the database, how did you fix that with 9lessons.lab?

Thanks a lot.
Gr. Thomas

Fardhie said...

This information not for Business, also not to look for Money,but to share Phenomenon to us all.
http://twitter.com/fardhie

mike said...

Outstanding work to have Twitter and PHP both. As much accounts on Twitter it can manage and get updated to your followers. just Log on to the Link Behind.

gioffry said...

Srinivas thank you
but I've the same problem of Thomas van Broekhoven.

Can you help us?

Ryan said...

Nice tutorial! And thanks for the other Twitter API articles links.Very helpful.

Anonymous said...

I'm fail even to get oauth_token, 401.
and secret.php in zip file.
you should change the var name as consumerKey from consumer_key , as well Secret also.

let me get old version and test again.

BTW great job , thank you.

Reinhard said...

Hi, I use above script - mostly correct i.e. authorisation, but have a problem with the update.php -> can't get a statusupdate ???
Any idea or help?
tks a lot brgds from germany / reinhard

Balaguru said...

Hi Friends,
I am getting this type of error "Request token must be exchanged for an access token before use" while posting a message.

Please advice how to resolve this.

Anonymous said...

thank u

seetha said...

every thing is working fine,
can u make this working in codeignitor

player said...
This comment has been removed by the author.
player said...

wht mistake i have done. and how do i debug the error "not logged in". Please guide.

Will S said...

my $token does not have a oauth_token so it just goes to https://api.twitter.com/oauth/authorize?oauth_token= any ideas?

mytvstation said...

anjali

twitter returns me the same oauth_token and oauth_token_secret every time...

Please help.

Auto Expert in CA East Bay said...

Nicely explained. Thank you.

Suhaib Malik said...

@Will

Do the following changes in secret.php
$consumer_key
$consumer_secret

I did the above mentioned changes and it worked well :))

Bas Matthee said...

For the dutch readers, there's a dutch version of a similar article right here:

http://bas-matthee.nl/2011/01/17/met-php-een-tweet-plaatsen-op-twitter-met-oauth/

Richard said...

Can anyone confirm that this works as it is to store the tokens. It looks like there is a mixed use of $consumer_key and $consumerKey

Any other changes?

hiren said...

hello,
I get my consumerKey and consumerSecret key both and i set it in secret.php file then after i get some twitter error like:

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.


what i do? please help me.

YonGun Blog's said...

can you share about connect Facebook API use PHP language.....


thank's before...

scape said...

awesome tutorial! thanks for taking time to write these

Anonymous said...

When i click on add twitter account the link is this:http://twitter.com/oauth/authorize?oauth_token=

What do i wrong? I fillt in secret.php

Anonymous said...

There are 2 differtens confirm.php 's Which one is the right one?

Anonymous said...

http://twitter.com/oauth/authorize?oauth_token=

What's the promlem?
I've fixed all files, but it doesn't work...

Please, help!

Srinivas Tamada said...

Download script updated

Srinivas Tamada said...

http://twitter.com/oauth/authorize?oauth_token=

Give valid $consumerKey, $consumerSecret

Anonymous said...

is there any problem at mysql table? when i try to confirm.php always getting "You are not logged in"

any solutions?

mujaffar said...

yahooooooooooooooooo This is worked me
Thanks for posting this
since one month i am finding such type of code but not got the success
and now by this code it worked for me

The message "You are not logged in" could be come because you not set the page callback properely
thats why it happen
if you set the page call back to
YOURDOMAIN / PATH TO FOLDER/confirm.php then it works fine

Thanks
mujaffar

A-Kay said...

Where did you get the "post_statusesUpdate" method from.. its not in the downloadable scripts.

Anonymous said...

yes please! We have no "post_statusesUpdate"

Anonymous said...

i can't connect my web to database..can u help me...

Anonymous said...

"Notice: Undefined index: port in EpiOAuth.php in line no. 147"

I m getting this error...
what to do? please help me

Dhaval said...

Yess, I've done it

Anonymous said...

If you are using characters like: š, č, or ž Twitter API returns this:
Array ( [error] => Could not authenticate with OAuth. [request] => /statuses/update.json )

Lucifix said...

If you're using characters like š, č or ž when posting status twitter api returns you this error:
Array ( [error] => Could not authenticate with OAuth. [request] => /statuses/update.json )

Palak said...

Hi,
I download the script.I set my call back url to http://mydomain.com/Oauth_9lessons2/confirm.php in my twitter application.

when I start with start.php it take me to login of twitter but when i logged in into the twitter it take me to the confirm.php file but it is blank and also it didn't insert any row to the db.the return url which I got is below.

http://mydomain.com/Oauth_9lessons2/confirm.php?oauth_token=UpexbKqb0Ox7TtvBbzCzWWguCgdT4uwbDYzP9OWSbKw&oauth_verifier=ZSnLbipWTWnPD0aakxxZ9PLhmQTcojewMEgnBrrKQ

Please guide me where I was wrong ??

xorcista said...

please how to make a update of status on twitter ?.. i try used the dode but don't work, help me please Srinivas :]

mukul said...

thanks man it will help me in my new project.

Anonymous said...

hmmmm, is there a way to make it like... If a user posts message in your shoutbox, it will update status on the certain twitter account, my account

ilaçlama said...

I was looking for. Thanx

Himanshu Jaju said...

please tell me how to use get_friendsIds .... it is giving me Not authorized to use this endpoint error...

Selena Gomez said...

I am impressed with this article, so informative to learn a lot and share with my close friends and colleagues

diensh said...

I want to change some text on the website into another language with google api translate using php like that "THIS IS A CAT" and i want to change only "CAT" word into another language

pls help on this topic

DINESH

Post a Comment

Subscribe now!Recent Posts

Categories

Subscribe now!Popular Posts

People Says

@9lessons thank you for the great tutorials, we truly appreciate your contributions to the design community.

Smashing Magazine

Like Me

follow me
products

9lessons labs

9lessons clouds

Android application

Chrome Extension