Creating a Simple Twitter App using oAuth and PHP

 Posted in Tutorials 581 days ago Written by: Abhishek
  • Buffer
  •  140
  • Buffer

Everyone on the web is updating to the latest & the most secure technologies with Twitter being the most hyped one as it upgraded from basic Authentication to the more secure oAuth. Earlier people had to risk their Twitter login credentials if they wanted to use some external Apps that gave them more control over their Twitter profile. Twitter would now be removing the basic Auth to fully support oAuth. As Twitter describes oAuth is:

Creating a Simple Twitter App using oAuth and PHP

OAuth is an authentication protocol that allows users to approve application to act on their behalf without sharing their password. More information can be found at oauth.net or in the excellent Beginner’s Guide to OAuth from Hueniverse.

As the title suggests, today we’ll be making a basic application which updates your Twitter status using oAuth and PHP. So let’s get started without wasting anymore time!

DOWNLOAD THE LIBRARY HERE!

NOTE: I strongly suggest that you should click on each of the screen-shots below, so that you can clearly understand what’s going on!

Before starting up, I also suggest you to read the other article on Updating Twitter using PHP as it has some background information about this article. Read it here!

SETTING IT UP

To get started open up notepad or any other code editor and make three files “index.php, style.css & update.php“. Now download the “download this Twitter oAuth library” made by Jaisen Mathaihere“. It is a ready-made library “stamped” by Twitter’s API (itself) which helps you to connect to Twitter using oAuth. Now place all these files in a folder and they should look something like this:

REGISTERING YOUR APPLICATION ON TWITTER

First of all we’ll need to register an app for you on Twitter so that you get your API keys you’ll use.

After reading that previous statement a question might have taken birth in  your mind, What’s the purpose of  getting these API Keys from Twitter?

We need the API Keys for getting our Application (app) registered on Twitter so that Twitter gives us the right to get the users/visitors authenticated and get their credentials/profile info from Twitter. With the increasing number of Twitter account frauds these days, I think that oAuth is the best step taken by Twitter towards user security. Also, the API keys let Twitter know of the URL where the user will be redirected to after successful authentication/login.

So for that (getting our app registered on Twitter) click here or go to http://twitter.com/apps. Note that you’ll need to login with your Twitter account to register an APP. The registration page that twitter provides is like the one below. I’ll describe everything as we go on!

I have explained the form on the screenshot above so I strongly advise you to have a close look to the form and see what to fill. Below, I have explained all the elements of the file;

  • Application Icon: If you want to give a pictorial representation to your app then this is the way!
  • Application Name: Your application’s name. Be ultra-sure to make it catchy!
  • Description: A small description for your application.
  • Application Website: A direct link to your application’s website. (For reference)
  • Organisation: Your organisation {Your may name your website here}, although not needed.
  • Website: Your Organisation’s website {Your main homepage}, not needed {just for reference}
  • Application Type: This will probably be Browser unless you use Twitter oAuth in a software.
  • Callback URL: The URL where Twitter should redirect a user after successful authentication! {See the screenshot for more}
  • Default Access Type: It should be Read & Write unless you just need to use the profile information of a user.
  • Use Twitter for login: If you are using Twitter as a Login to your website/application then check this otherwise no need!
  • Captcha: That’s the most difficult part! ;) haha..Just a captcha and is required!

After that just click on Save and you’ll be redirected to a page where Twitter will give you your API info. in the form of a Consumer Key & the Consumer Secret Key. The page will look something like the one below:

PREPARING TO MAKE THE APPLICATION

To get started, we’ll first need to fill the API keys, we got from Twitter in our Application’s library so that we don’t get confused later on! To do so open the secret.php file in the lib folder and you’ll see something like below:


<?php
$consumer_key = '<PLACE YOUR CONSUMER KEY HERE>';
$consumer_secret = '<PLACE YOUR CONSUMER SECRET KEY HERE>';
?>

Now just add the Consumer Key & the Consumer Secret you got from Twitter in between the quotes. Below is the copy of the secret.php file that 1stwebdesigner’s Twitter oAuth application is using:


