Latest Posts
  • How to Advertise Your Vape Business on Social Media: A Complete Guide
  • How To Create Custom Module Form with Menu Link in Drupal
  • Some Common Mistakes to Avoid While Doing SEO for Shopify
  • iPhone 8 & iPhone X Features Prices and Specifications
  • Make Money Easily to Automatically Link Keywords with Affiliate Links in WordPress
  • Yoast SEO Premium License Key Cracked or Patched
  • 6 Reasons To Choose WordPress For Blogging
  • Most Popular Coding Language In 2018
  • Facebook
  • Twitter
  • Instagram
  • RSS
  • YouTube
Developer Desks Developer Desks
  • Home
  • Codes
    • WordPress
    • PHP
    • Jquery
    • Javascript
    • Guest
  • Demos
  • blog
  • Tech News
  • Submit Your Articles
  • Contact
Apis

Login System with Twitter using Php

November 3, 2015
Share on Facebook Share on Twitter Google+ Pinterest LinkedIn Tumblr Email
Login System with twiter using Php

Many of the registered users wish to signup social networks like our previous articles login with Facebook and login with google. Twitter is one of the most used social networking website on the internet, So this is time I will explain how to make a Login System with Twitter using Php. Place a button on your site or application which allows Twitter users to enjoy the benefits of a registered user account in as little as one click.

Features:
Ease of use – A new visitor to your site only has to click two buttons in order to sign in for the first time.
Twitter integration – The Sign in with Twitter flow can grant authorization to use Twitter APIs on your users behalf.
OAuth based – A wealth of client libraries and example code are compatible with Sign in with Twitter’s API.

Please refer my previous articles
Login System with Google using Php and OAuth Api
Login System with Facebook using Php

Demo

Get Consumer key(API KEY) and Consumer Secret (API SECRET).

Step 1 – Go to the Url https://apps.twitter.com/
Login with you twitter credentials and access the twitter apps. Create new app

 

Login System with twitter using Php

Step 2 – Create new application with your application name and details. Important thing is please give correct “call back url” which is used in you coding.

Login System with twitter using Php

 

Step 3 – Get the Consumer key(API KEY) and Consumer Secret (API SECRET) here  twitter aouth

Login System with twitter using Php

Now go to coding

Configuration – Create database and table

