Creating a Simple Twitter App using oAuth and PHP

 Posted in Tutorials 682 days ago Written by: Abhishek
  • Buffer
  • Pin It
  •  151

update twitter thumb tutorialsEveryone 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:

preview creating simple twitter appusing oauth php tutorials

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
 

 151 Brilliant Comments - Join Discussion Now!

  • Kelvin Chan

    Posted 219 days ago
    122

    great tutorial, but I can’t seem to get the oauth_token.. :(

  • Micky

    Posted 225 days ago
    121

    Hey, get rid of the space in update.php in line 17. There are 2 spaces in that line, just delete one of them.

  • evan heminger

    Posted 226 days ago
    120

    What if I don’t have a website?

  • motorlu panjur

    Posted 235 days ago
    119

    is a herbal is live are you teacher systam

  • prefabrik ev fiyatları

    Posted 241 days ago
    118

    Though I think you’ll find the other topics pretty interesting too.

  • ivan

    Posted 245 days ago
    117

    I followed the instructions, step by step, but it doesn´t work fine. Twitter returns me a PIN code to put in to the app for the Authentication process ( of-band/PIN Code Authentication). This is so weird, because when I run your demo from this website, it works fine and doesn´t need the PIN code

    cheerrss!!!!!!

  • Eric Libay

    Posted 252 days ago
    116

    I can’t change my “Default Access type” into “Read & Write” it always turn into Read-Only..What happen to twitter.

  • Mathias

    Posted 262 days ago
    115

    Good tutorial

    Is there a way to use this API to check who unfollowed me in the last 48 house?

  • bjesua

    Posted 301 days ago
    110

    Hello, when i try to login i have this error on twitter

    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.

    Please can you help me or guide mi with this problem i had?
    i really need your answer thanks!

  • Palak

    Posted 301 days ago
    109

    Hi,

    Thanks for nice tutorial. It helps me lot. One thing I want to ask that. I want to follow the user by this api. how it can be done ? is there any particular function in twitter lib for that ? same like
    $update_status = $twitterObj->post_statusesUpdate(array(‘status’ => $msg)); as u used this for the post to twitter.
    Please tell me how can I follow the user by this api ?

    Thanks.

  • sai

    Posted 303 days ago
    108

    the demo is working. but i downloaded and when i am accessing it is not working can u help me please.

  • Ekn

    Posted 307 days ago
    106

    I got no success in trying. The link to the DEMO is broken. Could you please, update it?

    • Rean John Uehara

      Posted 307 days ago
      107

      That’s odd, the demo is working fine for me and I’ve allowed 1stwebdesigner access to my Twitter account. :|

  • naff

    Posted 312 days ago
    105

    nice info…. thank’s

  • dt

    Posted 329 days ago
    104

    Any idea how to use this great tool in a frame? it simply does not open the sign in link within a frame. I am aware about the policy of twitter for frames but there should be way to use it.

    What is my thinking is to open the sign in link in a new window and after authenticating, the frame should refresh itself to load required page. But I couldnt manage to do it.

    any help is welcome?

    • Abhishek

      Posted 266 days ago
      113

      No need to use frames. You can instead use an AJAX-jQuery method to achieve the same!

  • Rupanjan

    Posted 338 days ago
    103

    This code is working fine than the other one
    Thanx for sharing

    Rupanjan

  • Kevin

    Posted 340 days ago
    101

    Where is the log out button so users can log out of your application AND Twitter?

  • Usman

    Posted 342 days ago
    100

    Hi,

    i m trying to use your code but no success for me. using same code as you have asked only changed my consumer keys. nothing less OR more. please see below URL why it is behaving like this.

    http://www.socialscratch.com/images/twitter-oauth/

    Waiting for your reply.

    Thanks in Advance

    Regards
    Usman

  • PM

    Posted 357 days ago
    99

    Hi,

    Thanks for sharing very helpful information. Can you demonstrate how to retrieve tweets from an account?

    Thanks again,
    -PM.

  • jude

    Posted 375 days ago
    97

    HI ,

    Is it possible to include a username and password field so there is no request for authorization ?

    thanks in advance
    Jude Dcoutho

    • Rean John Uehara

      Posted 375 days ago
      98

      Hi, as far as I am concerned the authorization is required by Twitter. But you can still go here to find out: http://dev.twitter.com/pages/oauth_faq

    • Abhishek

      Posted 266 days ago
      112

      Twitter had closed that method of authentication last year itself.

  • Lev

    Posted 381 days ago
    93

    Don’t use the code posted here – it is OUT OF DATE (get it from the author directly at the URL provided below).

    I ran into a number of issues with the code provided here (the biggest being many status updates would outright fail because of accented characters).

    The same library (only newer code, with lots of fixes) can be found here:

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

  • int

    Posted 387 days ago
    92

    My messages are not getting added to the time line.

    Is there something I should do to rectify it?

    • Abhishek

      Posted 377 days ago
      96

      Change your application’s access type to “Read/Write”.

  • edwin

    Posted 391 days ago
    91

    Is it possible to let the script login automatic so you can go to the page and fill in the tweet, instead of going to the page and login to twitter first.

  • Anh

    Posted 392 days ago
    90

    Great tutorial, but there’s an error. In the “secrets.php,” the variables should be $consumerKey and $consumerSecret, not $consumer_key and $consumer_secret. You have to change this in the index.php file as well. If you don’t, the oauth token won’t register.

    • Abhishek

      Posted 377 days ago
      94

      No need to make such changes. Those are variable names..

  • Rupanjan Mukherjee

    Posted 397 days ago
    88

    Every Thing is Understandable but my question where to put the (oauth_token ) (oauth_token_secret)
    am a newbie in this field.
    another question what will be my call back url is it http://www.xyz.com/xyz/update.php
    any body can explain?

    Thanks in advance. The topic is nice may i mistake something

    • Anh

      Posted 392 days ago
      89

      I’m having the same problem. I followed the tutorial exactly and I updated the secrets php script with my own keys, but it’s not “seeing” my oauth token?

      Any help would be appreciated! Thanks.

    • Abhishek

      Posted 377 days ago
      95

      secret.php file!

  • Zach

    Posted 405 days ago
    86

    Great tutorial! Very cool potential here.

    I was struggling with a goofy error, and I just figured it out. In case anyone is in the situation where you send your tweet, the page reloads, says you successfully updated your timeline, but you DON’T see anything actually update on your feed, make sure your app is registered as Read & Write under “Default Access Type”. I had mine set to Read-only, so it wasn’t working.

    I figured it out by checking the temporary variable that gets assigned the response to the update (in index.php):

    $temp = $update_status->response;

    and found [error] => Read-only application cannot POST

    Silly error. Very simple. But fooled me nonetheless. Hopefully this post will help someone else out.
    Cheers!

    • Abhishek

      Posted 405 days ago
      87

      It’ll surely help people out!

1 2 3 4
US