<?php
$consumer_key = 'vUztW1221HktEoi1MD3hxg';
$consumer_secret = '8R7gXaKaGfHHjtMxj6ennJMd0c8esDP4nCsKjiJAk';
?>

These API keys {consumer key, consumer secret} enable Twitter to redirect and process your oAuth request to Twitter for login.

OUR APPLICATION FILES

Index.php: Basically this file will do all our work as it shows the “Sign In Through Twitter” button and then processes all our oAuth request using the oAuth library we are using. Co-incidentally, Twitter also redirects the user to this file after successfull authentication {Remember the screenshot above ?}

Update.php: You’ll update your Twitter status using this file. Uses index.php file for form processing. (Explained below!)

Style.css: Contains all the styles that we’ll use for our application.

WRITING THE APPLICATION

Open the Index.php file you made and add the following code to it:


<?php

session_start();

include 'lib/EpiCurl.php';
include 'lib/EpiOAuth.php';
include 'lib/EpiTwitter.php';
include 'lib/secret.php';

$twitterObj = new EpiTwitter($consumer_key, $consumer_secret);
$oauth_token = $_GET['oauth_token'];
 if($oauth_token == '')
 {
 $url = $twitterObj->getAuthorizationUrl();
 echo "<div style='width:200px;margin-top:200px;margin-left:auto;margin-right:auto'>";
 echo "<a href='$url'>Sign In with Twitter</a>";
 echo "</div>";
 }
 else
 {
 $twitterObj->setToken($_GET['oauth_token']);
 $token = $twitterObj->getAccessToken();
 $twitterObj->setToken($token->oauth_token, $token->oauth_token_secret);
 $_SESSION['ot'] = $token->oauth_token;
 $_SESSION['ots'] = $token->oauth_token_secret;
 $twitterInfo= $twitterObj->get_accountVerify_credentials();
 $twitterInfo->response;

 $username = $twitterInfo->screen_name;
 $profilepic = $twitterInfo->profile_image_url;

 include 'update.php';

 }

if(isset($_POST['submit']))
 {
 $msg = $_REQUEST['tweet'];

 $twitterObj->setToken($_SESSION['ot'], $_SESSION['ots']);
 $update_status = $twitterObj->post_statusesUpdate(array('status' => $msg));
 $temp = $update_status->response;

 echo "<div align='center'>Updated your Timeline Successfully .</div>";

 }

?>

Now I’ll be explaining the whole code used above below (in point form):

  • We start off by firing our session using:

session_start();

The pre-built PHP function that we are usign above just creates a session or resumes the current one.

  • To keep the application as simple as we can we include all the files from the library including the secret.php file:

include 'lib/EpiCurl.php';
 include 'lib/EpiOAuth.php';
 include 'lib/EpiTwitter.php';
 include 'lib/secret.php';

We do so as we’ll be interpreting everything in our index.php file.

  • The rest of the code just helps in getting the user logged in to Twitter using the access tokens.

$twitterObj = new EpiTwitter($consumer_key, $consumer_secret);
 $oauth_token = $_GET['oauth_token'];
 if($oauth_token == '')
 {
 $url = $twitterObj->getAuthorizationUrl();
 echo "<div  style='width:200px;margin-top:200px;margin-left:auto;margin-right:auto'>";
 echo "<a href='$url'>Sign In with Twitter</a>";
 echo "</div>";
 }
 else
 {
 $twitterObj->setToken($_GET['oauth_token']);
 $token = $twitterObj->getAccessToken();
 $twitterObj->setToken($token->oauth_token,  $token->oauth_token_secret);
 $_SESSION['ot'] = $token->oauth_token;
 $_SESSION['ots'] = $token->oauth_token_secret;
 $twitterInfo= $twitterObj->get_accountVerify_credentials();
 $twitterInfo->response;

 $username = $twitterInfo->screen_name;
 $profilepic = $twitterInfo->profile_image_url;

 include 'update.php';

 }

After that we define the variables twitterObj & oauth_token to make it easier for us to connect and authenticate with Twitter. Then we open our if statement and check the oauth_token which is our access tokes for the account that will be authenticated with Twitter. We then redirect the user to Twitter’s authentication page using the $url which is defined in one the library files. The $url is made using the access token and the Twitter oAuth login link. One of the sample $url is:

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

