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.
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)
);
(
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>";
}
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
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;
}
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");
?>
$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
- OAuth FAQ - Twitter Wiki
- Writing your first Twitter application with OAuth
- Twitter OAuth Sign In Tutorial
- How to quickly integrate with Twitter’s OAuth API using PHP
Book : Twitter API: Up and Running: Learn How to Build Applications with the Twitter API
Thanks, awesome!
ReplyDeleteVery nice, as always.
ReplyDeleteReequest 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
Again a useful post Sri congrats , which library you are using for it??
ReplyDeleteAwesome, thanks a lot.. I will try.. btw, u r using IE? cant believe..
ReplyDeleteI want to use Facebook connect thru PHP. Please provide some tutorial on that, if possible. it will be of great use.. Thanks.
ReplyDeleteGreat post and very usefull,thank you!
ReplyDeleteHi, why do not use Abraham Twitteroauth library ?
ReplyDeleteEpi*.php is better ?
An awesome tut !!!
ReplyDeletegrt :) thanks for posting this :)
ReplyDeleteVery cool. Even more so that I show up in your friends list in the youtube.
ReplyDelete- How can I get list of (the people I follow) && (who have authorized this API) ?
ReplyDeleteCan you make an full user system based on this? I have a script called Zubee Tube wich we'll badly need this!
ReplyDeletehi srinivas, thanks for the wondeful post.
ReplyDeletebut, 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.
@Vijay
ReplyDeleteTry once again.
Wow...it actually worked. I didn't change anything I believe. But I am trying from work this time.
ReplyDeleteThank 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 :)
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
ReplyDeletehttp://phpprogs.blogspot.com/2010/05/getting-twitter-homeline-using.html
@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..
ReplyDeletethanks for the help
I wanna backup @ebottabi ... how do you setup an local cookie for an user that has authentificated trought Twitter?
ReplyDeleteuhm...i got a error message.
ReplyDelete"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?
thank you, this is very nice tutorial. and i like it.
ReplyDeleteBut 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..
@Hariez
ReplyDeleteconsumer_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
Thanks a lot. This is very helpful; greatly appreciated!!
ReplyDeleteHi,
ReplyDeleteIt 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
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.
ReplyDeleteSrinivas thank you
ReplyDeletebut I've the same problem of Thomas van Broekhoven.
Can you help us?
Nice tutorial! And thanks for the other Twitter API articles links.Very helpful.
ReplyDeleteI'm fail even to get oauth_token, 401.
ReplyDeleteand 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.
Hi, I use above script - mostly correct i.e. authorisation, but have a problem with the update.php -> can't get a statusupdate ???
ReplyDeleteAny idea or help?
tks a lot brgds from germany / reinhard
Hi Friends,
ReplyDeleteI 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.
thank u
ReplyDeleteevery thing is working fine,
ReplyDeletecan u make this working in codeignitor
This comment has been removed by the author.
ReplyDeletewht mistake i have done. and how do i debug the error "not logged in". Please guide.
ReplyDeletemy $token does not have a oauth_token so it just goes to https://api.twitter.com/oauth/authorize?oauth_token= any ideas?
ReplyDeleteanjali
ReplyDeletetwitter returns me the same oauth_token and oauth_token_secret every time...
Please help.
Nicely explained. Thank you.
ReplyDelete@Will
ReplyDeleteDo the following changes in secret.php
$consumer_key
$consumer_secret
I did the above mentioned changes and it worked well :))
For the dutch readers, there's a dutch version of a similar article right here:
ReplyDeletehttp://bas-matthee.nl/2011/01/17/met-php-een-tweet-plaatsen-op-twitter-met-oauth/
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
ReplyDeleteAny other changes?
hello,
ReplyDeleteI 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.
can you share about connect Facebook API use PHP language.....
ReplyDeletethank's before...
awesome tutorial! thanks for taking time to write these
ReplyDeleteWhen i click on add twitter account the link is this:http://twitter.com/oauth/authorize?oauth_token=
ReplyDeleteWhat do i wrong? I fillt in secret.php
There are 2 differtens confirm.php 's Which one is the right one?
ReplyDeletehttp://twitter.com/oauth/authorize?oauth_token=
ReplyDeleteWhat's the promlem?
I've fixed all files, but it doesn't work...
Please, help!
Download script updated
ReplyDeletehttp://twitter.com/oauth/authorize?oauth_token=
ReplyDeleteGive valid $consumerKey, $consumerSecret
is there any problem at mysql table? when i try to confirm.php always getting "You are not logged in"
ReplyDeleteany solutions?
yahooooooooooooooooo This is worked me
ReplyDeleteThanks 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
Where did you get the "post_statusesUpdate" method from.. its not in the downloadable scripts.
ReplyDeleteyes please! We have no "post_statusesUpdate"
ReplyDeletei can't connect my web to database..can u help me...
ReplyDelete"Notice: Undefined index: port in EpiOAuth.php in line no. 147"
ReplyDeleteI m getting this error...
what to do? please help me
Yess, I've done it
ReplyDeleteIf you are using characters like: š, č, or ž Twitter API returns this:
ReplyDeleteArray ( [error] => Could not authenticate with OAuth. [request] => /statuses/update.json )
If you're using characters like š, č or ž when posting status twitter api returns you this error:
ReplyDeleteArray ( [error] => Could not authenticate with OAuth. [request] => /statuses/update.json )
Hi,
ReplyDeleteI 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 ??
please how to make a update of status on twitter ?.. i try used the dode but don't work, help me please Srinivas :]
ReplyDeletethanks man it will help me in my new project.
ReplyDeletehmmmm, 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
ReplyDeleteI was looking for. Thanx
ReplyDeleteplease tell me how to use get_friendsIds .... it is giving me Not authorized to use this endpoint error...
ReplyDeleteI am impressed with this article, so informative to learn a lot and share with my close friends and colleagues
ReplyDeleteI 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
ReplyDeletepls help on this topic
DINESH
Can i use stored token again to update status for offline user ?
ReplyDeleteFor example :
@user1 token stored and status updated once. Next day am i able to use stored token to update status for @user1 ? OR @user1 need to authenticate again ?
Thanks
Hi Dude,
ReplyDeleteNice Piece of code you have there... I used it on my current project and it works just fine. But I have a question. Using the keys stored in the db How can I Display a already connected to twitter message on the scree?
Would appreciate if you reply fas as I'am in a jiffy of a situation here...
Cheers... \m/
in the passcode that placed vareable
ReplyDeleteI have two problems when they approve the palicacion I get a PIN,
ReplyDeleteand the other in the file confirm I get You are not logged in, I do
Fatal error: Class 'EpiOAuth' not found in /home/a5956712/public_html/a/EpiTwitter.php on line 2
ReplyDeleteNeed help getting more than 20 status with Epitwitter....get_statusesUser_timeline() gives me only the recent 20 statuses
ReplyDeletethank u very much
ReplyDeletehey Srinivas, can i use twiiter api as offline_access kinda posting twwets of my clients like facebook
ReplyDeletehow i can get screen name of a user?
ReplyDeleteWhen posting a tweet:
ReplyDelete$message = "test tweet";
$Twitter = new EpiTwitter($consumerKey, $consumerSecret);
$Twitter->setToken($oauth_token,$oauth_token_secret);
$status=$Twitter->post_statusesUpdate(array('status' => $message));
print_r( $status->response);
I get the following:
Array ( [errors] => Array ( [0] => Array ( [message] => Sorry, that page does not exist [code] => 34 ) ) )
I get the following:
ReplyDeleteArray ( [errors] => Array ( [0] => Array ( [message] => Sorry, that page does not exist [code] => 34 ) ) )
Hi! !
ReplyDeleteI am getting the allow apps by twitter and redirecting to my page as well. But I want to get the twitter tweets posted on timeline. Can you please help me to do this?
Thank you for your script
ReplyDeleteI like to read your blog , Keep Posting
ReplyDeleteCan i use stored token again to update status for offline user ?
ReplyDeletea very nice and informative guide for programmers. Good work flow of the tutorial. Expecting some more interesting tutorials.
ReplyDeleteGetting the following error :
ReplyDeleteThere is no request token for this page. That's the special key we need from applications asking to use your Twitter account. Please go back to the site or application that sent you here and try again; it was probably just a mistake.
Anything changed in the last few hours?
can any one explain in depth because i m new to the twitter apis.
the script work perject, thanks you
ReplyDelete