CREATE TABLE IF NOT EXISTS `twitter_users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `twit_id` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

Create config.php file for configuration with database.. Enter Your Consumer key(API KEY) and Consumer Secret (API SECRET) and call back url.

<?php

error_reporting(E_ALL & ~E_DEPRECATED & ~E_NOTICE);
ob_start();
session_start();

define('PROJECT_NAME', 'Login System with twitter using PHP - www.Developerdesks.com');

define('DB_DRIVER', 'mysql');
define('DB_SERVER', 'localhost');
define('DB_SERVER_USERNAME', 'root');
define('DB_SERVER_PASSWORD', '');
define('DB_DATABASE', 'your database');

$dboptions = array(
    PDO::ATTR_PERSISTENT => FALSE,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
try {
  $DB = new PDO(DB_DRIVER . ':host=' . DB_SERVER . ';dbname=' . DB_DATABASE, DB_SERVER_USERNAME, DB_SERVER_PASSWORD, $dboptions);
} catch (Exception $ex) {
  echo $ex->getMessage();
  die;
}

define("CLIENT_ID", "your client id");  // place your key here
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.developerdesks.com/login-with-twitter/");
/* the page where you will be redirected for authorization (call back url)*/
define("REDIRECT_URL", SITE_URL."twitter_login.php");

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

?>

Create Call back url file twitter_login.php

When the user is signed in to twitter.com but has not granted access, a list of requested permissions, along with Sign In and Cancel buttons are shown. When the user is not signed in to twitter.com input fields for a username and password will be shown. Note that even if the user has already granted access to the application, the list of permissions will still be shown. The call back url function check the process integration with your database and twitter database give the access.

<?php

require('http.php');
require('oauth_client.php');
require('config.php');

//require('config.php');

$client = new oauth_client_class;
$client->debug = 1;
$client->debug_http = 1;
$client->redirect_uri = REDIRECT_URL;
//$client->redirect_uri = 'oob';

$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('Please go to Twitter Apps page https://dev.twitter.com/apps/new , ' .
          'create an application, and in the line ' . $application_line .
          ' set the client_id to Consumer key and client_secret with Consumer secret. ' .
          'The Callback URL must be ' . $client->redirect_uri . ' If you want to post to ' .
          'the user timeline, make sure the application you create has write permissions');

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)
  exit;
if ($success) {
  // Now check if user exist with same email ID
  $sql = "SELECT COUNT(*) AS count from twitter_users where twit_id = :id";
  try {
    $stmt = $DB->prepare($sql);
    $stmt->bindValue(":id", $user->id);
    $stmt->execute();
    $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 `twitter_users` (`name`, `twit_id`) VALUES " . "( :name, :id)";
      $stmt = $DB->prepare($sql);
      $stmt->bindValue(":name", $user->name);
      $stmt->bindValue(":id", $user->id);
      $stmt->execute();
      $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;
}
header("location:home.php");
exit;
?>

Finally create link for login in index.php

 <a href="<?php echo $loginURL; ?>">
       Login with twitter
    </a>

Create home page as home.php after registering.

<?php if ($_SESSION["new_user"] == "yes") { ?>
<h2>welcome to developer desks.com </h2>
    <h2>Thank you for registering with us!!!</h2>
  <?php } else { ?>
    <h2>Welcome back <?php echo $_SESSION["name"] ?>!!!</h2>
<?php } ?>
<h5>Your Login email is: <?php echo $_SESSION["email"]; ?></h5>

Logout.php

<?php if ($_SESSION["new_user"] == "yes") { ?>
<h2>welcome to developer desks.com </h2>
    <h2>Thank you for registering with us!!!</h2>
  <?php } else { ?>
    <h2>Welcome back <?php echo $_SESSION["name"] ?>!!!</h2>
<?php } ?>
<h5>Your Login email is: <?php echo $_SESSION["email"]; ?></h5>

That’s it enjoy the code. Please subscribe me if you like my work.

Was this article helpful?

   

Awesome, share it:

Share Tweet Google Plus LinkedIn

Thanks!

Thanks for getting in touch with us.

Share this:

  • Twitter
  • Facebook
login with twittertwitter apitwitter login
Raja sekar

I'm Rajasekar - Web developer, Freelancer, Blogger and Owner of DeveloperDesks. From India lives in Bahrain. I love to do coding, Creating websites and trying different with code and designs. You Can Hire Me

  • Website

Related Posts

Most Popular Coding Language in 2017

Most Popular Coding Language In 2018

February 18, 2017
How to Create Like & Unlike code like FB uisng PHP, MySQL and jQuery

How to Create Like & Unlike code like FB using PHP, MySQL and jQuery

November 25, 2016
live-search-in-php-and-mysql-using-jquery

Live search in PHP and Mysql using Jquery

October 13, 2016
  • Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

    Thank you for subscribing.

    Something went wrong.

    we respect your privacy and take protecting it seriously

  • Help Me To Improve My Desk
    Buy Me A Coffee
  • About

    Developer Desks is Teach Coding and updates latest technology news in our blog. We have Highly professional web designer and Developer. We do Website developing work as a freelancer. Founded in 2015, This blog focus on the latest trends, tutorials, opinion articles as well as tips and tricks to empower our readers to become better web developers.

    Read More
    Facebook Twitter Instagram LinkedIn

    Copyrights © 2014 - 2022 Developer desks. All rights reserved. Designed by Developer desks.

  • Latest Posts
    • guest-blog-post
      How to Advertise Your Vape Business on Social Media: A Complete Guide
      Guest Blog May 30, 2018
    • How To Create Custom Module Form with Menu Link in Drupal
      Drupal April 4, 2018
    • Shopify Mistakes
      Some Common Mistakes to Avoid While Doing SEO for Shopify
      SEO September 18, 2017
    • iphone 8 features
      iPhone 8 & iPhone X Features Prices and Specifications
      Android updates September 13, 2017
  • Downloads
    Icon
    Multi select filter ajax 1798 downloads 3.43 KB
    Download
    Icon
    Check Existing username and match password using ajax 354 downloads 3.51 KB
    Download
    Icon
    Export excel from mysql table data 349 downloads 3.55 KB
    Download
    Icon
    php session without database 330 downloads 1.64 KB
    Download

Powered by Developer Desks. Privacy Policy

Top
Developer Desks
     

    Loading Comments...