Login with Twitter using PHP


Feb 19, 2019

Simple way to make login and registration with twitter using Twitter API. Twitter is most popular social network on the internet and users are registered with twitter. You can implement Twitter Login API on your website using using PHP.

In this article i will explain you how to implement login and registration with twitter using PHP.

first go to the Application Management page and login with your Twitter account.

Add application details like name, description, website and callback url.

Once Twitter App creation is completed you will get the Consumer key and Consumer secret. Note this Consumer key and Consumer secret for the implementation in the PHP script.

Download Twitter oAuth libraby by clicking here

Create a "config.php" file


session_start();
// Include Twitter Auth library
require_once('Twitter/twitteroauth.php'); 

$ConsumerKey = 'CONSUMER-KEY';
$ConsumerSecretKey = 'CONSUMER-SECRET-KEY';
$RedirectUrl = 'REDIRECT-URL';


Create a "index.php" file


require_once 'config.php';

$twitter_auth = new TwitterOAuth($ConsumerKey, $ConsumerSecretKey);
$twitter_token = $twitter_auth->getRequestToken($RedirectUrl);
$twitterAuthURL="";
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];

if($twitter_auth->http_code == '200'){
	$authentication = $twitter_auth->getAuthorizeURL($twitter_token['oauth_token']);
	$twitterAuthURL=filter_var($authentication, FILTER_SANITIZE_URL);
}else{
	echo  '

Error connecting to twitter!

'; die(); } <a href="<?php echo $twitterAuthURL; ?>">Login & Registration With Twitter</a>

Create a "result.php" file


require_once 'config.php';

$twitterAuth = new TwitterOAuth($ConsumerKey, $ConsumerSecretKey, $_SESSION['oauth_token'] , $_SESSION['oauth_token_secret']);
$accessToken = $twitterAuth->getAccessToken($_REQUEST['oauth_verifier']);
if($twitterAuth->http_code == '200'){
	$userInfo = $twitterAuth->get('account/verify_credentials');
	echo json_encode($userInfo);
	exit();
}

Copyright 2018. All rights are reserved