Connect Twitter API with OAuth using PHP.
Wall Script
Follow Me:
Thursday, February 25, 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

Was this article helpful?
Thanks! Your feedback helps us to improve 9lessons.info


82 comments:

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

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

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

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

    ReplyDelete
  5. Great post and very usefull,thank you!

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

    ReplyDelete
  7. grt :) thanks for posting this :)

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

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

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

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

    ReplyDelete
  12. 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 :)

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

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

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

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

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

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

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

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

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

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

    Can you help us?

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

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

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

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

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

    ReplyDelete
  28. This comment has been removed by the author.

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

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

    ReplyDelete
  31. anjali

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

    Please help.

    ReplyDelete
  32. @Will

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

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

    ReplyDelete
  33. 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/

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

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

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


    thank's before...

    ReplyDelete
  37. awesome tutorial! thanks for taking time to write these

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

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

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

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

    Please, help!

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

    Give valid $consumerKey, $consumerSecret

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

    any solutions?

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

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

    ReplyDelete
  45. yes please! We have no "post_statusesUpdate"

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

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

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

    ReplyDelete
  48. Yess, I've done it

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

    ReplyDelete
  50. 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 )

    ReplyDelete
  51. 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 ??

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

    ReplyDelete
  53. thanks man it will help me in my new project.

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

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

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

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

    ReplyDelete
  58. Can i use stored token again to update status for offline user ?

    For 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

    ReplyDelete
  59. Hi Dude,

    Nice 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/

    ReplyDelete
  60. in the passcode that placed vareable

    ReplyDelete
  61. I have two problems when they approve the palicacion I get a PIN,

    and the other in the file confirm I get You are not logged in, I do

    ReplyDelete
  62. Fatal error: Class 'EpiOAuth' not found in /home/a5956712/public_html/a/EpiTwitter.php on line 2

    ReplyDelete
  63. Need help getting more than 20 status with Epitwitter....get_statusesUser_timeline() gives me only the recent 20 statuses

    ReplyDelete
  64. hey Srinivas, can i use twiiter api as offline_access kinda posting twwets of my clients like facebook

    ReplyDelete
  65. how i can get screen name of a user?

    ReplyDelete
  66. When posting a tweet:

    $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 ) ) )

    ReplyDelete
  67. I get the following:
    Array ( [errors] => Array ( [0] => Array ( [message] => Sorry, that page does not exist [code] => 34 ) ) )

    ReplyDelete
  68. Hi! !

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

    ReplyDelete
  69. Thank you for your script

    ReplyDelete
  70. Can i use stored token again to update status for offline user ?

    ReplyDelete
  71. a very nice and informative guide for programmers. Good work flow of the tutorial. Expecting some more interesting tutorials.

    ReplyDelete
  72. Getting the following error :

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

    ReplyDelete
  73. the script work perject, thanks you

    ReplyDelete

Make in India