You can clearly see how Twitter well Twitter uses the oauth_tokens. After that we just open our session with Twitter and then get the profile information of the user from Twitter:


$twitterInfo= $twitterObj->get_accountVerify_credentials();
 $twitterInfo->response;

 $username = $twitterInfo->screen_name;
 $profilepic = $twitterInfo->profile_image_url;

Here we defined the twitterInfo variable which is in short getting a user’s profile credentials from the $twitterObj data and then we use the screen_name & profile_image_url functions to get the profile name and profile image of the logged in user. At the same time we are assigning variables to the profile name and profile and profile image which we will use in the update.php file.

After that we are also including the update.php file using the snippet below:

 include 'update.php';

Now copy the code below to your update.php file:


<html>
<head>
<title>Twitter oAuth Application by 1stwebdesigner | Update your status</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen, projection" />

</head>
<body>
<h1>Hello and Welcome to the oAuth Tutorial</h1>
<?php $_SESSION['twitter_profile']; ?>
<div id="form"><!--Start form-->
<p>Twitter Handle: <?php echo $username ?></p>
<p>Profile Picture: <br /><?php echo "<img src='$profilepic' />" ?><br /></p>
<label>Update Twitter Timeline</label><br />
<form method='post' action='index.php'>

<br />
<textarea  name="tweet" cols="50" rows="5" id="tweet" ></textarea>
<br />
<input type='submit' value='Tweet' name='submit' id='submit' />
</form>
</div><!--End Form-->
</body>
</html>

This is just a simple HTML page consisting of small chunks of PHP code for showing the user’s username, profile picture of the user as uploaded on Twitter. The page also consists of a text box which the user can use to update his/her status timeline on Twitter. You might have noticed by now that I am using the index.php file for form processing. The code that processes this form and posts to twitter is the one below (already in our index.php file):


if(isset($_POST['submit']))
 {
 $msg = $_REQUEST['tweet'];

 $twitterObj->setToken($_SESSION['ot'], $_SESSION['ots']);
 $update_status = $twitterObj->post_statusesUpdate(array('status'  => $msg));
 $temp = $update_status->response;

 echo "<div align='center'>Updated your Timeline Successfully  .</div>";

 }

Here we are taking the data from the textbox named tweet and then posting it to twitter and then notifying the user that his/her message was successfully and his/her timeline was updated.

Our style.css file doesn’t have any special styles that we need to discuss here. They were just used to style the update form.

NOTE: You may want to add the character count and limit as Twitter doesn’t accept any Tweets which consists of more than 140 characters {Even from the API}. I have explained it in my previous tutorial on 1stwebdesigner about Updating Twitter using Twitter API and PHP.

You may now download the completed application files here but don’t forget to edit the secret.php file with your API keys as it won’t work without it. Feel free to build on the application we made today!

TWITTER APPLICATIONS YOU USE USING oAUTH

We all know that Twitter provides an easy-to-use interface for its users. The main advantage of using oAuth is that users can see what applications have access to their profiles. If you want to check that then you can do so by:

  • Login through Twitter (web-service).
  • Go to Settings after successful login.
  • Then click on the Connections tab.
  • On that page, Twitter gives a list of all the apps that have access to your profile.

You can check that easily by following the screenshot below:

This is a screen-shot of my Connections page which is showing me all the Twitter websites/applications I have given access to!

FURTHER READING

There’s another great Twitter oAuth library made by @abraham which can be seen in action here and it can be downloaded here. Tutorials regarding that library are available here!

That’s it! If you have anything to add or have a query then feel free to comment on this post. Thanks ;)

 Did you enjoy this article and found it useful?

Article was created by

4

Articles


