Login with Twitter OAuth API Using PHP

Abhigyan Singh 29th Sep 2020

This tutorial will show to twitter login using PHP. Here we use the Twitter OAuth PHP library for twitter sign in. Twitter has become the most popular social network after Facebook. Millions of users are connected and active daily with twitter. Nowadays every web application will have this social network OAuth to improve the user comfort level. So users would not need to create separate login credentials 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 log in with existing popular social media account.

In this article, we will explain how you can integrate login with twitter on your website. The whole process will be divide into two steps:

  • Create a Twitter app to get API and secret keys.
  • Download Twitter OAuth PHP library files and Create a view for login with twitter, requesting a token, or show user information after twitter authentication.

Create Twitter Login App

Below, we are going to describe the whole process in details or step by step:

1. Go to https://apps.twitter.com/app/new. Enter your app name and other details that you want to put there. In my case the app name is discussdesk2. The name will show when a user will log in through your app.

2. After Filling the above details, click on create your Twitter Application Button you will redirect to the app details page with four tabs. Click on the key and the access token tab will have your API key and secret key as shown below. By going into the setting tab, you can change your app details, and changing access type will have to go in the permissions tab.

Download Twitter OAuth PHP Library and merge with your Project

You can get Twitter OAuth PHP Library Files from the twitter folder when you download our demo and can modify according to your requirement as shown below:

After downloading, you have to create three files:

  • index.php
  • config.php
  • logout.php

In index.php file will contain your view part i.e. when the user will log in through a button or some hyperlink and retrieving app request or response. Put the following code in the index file and save it.

<?php
// Include config file and twitter PHP Library
include_once("config.php");
include_once("twitter/twitteroauth.php");

if(isset($_GET['request']))
{
//Fresh authentication
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$request_token = $connection->getRequestToken(OAUTH_CALLBACK);

//Received token info from twitter
$_SESSION['token'] = $request_token['oauth_token'];
$_SESSION['token_secret'] = $request_token['oauth_token_secret'];

//Any value other than 200 is failure, so continue only if http code is 200
if($connection->http_code == '200')
{
//redirect user to twitter
$twitter_url = $connection->getAuthorizeURL($request_token['oauth_token']);
header('Location: ' . $twitter_url);
}else{
die("error connecting to twitter! try again later!");
}
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login with Twitter</title>

</head>
<body>
<?php
if(isset($_REQUEST['oauth_token']) && $_SESSION['token'] == $_REQUEST['oauth_token']){

$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['token'] , $_SESSION['token_secret']);
$access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
if($connection->http_code == '200')
{

$user_data = $connection->get('account/verify_credentials');
$result = '<h1>Twiiter Profile Details </h1>';
$result .= '<img src="'.$user_data['profile_image_url'].'">';
$result .= '<br/>Twiiter ID : ' . $user_data['id'];
$result .= '<br/>Name : ' . $user_data['name'];
$result .= '<br/>Twiiter Handle : ' . $user_data['screen_name'];
$result .= '<br/>Follower : ' . $user_data['followers_count'];
$result .= '<br/>Follows : ' . $user_data['friends_count'];
$result .= '<br/>Logout from <a href="logout.php?logout">Twiiter</a>';
echo '<div>'.$result.'</div>';
}else{
die("error, try again later!");
}

}else{
//Display login button
echo '<a href="index.php?request=twitter"><img src="image/login_button.jpg" /></a>';
}
?>

</body>
</html>

In config.php, you will put your app key, secret key, and redirect URL and save with the following code:

<?php
if(array_key_exists('logout',$_GET))
{
session_start();
unset($_SESSION['userdata']);
session_destroy();
header("Location:index.php");
}
?>

If you have any queries regarding our script, please feel free to ask me in the comment section.

Authored By Abhigyan Singh

He is a continuous blogger and has blogged on different topic. He loves to surf Internet and always trying to get new Idea about new Technology and Innovations and sharing these great information to all the technology lovers.

Also on DiscussDesk