Creating a Simple Twitter App using oAuth and PHP

 Posted in Tutorials 577 days ago Written by: Abhishek
  • Buffer
  •  138
  • 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
 

 138 Brilliant Comments - Join Discussion Now!

  • jeremy

    Posted 15 hours ago
    138

    I want my script to post new blog posts, why would i have to autenticate with my browser everytime??? my script will be called by another script not by a browser, the old api was sooo much simpler. this sucks

    Reply
  • Theo

    Posted 5 days ago
    137

    Hi!
    I have some ugly php error messages:
    Warning: include(lib/EpiCurl.php) [function.include]: failed to open stream: No such file or directory in /var/www/virtual/artlog.hu/htdocs/twitter/index.php on line 5

    Warning: include() [function.include]: Failed opening ‘lib/EpiCurl.php’ for inclusion (include_path=’.:/usr/share/php:/usr/share/pear’) in /var/www/virtual/artlog.hu/htdocs/twitter/index.php on line 5

    Warning: include(lib/EpiOAuth.php) [function.include]: failed to open stream: No such file or directory in /var/www/virtual/artlog.hu/htdocs/twitter/index.php on line 6

    Warning: include() [function.include]: Failed opening ‘lib/EpiOAuth.php’ for inclusion (include_path=’.:/usr/share/php:/usr/share/pear’) in /var/www/virtual/artlog.hu/htdocs/twitter/index.php on line 6

    Warning: include(lib/EpiTwitter.php) [function.include]: failed to open stream: No such file or directory in /var/www/virtual/artlog.hu/htdocs/twitter/index.php on line 7

    Warning: include() [function.include]: Failed opening ‘lib/EpiTwitter.php’ for inclusion (include_path=’.:/usr/share/php:/usr/share/pear’) in /var/www/virtual/artlog.hu/htdocs/twitter/index.php on line 7

    Fatal error: Class ‘EpiTwitter’ not found in /var/www/virtual/artlog.hu/htdocs/twitter/index.php on line 10

    Anyone?

    Reply
  • aaron

    Posted 13 days ago
    136

    Hi– once on my server, i tried to follow the link and sign in with twitter but i got this 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.

    the consumer secret and key were the only two devices needed, correct?

    Reply
  • Rissa

    Posted 19 days ago
    135

    Out of ALL the tutorials I have tried out of the past week, this is the ONLY one that worked lol. Now I just have to figure out how to update the bg image instead of posting a tweet, oh geez.

    Reply
  • Drewseph

    Posted 59 days ago
    134

    I’m a bit confused at what I need to store in my database and where I need to call it

    I have the script working perfectly but I’d prefer to not have to authenticate every time and have to “Allow” app to post

    Reply
  • Tonny

    Posted 62 days ago
    133

    Dudz, help me how can i decode $twitterInfo->response

    Reply
  • tonny

    Posted 62 days ago
    132

    How can i decode twitterInfo object?

    Reply
  • Pur

    Posted 67 days ago
    130

    Hi Bhardwaj,

    I’ve tried this script on my website for member area (where the session_start() is always there). Getting $username and $profilepic when visitor redirected to callback URL is work nicely. It means that writing $_SESSION['ot'] and $_SESSION['ots'] also good. But i always fail sending post to twitter. I tried to display error by adding print_r($temp) and I found error like “Invalid/Token Expired”. So that after doing POST Request there are missing value of $_SESSION['ot'] and $_SESSION['ots'] even if I add or remove session_start() on the top of page.

    I’ve also tried other different tutorials and simply not working when sending tweet. I put customer_key and customer secret correctly, and set my application permission to read and write, give correct callback URL, domain and web address. Still not working.

    Because there are missing $_SESSION['ot'] and $_SESSION['ots'] value when sending Post Request, I tried to record those string to my myql table when getting back to Callback URL (where $_SESSION['ot'] and $_SESSION['ots'] got their values correctly), and then call them when posting tweet. And still not working.

    Can you tell me why I loss $_SESSION['ot'] value when sending POST Request even if i send it to different file , and why I got error: Invalid/token expired even i use toke key from mysql record.

    It seems something causes that errors on my server but I don’t know what is it because the script doesn’t return any error until I put this print_r($temp).

    Can you help me fix this problem please!

    Thanks for your great posts.

    Reply
    • Pur

      Posted 67 days ago
      131

      Note:
      My server is also PHP CURL enabed, safe_mode=off, and works well in integrating facebook API with PHP.
      I really need this twitter API script, and your script is the only script that successfully displaying twitter user data on Callback, but fail sending post to twitter.
      Hope you help me fix this.

      Reply
  • Francis

    Posted 72 days ago
    129

    Great tutorial, I’m planning to develop my own twitter API and this one is a good example to start for. Thanks for sharing.

    Reply
  • sonu

    Posted 85 days ago
    128

    I want to upload image on twitter account with php code can anyone help me regarding this.

    Thanks for this

    Reply
  • priya

    Posted 96 days ago
    126

    Hi
    we get user name of the person through this code
    $username = $twitterInfo->screen_name;

    but i dont know how to get email id of him

    will please answer?

    Reply
  • Umer

    Posted 106 days ago
    125

    Nice post but even in your demo once i refresh the page, my user info including picture goes off and it does not retain the session. Kindly comment and update your code to make it complete teaching beginners to retain user info as well.

    Reply
    • Abhishek Bhardwaj

      Posted 90 days ago
      127

      This was a basic tutorial without any databases involved (Yes, you’ll need a database to retain sessions).

      Reply
  • Nilesh

    Posted 109 days ago
    124

    Really good documentation specially for beginners.

    Reply
  • Daniel

    Posted 111 days ago
    123

    A snag which I ran into and remedied: don’t forget to enable the cURL extension in php.ini (uncomment extension=php_curl.dll). Otherwise you’ll run into ‘could not find **_curl_**() function’ errors.

    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