Hello there! I am Abhishek Bhardwaj and I love to make programs in VB & JAVA. I also love Web-Designing & *Development. I write on my blog @ TutorialsWalk. You can follow me on Twitter!
Free Website
 

 140 Brilliant Comments - Join Discussion Now!

  • Jeffrey Bennett

    Posted 502 days ago
    48

    Hi there! Your demo URL sends me to a page that says “This Account Has Been Suspended”. I would love to see it up and running! Thanks! :)

    Reply
    • Abhishek

      Posted 500 days ago
      49

      Hey, Sorry for the downtime! It was due to a stupid error made by my hosting provider. The tutorial demo is now back up and you can see it running. Sorry once again for the inconvinience!

      Reply
  • Jeff

    Posted 503 days ago
    47

    Hi Abhishek,

    I have used your module for one of my site and it works great on my local pc which has PHP 5.2.9, however, when I use in live server having PHP 5.1.6, the thing is not working.

    I have updated the secret.php for live site as it required, however, in step 1 it self, it does give me like http://twitter.com/oauth/authorize?oauth_token=

    means something is going wrong. Can you please help for this since i am trying it from last 2 days.

    Jeff

    Reply
  • Mike the Pike

    Posted 509 days ago
    46

    Hi just wondering if you have ever pulled posts out fo twitter for website consumption with this. I got this working no problem but really what I want to do it more a twitter2html thing although it uses basic authentication.

    Reply
  • Sebastien

    Posted 521 days ago
    38

    Hey,

    Thanks a lot of this write up. I don’t know why but for some reason oAuth just confuses the heck out of me and this helped quite a bit.

    I do have a question though :) I need each call to have a custom callback page to identify our clients. I know this is possible because near the callback input on the twitter application settings page it explains that I can do so by including a oauth_callback. I tried poking around in your code to see if this was supported somehow but I can’t seem to find it. I have my fingers crossed that you’ll tell me I just need to include it in some sort of parameters array so one of the constructors :)

    Any help would be appreciated and thanks again :)

    Reply
    • Sebastien

      Posted 521 days ago
      39

      For anyone that might have the same problem as me, I solved it by using the code found here: https://docs.google.com/View?docID=dcf2dzzs_2339fzbfsf4

      It’s very similar to the tutorial here (though not explained as well, you might have to dig a little in the code and read his documentation file) but it clearly shows how to define your callback when you request a token. This would allow you to pass along GET variables or go to different domains (which is how I identify clients)

      HTH!

      Reply
      • Abhishek Bhardwaj

        Posted 519 days ago
        44

        Ya, Abraham’s Twitter oAuth library is more user and feature friendly! Jaisen’s library doesn’t supprt that well. There are some tutorials out there on Abraham’s library too which can be found here: http://wiki.github.com/abraham/twitteroauth/links

        Reply
  • Endolino

    Posted 523 days ago
    37

    Hello,
    reading your tutorial will drop some errors in my mind. In my application i wanna only send messages to my twitter account avoiding endless login in with username and password.
    Where i am be able to get the secret password which i can put into the constructor as 3th and 4th argument?

    Reply
    • Abhishek Bhardwaj

      Posted 519 days ago
      42

      Store your tokens and other login credentials in your database!

      Reply
      • Cristian

        Posted 513 days ago
        45

        Please give me a real example (code please!!!) because I’m new in PHP…
        Thank you,
        Cristian

        Reply
  • robbie

    Posted 524 days ago
    35

    Hello … just to give my gratitude at first when i saw this tutorial … i passed it up because it looked very technical …but as the hours passed and the frustration kicked in i came back across … and its brillant exactly what i have been looking for….. BUT of course always a but…. when i follow all the instructions and upload the files i get this parse error ….

    Parse error: syntax error, unexpected T_CONST, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or ‘}’

    … on line 4 of the EpiCurl.php file ….HELP i checked the Phpinfo of my site i have curl enabled and it is quite a late version . Any help would be super appreciated

    Reply
    • Abhishek Bhardwaj

      Posted 519 days ago
      40

      That means that your server has PHP4. This application just works in PHP5!
      But if you have PHP5 then either the cURL extension on that isn’t installed or it isn’t configured properly.

      Reply
  • Marcus

    Posted 528 days ago
    34

    Thanx for this great tutorial!!!
    I´ve been looking for a long time for a code like this!

    Reply
  • Mark

    Posted 540 days ago
    32

    Thanks to you and Jaisan for all the great articles on the Twitter API…
    I seem to missing something, it seems that I can only access twitter by starting from scratch and fails the tokens on repeated access, part of which you may have touched on above about token lives. My question would be is it possible to create an application that can be called as a stand-alone and update my Twitter account without repeating the Twitter authorization each time? (Application would create the new tweets). Would the application have to use basic (curl) login to Twitter prior to creating the access tokens?

    Reply
  • bharath

    Posted 547 days ago
    31

    Thank You i was searching for this in many places you teached me very easily
    Thanks ………..

    Reply
  • cheza

    Posted 552 days ago
    29

    Hi,

    just out of curiosity. How do you verify a user, once you have all the needed tokens, if he revisits your page. Clearly you’d have to – somehow – identify that visitor als the one specific user.

    Actually, in my opinion, at that point you won’t get around asking for twitter screen name and password, which you will have to compare to other screen names and pws which will have to be stored in your DB. => All bonuses of oauth are gone by then… I am currently stuck at that point in developing a twitter app.

    It would be nice if you could point me in the right direction! (even though I am developing with RoR instead of PHP :)!)

    thanks cheza

    Reply
    • Abhishek Bhardwaj

      Posted 519 days ago
      41

      That can be done using a database.
      You’ll have to store the login credentials & tokens in your database. Then if a user revisits the page, you can identify him using the tokens & credentials.

      Reply
    • Terri Ann

      Posted 479 days ago
      54

      After the user verifies with Twitter and the token is passed back the these two lines hold the key to what you need to store in the database:

      $_SESSION['ot'] = $token->oauth_token;
      $_SESSION['ots'] = $token->oauth_token_secret;

      Those two values are used again here:

      $twitterObj->setToken($_SESSION['ot'], $_SESSION['ots']);

      Before posting the status update. Replace the setting of the session super global with any kind-of database set and get functionality and you will be on your way. Everything you need is in that index.php file!

      Reply
  • freak

    Posted 553 days ago
    28

    It doesn’t generate a oauth_token for me, I have edited the secret.php but it doesn’t work. I’m using a .in domain from securesignup.net, site is hosted on 0fees.net.

    Reply
  • neko

    Posted 561 days ago
    26

    hello.
    your tutorial so easily to understand!
    thank you so mach.

    but i have a problem.
    i try to tweet in japanese,status is incorrect.
    In english , status is OK.

    i think encode problem.
    how can i solve ?
    please help me.

    Reply
    • Neko

      Posted 557 days ago
      27

      I solve that.
      I try to make original script,so I can tweet in multibyte(japanese).
      thank you!

      Reply
      • Abhishek Bhardwaj

        Posted 519 days ago
        43

        Glad that you could find the solution yourself!

        Reply
  • Rims

    Posted 564 days ago
    24

    Hello… i have used the same code in my php project bcz i want to run it on localhost.
    I have also registered application in twitter and changed the secret.php file. but then also i m getting error….
    Call to undefined function curl_multi_init() in C:\Program Files\xampp\htdocs\twitter\lib\EpiCurl.php on line 21.

    Plz tell me how to resolve this error.
    I have searched about it there is no prob with PHP installed bcz it is giving information when i call function phpinfo();.

    Reply
    • Abhishek

      Posted 563 days ago
      25

      The problem is that you do not have cURL extension installed (or it is disabled).
      Reconfigure it and it should work!

      Reply
  • seddik

    Posted 570 days ago
    21

    this tutorial helped me really much but just one thing i didn’t understand, for the callback url, I tried http://localhost/twitter/index.php but at twitter application settings it doesn’t accept this url ?

    Reply
    • Abhishek Bhardwaj

      Posted 568 days ago
      23

      lol Sorry, I think Twitter doesn’t accept any URL which doesn’t have a .com or .net or all those other domain suffixes.

      Reply
  • drooh

    Posted 572 days ago
    20

    I dont understand, everytime I have to click to sign in authenticate with twitter? It would be nice to just do that once and not have to do it every time you wanted to post to twitter.

    Reply
    • Abhishek Bhardwaj

      Posted 568 days ago
      22

      That’s because I am not storing the token keys anywhere. This is just a simple app! Maybe in the future, I’ll have another tutorial on 1WD that connects to a database and stores the authentication keys so that the user doesn’t have to login again and again!!

      Reply
      • Jim

        Posted 550 days ago
        30

        It would be awesome if you could add it to this tutorial any time soon.
        Thank you very much

        Reply
    • Francesco

      Posted 529 days ago
      33

      Hi drooh,
      I have your same problem.
      have you solved?

      tnx

      Reply
  • yankymetro

    Posted 576 days ago
    18

    I don’t know what’s the callback URL. It’s hard. Explain it to me better. Thanks.

    Reply
    • Abhishek

      Posted 575 days ago
      19

      Do you really think its hard? Check the first screenshot and that’s your answer otherwise the callback URL is: http://your-website.com/“”index.php”" ……..

      Reply
  • SG

    Posted 579 days ago
    16

    Great post!

    Can you also tell us how to test it locally? I want to develop and test an app locally before uploading it. What should be the web / callback URL for this and how should localhost / server handle it?

    Thanks a lot.

    Reply
  • Jordan Walker

    Posted 579 days ago
    15

    Wow, excellent tutorial with very detailed instruction.

    Reply
  • Zachary Collins

    Posted 579 days ago
    13

    Hey there,
    Great tutorial! Only problem I am having is when I connect my account and it brings me back to the index.php page, I refresh, and it doesnt load the user.

    Thanks,
    Zachary Collins

    Reply
    • Abhishek

      Posted 579 days ago
      14

      Check your callback URL on Twitter, and did you change the API Keys in secret.php file?

      Reply
      • Carter Thayer

        Posted 524 days ago
        36

        I checked both, the refresh problem is still happening. Let me know if you find a solution. Also, same thing is happening on your demo page.

        Reply
  • Rvarm1

    Posted 580 days ago
    11

    Hi! I was making a similiar application, but whenever I clicked sign in with twitter, it gave me this error:
    “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.”

    Can you please help me? I already tried resetting the keys, but it didnt work.

    Thanks for your help!

    Reply
    • Abhishek

      Posted 580 days ago
      12

      I think the tokens are valid for only 2 minutes. Everytime you open your oAuth app, the application connects to the API and gets your token automatically..try refreshing the page and clearing your cache + cookies, it should work..

      The error you are talking about ignites when your token has expired..and most times its due to the fact that someone else used that..after all there are 1000s of Twitter oAuth apps running on the web and these tokens are distributed among everyone! :D

      Reply
  • Jaisen Mathai

    Posted 580 days ago
    5

    I added this article to the readme of the Twitter-Async library on Github.

    http://github.com/jmathai/twitter-async

    Thanks for the write up.

    Reply
  • Box Model Junkie

    Posted 580 days ago
    4

    It nice to see that it’s relatively easy to integrate oAuth into your app.

    Reply
    • Abhishek

      Posted 580 days ago
      8

      Yes, It initially looks difficult but its relatively easy once you dive into the code.

      Reply
  • Siddharth

    Posted 580 days ago
    3

    hey thats wonder tutorial..
    am actually using these.. and could u say..
    in case i we want to use these if the user s not online.. but registered..
    how to get and store the oauth token and secrets ?
    and how to ue them again to update the satus ?/
    can u help me out ?
    am tryin to do for http://sms2twitter.in

    Reply
    • Abhishek

      Posted 580 days ago
      6

      That can be done using a database which stores all tokens! I also emailed you from your website so I guess we should continue our conversation there :D

      Reply
  • ditatompel

    Posted 581 days ago
    2

    Nice tutorial! Thank you for sharing! =)

    Reply
    • Abhishek

      Posted 580 days ago
      7

      Thank you!! :)

      Reply
  • Irina

    Posted 581 days ago
    1

    Great tutorial! Thanks. I just wanted to make a similar app :)

    Reply
    • Abhishek

      Posted 580 days ago
      9

      Glad you liked it :)

      Reply
1 2 3 4

 Add Your Own Brilliant Comment:

Tags allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

US