Login System with twitter using OAuth php and mysql

Login System with twitter using OAuth php and mysql

Twitter is the last part of my “login system with social sites” series. After so many requests pouring in from my blog followers for twitter login system, I simply had to. In this tutorial I will be explaining how to create a twitter app for website and integrating the Login System with twitter using OAuth php and MySQL.

View Demo

How OAuth login works

Check out my posts on PHP OAuth to get better insights Login System with LinkedIn using OAuth php and mysql, Login System with Facebook with php and mysql, Login System with Google using OAuth php and mysql, Login System with Github using OAuth php and mysql, Login System with Twitter using OAuth php and mysql.

How to create a Twitter Application for website?

Create an aplication to get CLIENT ID and SECRET KEY. Given below is the powerpoint presentation which will guide you through the process of making the application.


Integration of twitter with OAuth PHP and MySQL

All the login process is very similar to the post I have posted before, please refer those if you still dont get it. The only difference in this tutorial is that twitter does not gives email address via their API, so you will have to use the unique twitter id to keep the track of the user. Check the database structure below.

USE login_system;
CREATE TABLE IF NOT EXISTS `users_twitter` (
  `name` varchar(255) NOT NULL,
  `twitter_id` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)

Set your website and twitter configuration settings in config.php file
define('DB_DRIVER', 'mysql');
define('DB_SERVER', 'localhost');
define('DB_SERVER_USERNAME', 'root');
define('DB_SERVER_PASSWORD', '');
define('DB_DATABASE', 'login_system');

define("CLIENT_ID", "your client ID");
define("SECRET_KEY", "your secret key");
Make sure the url end with a trailing slash, give your site URL 
your Site URL
define("SITE_URL", "http://demos.aarafacademy.com/login-with-twitter/");
/* the page where you will be redirected for authorization */
define("REDIRECT_URL", SITE_URL."twitter_login.php");

define("LOGOUT_URL", SITE_URL."logout.php");

Set your login and logout URL.
<a href="twitter_login.php">
  Login with Microsoft

<a href="<?php echo LOGOUT_URL; ?>">

When user tries to login via twitter they are taken to twitter_login.php and these code are executed. Make sure the dependencies files exist.

$client = new oauth_client_class;
$client->redirect_uri = REDIRECT_URL;

$client->client_id = CLIENT_ID;
$application_line = __LINE__;
$client->client_secret = SECRET_KEY;

if (strlen($client->client_id) == 0 || strlen($client->client_secret) == 0)
  die('set your access');

if (($success = $client->Initialize())) {
  if (($success = $client->Process())) {
    if (strlen($client->access_token)) {
      $success = $client->CallAPI(
              'https://api.twitter.com/1.1/account/verify_credentials.json', 'GET', array(), array('FailOnAccessError' => true), $user);
  $success = $client->Finalize($success);
if ($client->exit)

And finally insert or update user data in the database based on the database records.
if ($success) {
  // Now check if user exist with same email ID
  $sql = "SELECT COUNT(*) AS count from users_twitter where twitter_id = :id";
  try {
    $stmt = $DB->prepare($sql);
    $stmt->bindValue(":id", $user->id);
    $result = $stmt->fetchAll();

    if ($result[0]["count"] > 0) {
      // User Exist 

      $_SESSION["name"] = $user->name;
      $_SESSION["id"] = $user->id;
      $_SESSION["new_user"] = "no";
    } else {
      // New user, Insert in database
      $sql = "INSERT INTO `users_twitter` (`name`, `twitter_id`) VALUES " . "( :name, :id)";
      $stmt = $DB->prepare($sql);
      $stmt->bindValue(":name", $user->name);
      $stmt->bindValue(":id", $user->id);
      $result = $stmt->rowCount();
      if ($result > 0) {
        $_SESSION["name"] = $user->name;
        $_SESSION["id"] = $user->id;
        $_SESSION["new_user"] = "yes";
        $_SESSION["e_msg"] = "";
  } catch (Exception $ex) {
    $_SESSION["e_msg"] = $ex->getMessage();

  $_SESSION["user_id"] = $user->id;
} else {
  $_SESSION["e_msg"] = $client->error;

View Demo
Share to download the Source Codes for FREE!
We're glad to give free downloads, but we need your love to carry on making that.
Please support us by sharing the page.

Get the latest updates directly in your inbox for FREE: Subscribe here

Share your feedback / let me know your doubts regarding this tutorial in the comment box given below.


Shahrukh Khan (Hasan)

A software engineer who's a die-hard coder, blogger, dreamer and mentor with years of expertise in web development. Know more...

Related Posts

Gokul raj on

The Above example for login with twitter was logging perfectly but after in home page wen clicked logout and once try to login it directly logins with email and password submittion

Shahrukh Khan on

maybe your session is not destroyed, that can be a reason.

Sandeep pattanaik on

Thanks friend 🙂

แบตเตอรี่รถกระบะจันทบุรี on

That is a really good tip particularly to those fresh to the blogosphere.

Simple but very accurate info Thank you for sharing this one.
A must read article!

Zohan on

Thanks for the code . I have the permission to access email address in my application but how am i suppose to use it in your code. How to fetch it an get it in user data.

Shahrukh Khan on

just run the demo

bhuvana on

Very very useful code..thanks lot…

Yash Kumar Verma on

Kindly upload the output of the program as well sir


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.