Sunday 2 October 2016

Login with Twitter using PHP : OAuth PHP

Twitter oAuth PHP library helps web developer to integrate twitter login system by quick, easy and powerful way. This Login with Twitter API tutorial will explain how to implement users sign in with Twitter using PHP and store the user informations into the MySQL database. We will discuss about implementing sign in with twitter using PHP andTwitter Apps creation process. We have used Twitter OAuth PHP library to support OAuth for Twitter’s REST API.
From the above Demo links you would be able to view the live demo of the project. Also you can download the full source code of PHP login with Twitter API from the above Download link and implement the twitter login system within a minute.
This project contains three folders named inc/includes/ and images/ with some PHP files. The folders and files structure are given below:
  • inc/
    • OAuth.php
    • twitteroauth.php
  • includes/
    • functions.php
  • process.php
  • config.php
  • index.php
  • logout.php
  • images/

Twitter Apps Creation:

 At first go to the https://apps.twitter.com/app/new and login at your Twitter developer account.
 Create new apps with the following details.
  • Name: Your application Name. This is shown to the user while authorizing.
  • Description: Your application Description. This is shown to user while authorizing.
  • Website: Your application website.
  • Callback URL(*): After authorization, this URL is called with oauth_token.
 Now change the apps permission to Read and Write or Read, Write and Access direct messages. For change the apps permission, you need to add mobile number to your twitter account. If you are not able to add mobile number from the web, then please follow the below steps.
  • In order to use this process, you need to have a smart phone and install the Twitter mobile application. By this process you will be able to switch to Twitter application write access, although the Twitter websites doesn’t accept your phone number.
  • After installing the Twitter mobile application, go to the tab on the right, it’s the screen showing your user details. Hit the wheel (it’s shown under the amount of tweets) and click Settings.
  • After clicking on Settings, another view opens where you have to click on your account.
  • The following view shows the options for your Account – scroll all the way down and click Security.
  • After hitting the Security option, the application will ask you to add a phone.
  • After clicking Add phone, the mobile browser will open and require you to insert your phone number.
  • After adding the phone number and pressing save, wait a few minutes. Twitter will send you a link to the phone number you just added to verify it. After clicking the link in the SMS the phone number is approved and you should be able to switch the application access to write.
 After the apps creation you have to click on Test OAuth. Also you should login with your twitter account for test OAuth. After that you would be redirected to the OAuth Settings page. At the OAuth Settings page you can see the Consumer key and Consumer secret.
 Congratulation! your apps creation has completed.

Database table creation:

To store the user information, you need to create a database and a table. At first create a database like codexworld. After that copy the below SQL query and run the SQL query on the database.
CREATE TABLE `users` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `oauth_provider` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
    `oauth_uid` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
    `username` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
    `fname` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
    `lname` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
    `locale` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
    `oauth_token` text COLLATE utf8_unicode_ci NOT NULL,
    `oauth_secret` text COLLATE utf8_unicode_ci NOT NULL,
    `picture` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
    `created` datetime NOT NULL,
    `modified` datetime NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

Installation:

In this project you just have to modify only two files.
 Database configuration (includes/functions.php):functions.php file have Users class with some functions. Into the __construct() function we have configured the database and connect with the database. You need only to change the $dbServer$dbUsername$dbPassword and $dbName variables value with your MySQL server details.
  • function __construct(){
        //database configuration
        $dbServer 'localhost'//Define database server host
        $dbUsername 'root'//Define database username
        $dbPassword ''//Define database password
        $dbName 'codexworld'//Define database name
        
        //connect databse
        $con mysqli_connect($dbServer,$dbUsername,$dbPassword,$dbName);
        if(mysqli_connect_errno()){
            die("Failed to connect with MySQL: ".mysqli_connect_error());
        }else{
            $this->connect $con;
        }
    }
 Twitter API configuration (config.php): open the config.php file and modify the CONSUMER_KEYCONSUMER_SECRETand OAUTH_CALLBACK constants value.
