In this post, I am going to explain “How to create Twitter oAuth Login in php”. Twitter is the most popular social networks and millions of users on twitter, you can increase website subscriber using twitter login because Now a days every web application will have this social network OAuth to improve user comfort level. So user would not need to create separate login credential for each application. By using one twitter account you can register with several websites or applications.It’s really useful when you want to avoid long signup forms for user and let them login with existing popular social media account.
What Is OAuth?
OAuth is the most common authorization framework today, and it is used on most common web applications and services, like GitHub, Google, Facebook and Twitter etc.
This framework allows users to grant you permission to act on their behalf without sharing the account password. After the user has given permission, OAuth will return you a token. This token itself grants access to make requests on behalf of the user.
In this article we will explain that how you can integrate login with twitter in your website. So you have just follow few steps which is given below:-
Step 1:- To access twitter API you need to create twitter app and get the Consumer Key and Consumer Secret. Let’s create new application on the application management page.
After logging in, you need to click the Create New App button and fill in the form with your application details: name, description, website and callback URL.
What is the callback URL?
The URL where Twitter should redirect a user after successful authentication. And change the apps permission to Read and Write or Read, Write and Access direct messages. For changing the apps permission, you need to add a mobile number to your twitter account. Once Twitter App creation is completed, click on Test OAuth for testing OAuth. After testing you would be redirected to the OAuth Settings page. From the OAuth Settings page, you’ll get the Consumer key and Consumer secret.
Step 2:- Create Database Table
1 2 3 4 5 6 7 8 9 10 11 12 13 | CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `oauth_provider` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `oauth_uid` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `oauth_token` varchar(250) COLLATE utf8_unicode_ci NOT NULL, `oauth_secret_token` varchar(250) COLLATE utf8_unicode_ci NOT NULL, `oauth_name` varchar(100) 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; |
Step 3:- Let’s Start Coding
Before start coding we need to download twitter PHP library, I will use I will use TwitterOAuthas the most popular and easy to use. We can install it from the command line with Composer:
1 2 3 | composer require abraham/twitteroauth |
Step 4:- Now after installation we need to create config.php file to define Consumer Key, Consumer Secret and database configuration settings. So just create config.php file and copy below code and paste.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | <?php define("Consumer_Key", "put your consumer Key"); define("Consumer_Secret", "put your consumer secret key"); define("Callback_URL", "put your callback URL "); define('DB_SERVER', 'localhost'); define('DB_USERNAME', 'database username'); define('DB_PASSWORD', 'enter database password'); define('DB_DATABASE', 'enter database name'); $db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE); ?> |
Step 5:- Now create index.php file to display button Login with Twitter, If user already login then display Logout button.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | <?php session_start(); ?> <!doctype html> <html> <head> <meta charset="utf-8"> <title>Twitter Login using PHP</title> <style> .wrapper { width: 800px; margin:0 auto; } h1 { font-size:28px; font-family:Gotham, "Helvetica Neue", Helvetica, Arial, sans-serif; } </style> </head> <body> <div class="wrapper"> <h1><a href="https://webprepration.com/twitter-login-using-php/">Twitter Login using TwitterOAuth and PHP</a></h1> <?php if(!isset($_SESSION['name'])) { echo "<a href='twitterLogin.php'><img src='../img/twitter_login_button.png' style='width: 47%;'></a>"; }else { echo "User's Name: ". $_SESSION['name'] . "<br>"; echo "Screen Name: ". $_SESSION['username'] . "<br>"; echo "Last Tweet: " .$text = $_SESSION['text'].'<br><br>'; echo "<a href='logout.php'>Logout</a>"; } ?> </div> </body> </html> |
Start the Login Script
Now create new php file twitterLogin.php and include Composer autoload file, TwitterOAuth library, start session, and import the settings of our application from the config file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <?php session_start(); include ('config.php'); require "lib/autoload.php"; use Abraham\TwitterOAuth\TwitterOAuth; $connection = new TwitterOAuth(Consumer_Key, Consumer_Secret); $request_token = $connection->oauth("oauth/request_token", array("oauth_callback" => Callback_URL)); $_SESSION['oauth_token'] = $request_token['oauth_token']; $_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret']; $url = $connection->url("oauth/authorize", array("oauth_token" => $request_token['oauth_token'])); header('Location: ' . $url); ?> |
Now create new php file Twitterback.php file and handle all the process like authorization and database process. So just copy below code and paste.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | <?php session_start(); include ('config.php'); require "lib/autoload.php"; use Abraham\TwitterOAuth\TwitterOAuth; if($_GET['oauth_token'] || $_GET['oauth_verifier']) { $connection = new TwitterOAuth(Consumer_Key, Consumer_Secret, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']); $access_token = $connection->oauth('oauth/access_token', array('oauth_verifier' => $_REQUEST['oauth_verifier'], 'oauth_token'=> $_GET['oauth_token'])); $connection = new TwitterOAuth(Consumer_Key, Consumer_Secret, $access_token['oauth_token'], $access_token['oauth_token_secret']); $user_info = $connection->get('account/verify_credentials'); $oauth_token = $access_token['oauth_token']; $oauth_token_secret = $access_token['oauth_token_secret']; //echo "<pre>"; //print_r($user_info); $user_id = $user_info->id; $user_name = $user_info->name; $user_pic = $user_info->profile_image_url_https; $text = $user_info->status->text; $username = $user_info->screen_name; $sql="SELECT uid FROM users WHERE oauth_provider = 'twitter' and oauth_id = $user_id"; $result=mysqli_query($db,$sql); $row=mysqli_fetch_array($result,MYSQLI_ASSOC); if(mysqli_num_rows($result) == 1) { $query = mysqli_query($db, "UPDATE users SET oauth_token = '$oauth_token', oauth_secret_token = '$oauth_token_secret' WHERE oauth_provider = 'twitter' and oauth_id = $user_id"); if($query) { $_SESSION['name'] = $user_name; $_SESSION['dp'] = $user_pic; $_SESSION['text'] = $text; $_SESSION['username'] = $username; header('Location: index.php'); }else { echo mysqli_error($db); } }else { $query = mysqli_query($db, "INSERT INTO users (oauth_id, oauth_provider, oauth_token, oauth_secret_token, oauth_name) VALUES ($user_id, 'twitter', '$oauth_token', '$oauth_token_secret', '$user_name')"); if($query) { $_SESSION['username'] = $username; $_SESSION['text'] = $text; $_SESSION['name'] = $user_name; $_SESSION['dp'] = $user_pic; header('Location: index.php'); }else { echo mysqli_error($db); } } }else { header('Location: twitterLogin.php'); } ?> |
I hope you might have understood it properly, keep reading our other blogs posts for more coding tricks.
Thanks!!
I’m a full-stack developer. My hobby and profession to write blog and programming tips that helps to others. I am a great admirer of PHP, Laravel, Codeigniter, AngularJS, Vue.js, Javascript, JQuery, WordPress, Plugin Development, Theme Development and Bootstrap from the early stage.
This is my first time visit at here and i am in fact pleassant to read all at alone place.
Waay cool! Some very vaoid points! I aplreciate youu writing this post plhs the rrest oof thee site
iss also ver good.