Twitter API Integration with PHP

Twitter API is one of the best API Services that I have used and it is as simple as it should be with the open source libraries that are available on the internet for any language, you name it.

This post will guide you to a simple twitter API Integration to your website in PHP.

As the language that we’re going to use is PHP, we’ll choose Abraham’s TwitterOAuth Library.

For many reasons, I choose Abraham’s library anytime I want to do a twitter integration with my code. It is one of the first and most used API Libraries that is available for twitter in PHP which is followed by Matt Harris OAuth (which is a good one too).

And it started to support Update with media facility , which was not there earlier made me stick with this library all the time. Obviously, the code is in OOPs, so that it can be used with any frameworks at anytime if some little adjustments are made in implementation.

You can download the updated files from Abraham’s GitHub, or you can download a little easier implementation example files from twitter-api-integration-twitteroauth.

If you’re gonna try implementing a fresh one, here’s how to integrate twitter api to make things easy. Download the twitteroauth library for twitter from GitHub. You would find a folder named twitteroauth, which is the main folder that has the twitteroauth class file twitteroauth.php and Oauth class file OAuth.php. It had to be said earlier that you should or must (if I may), have an app created with twitter.

You can find how to register an application with twitter at techlanes – my twitter tips blog. Once you create an app with twitter, lets come  back to the pages and its code. You would find another file named config.php file where all the configuration settings are written. By Configuration settings I mean declaring the Consumer Key, Secret, db settings(if you need one).

define('CONSUMER_KEY', 'Your Consumer Key');
define('CONSUMER_SECRET', 'Your Consumer Secret');
define('OAUTH_CALLBACK', 'http://yoursitename/callback.php');
$servername = 'localhost';
$hostname = 'root'; 
$password = '';
$dbname = "vitwitapp";
$con = mysqli_connect($servername, $hostname, $password, $dbname);
//Check Connection
if(mysqli_connect_errno($con)){
   echo "Failed to connect to db :".mysqli_connect_error();
}

You can declare your Access Token and Access Secret to your config file(Optional). The difference is if you’re using the app only to get the details from your twitter account, you should declare the access token and secret.

If you’re going to let other users to use the app, you shouldn’t declare the access token and access secret  to the file because, it (the tokens from your dev account) will only work  for your account.

So anyway, just don’t declare the tokens and secrets in the config page. I have the files setup with db connection to your localhost db table in twitter-api-integration-twitteroauth files.

index.php

<a href="redirect.php">Sign In With Twitter</a>

The above a href is all we need at the index page to make the connection. When a user clicks the sign in button which is linked to a page where the code is written to make the api connection to twitter. It is the redirect.php

<?php
/* Start session and load library. */
session_start();
require_once('twitteroauth/twitteroauth.php');
require_once('config.php');
/* Build TwitterOAuth object with client credentials. */
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
/* Get temporary credentials. */
$request_token = $connection->getRequestToken(OAUTH_CALLBACK);
/* Save temporary credentials to session. */
$_SESSION['oauth_token'] = $token = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
/* If last connection failed don't display authorization link. */
switch ($connection->http_code) {
  case 200:
    /* Build authorize URL and redirect user to Twitter. */
    $url = $connection->getAuthorizeURL($token);
    header('Location: ' . $url); 
    break;
  default:
    /* Show notification if something went wrong. */
    echo 'Could not connect to Twitter. Refresh the page or try again later.';
}

We’re storing the oauth_token and oauth_token_secret in the session for temporary for we will store it to db in callback.php page.

We’re connecting to the twitter api with $connection object and get the temporary credential details such as oauth_token and oauth_secret to session so that we can pass them onto the callback page. It also has the switch case to check the response status.

If the response status is 200, it will redirect to the twitter authorize/authenticate url. After authenticating from twitter, the user is directed to the callback url where we store the values for future uses.

The callback.php file should contain the checking sequence such that if the http response status is 200, redirect it to the page you want it to go after authentication.

/* Start session and load lib */
session_start();
require_once('twitteroauth/twitteroauth.php');
require_once('config.php');

/* If the oauth_token is old redirect to the connect page. */
if (isset($_REQUEST['oauth_token']) && $_SESSION['oauth_token'] !== $_REQUEST['oauth_token']) {
  $_SESSION['oauth_status'] = 'oldtoken';
  header('Location: ./clearsessions.php');
}
/*Create twitteroauth object with app key/secret and token key/secret from the default phase*/
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
/*Request Access tokens from twitter*/
$access_token = $connection -> getAccessToken($_REQUEST['oauth_verifier']);
// query to save the long lasting oauth tokens to the db for future uses.
$screenname = $access_token['screen_name'];
$user_id = $access_token['user_id'];
$logdate = date('Y-m-d');
$oauth_token = $access_token['oauth_token'];
$oauth_secret = $access_token['oauth_token_secret'];
$ins_sql = "insert into vitwit_users (user_id, screenname, logdate, oauth_token, oauth_secret) values('$user_id', '$screenname', '$logdate', '$oauth_token', '$oauth_secret') ";
$upd_sql = "update vitwit_users set oauth_token = '$oauth_token', oauth_secret = '$oauth_secret', logdate = '$logdate', screenname = '$screenname' where user_id='$user_id'";
$fetch_query = "select * from twit_users where user_id = '$user_id'";
$fetch_sql = mysqli_query($con,$fetch_query);
if(mysqli_num_rows($fetch_sql) > 0) {
  mysqli_query($con,$upd_sql);
}
else {
mysqli_query($con,$ins_sql);
}

/* Remove no longer needed request tokens */
unset($_SESSION['oauth_token']);
unset($_SESSION['oauth_token_secret']);

/* If HTTP response is 200 continue otherwise send to connect page to retry */
if (200 == $connection->http_code) {
  /* The user has been verified and the access tokens can be saved for future use */
  $_SESSION['status'] = 'verified';
  header('Location: ./home.php');
} else {
  /* Save HTTP status for error dialog on connnect page.*/
  header('Location: ./clearsessions.php');
}

Now after getting the long lasting access token and secret, you can save it if you want for future uses. And the above is a simple insert/update sql query to save the data to your table. Remove the tokens and secrets set in the session values once you save them.

Check the connection http response, if the status response is 200, redirect the page to the next page(home.php) that you’d want to else unset all the session values and redirect to the index page.

An Important thing you need to specify in the config file is the callback page url.  It is where the page gets redirected to after getting the tokens from twitter successfully.

Remember if you’ve not given any callback url, the API will take the callback url that is specified at your app when you created it.

/* Create a TwitterOauth object with consumer/user tokens. */
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET,$oauth_token, $oauth_secret);
/* If method is set change API call made. Test is called by default. */
$content = $connection -> get('account/verify_credentials');

The above lines are to get your account credentials from twitter to check that can be written in your home.php page. You can write the code to get your friend’s list, followers list, send a tweet, tweet images, ..(atmost do anything within the api limit) similar to the above ones.

Download:  twitter-api-integration-twitteroauth file – github.

Photo Credit : Flickr

Conclusion :

If you’re downloading the files from the github, make sure you input Consumer Key, Secret, and db details if any. Now that you’ve read how to integrate twitter api with your work, you can try out some simple implementations all by yourself. I bet you’d find twitteroauth library more easier than other twitter api libraries in php.

Drop me a comment if you find any difficulty in Twitter Integration or need any advice regarding making your twitter app better.

 

Photo Credit : Flickr