Note that: You can find the CONSUMER_KEY and CONSUMER_SECRET at the app page.(Go to the https://apps.twitter.com=> click on your app => click on the API Keys tab => copy the API key and API secret => replace CONSUMER_KEY value with API key and CONSUMER_SECRET value with API secret)
  • define('CONSUMER_KEY''Twitter Consumer Key');define('CONSUMER_SECRET''Twitter Consumer Secret');define('OAUTH_CALLBACK''http://localhost/login_with_twitter_using_php/process.php');

Getting User Email from Twitter Account

Basically, Twitter doesn’t return the user email after authentication. To get the user’s Email Address, your application needs to be whitelisted by Twitter. To get and store the user email address, follow the below steps.
  • Use this form to submit your request. It will take some times please be patient.
  • Once whitelisted, the Request email addresses from users checkbox will be available under your app permission on Application Management. Under settings, Privacy Policy URL and Terms of Service URL fields will be available. If enabled, users will be informed that your app can access their email on the OAuth dialog.
  • Open the process.php file and use include_email parameter in get() function. To do that replace $user_infovariable line value with the following line of code (probably line no. 25).
    $user_info $connection->get('account/verify_credentials', ['include_email' => 'true']);
    Now you can get the user email address using $user_info->email.
  • Add a new field (email) to store user email in the users table. Also, you can run the following SQL on userstable at the database.
    ALTER TABLE `users` ADD `email` VARCHAR(100) NOT NULL AFTER `lname`;
    
  • Open the includes/functions.php file and add $email parameter to the checkUser() function. Modify the INSERT and UPDATE query with email column name and value.
    function checkUser($oauth_provider,$oauth_uid,$username,$fname,$lname,$email,$locale,$oauth_token,$oauth_secret,$profile_image_url){
        $prevQuery mysqli_query($this->connect,"SELECT * FROM $this->tableName WHERE oauth_provider = '".$oauth_provider."' AND oauth_uid = '".$oauth_uid."'") or die(mysqli_error($this->connect));
        if(mysqli_num_rows($prevQuery) > 0){
            $update mysqli_query($this->connect,"UPDATE $this->tableName SET oauth_token = '".$oauth_token."', oauth_secret = '".$oauth_secret."', modified = '".date("Y-m-d H:i:s")."' WHERE oauth_provider = '".$oauth_provider."' AND oauth_uid = '".$oauth_uid."'") or die(mysqli_error($this->connect));
        }else{
            $insert mysqli_query($this->connect,"INSERT INTO $this->tableName SET oauth_provider = '".$oauth_provider."', oauth_uid = '".$oauth_uid."', username = '".$username."', fname = '".$fname."', lname = '".$lname."', email = '".$email."', locale = '".$locale."', oauth_token = '".$oauth_token."', oauth_secret = '".$oauth_secret."', picture = '".$profile_image_url."', created = '".date("Y-m-d H:i:s")."', modified = '".date("Y-m-d H:i:s")."'") or die(mysqli_error($this->connect));
        }
        
        $query mysqli_query($this->connect,"SELECT * FROM $this->tableName WHERE oauth_provider = '".$oauth_provider."' AND oauth_uid = '".$oauth_uid."'") or die(mysqli_error($this->connect));
        $result mysqli_fetch_array($query);
        return $result;
    }
  • Open the process.php file and pass the Twitter account email to checkUser() function once user logged in.
    $db_user->checkUser('twitter',$user_info->id,$user_info->screen_name,$fname,$lname,$user_info->email,$user_info->lang,$access_token['oauth_token'],$access_token['oauth_token_secret'],$user_info->profile_image_url);

No comments:

Post a Comment

Installation of Drop Box API on Codigniter

As with the YouTube API the first step in getting this sucker setup is getting a developer key by visiting  https://www.dropbox.com/develop...