How to Implement Login with Twitter PHP : Twitter API Part 1

Twitter Login with PHP

Twitter is one of the most popular social network used by millions of users. It also allows other websites to implement login with Twitter by using its API. If you are a developer and thinking to add Twitter Login in your website, this tutorial is for you. In this article, I will explain how to use Twitter API with PHP to add Login with Twitter in a website.

Implement Login with Twitter PHP

In this tutorial, I will be using TwiterOAuth library to implement various Twitter functions. Download it here.

I am assuming te root of your website is http://yourdomain and will be using it as a base for all files and requests.

Create Twitter Application

Step 1: Now create a Twitter application here: https://apps.twitter.com/app/new. You need to create a Twitter developer account to access this.

Step 2: Create a new app by entering Name, Description, website and Callback URL. The Callback URL is important because it will process call back request from API. In this, keep: http://yourdomain/oauth.php

Step 3: In Application Settings, check the Access Level. If you also want to tweet, retweet or perform any kind of other similar function, you also need to get the write permission. So, keep the access level to ‘Read and write’.

Step 4: Now go to ‘Keys and Access Tokens’. Here you get API keys and API Secret.

Getting Started

Now create a file config.php and paste the following code.

$CONSUMER_KEY='Your COnsumer API Key';
$CONSUMER_SECRET='Your Consumer API Secrent';
$OAUTH_CALLBACK='Call back URL';

I hope you know what values to put in the above code for key, secret and callback.

Now you need to create another file Login.php with following code.

<?php
session_start();
require_once('twitteroauth/twitteroauth.php'); // be sure to check the path of this file
include('config.php');


if(isset($_SESSION['name']) && isset($_SESSION['twitter_id'])) //check whether user already logged in with twitter
{

	echo "Name :".$_SESSION['name']."<br>";
	echo "Twitter ID :".$_SESSION['twitter_id']."<br>";
	echo "Image :<img src='".$_SESSION['image']."'/><br>";
	echo "<br/><a href='logout.php'>Logout</a>";


}
else // Not logged in
{

	$connection = new TwitterOAuth($CONSUMER_KEY, $CONSUMER_SECRET);
	$request_token = $connection->getRequestToken($OAUTH_CALLBACK); //get Request Token

	if(	$request_token)
	{
		$token = $request_token['oauth_token'];
		$_SESSION['request_token'] = $token ;
		$_SESSION['request_token_secret'] = $request_token['oauth_token_secret'];
		
		switch ($connection->http_code) 
		{
			case 200:
				$url = $connection->getAuthorizeURL($token);
				//redirect to Twitter .
		    	header('Location: ' . $url); 
			    break;
			default:
			    echo "Coonection with twitter Failed";
		    	break;
		}
	}
	else //error receiving request token
	{
		echo "Error Receiving Request Token";
	}
}
?>

Create another file oauth.php with following code

<?php
session_start();
require_once('twitteroauth/twitteroauth.php'); // Be sure to check the path of this file
include('config.php');

if(isset($_GET['oauth_token']))
{
	$connection = new TwitterOAuth($CONSUMER_KEY, $CONSUMER_SECRET, $_SESSION['request_token'], $_SESSION['request_token_secret']);
	$access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
	if($access_token)
	{
			$connection = new TwitterOAuth($CONSUMER_KEY, $CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
                        
                        // Here you also need to save $access_token['oauth_token’], $access_token['oauth_token_secret'] in your database if you need to access it later for tweeting or retweeting.
			$params =array();
			$params['include_entities']='false';
			$content = $connection->get('account/verify_credentials',$params);

			if($content && isset($content->screen_name) && isset($content->name))
			{
				$_SESSION['name']=$content->name;
				$_SESSION['image']=$content->profile_image_url;
				$_SESSION['twitter_id']=$content->screen_name;
                                $twitter_user = $content->screen_name;
                                 
                                // You can save basic user info in database.
				//redirect to main page where you will see basic profile.
				header('Location: login.php');&nbsp;
			}
			else
			{
				echo "<h4> Login Error </h4>";
			}
	}
else
{

	echo "<h4> Login Error </h4>";
}
}
else //Error. redirect to Login Page.
{
	header('Location: http://yourdomain.com/login.html'); 
}
?>

Now create a login.html file to put a login button and link it to the login.php

With the above files,  you can easily setup the login thing and get basic profile info.

Advertisement

Tags: |

Deepanker Verma is the founder of Techlomedia. He is a tech blogger, developer and gadget freak.


Similar Articles

0 Comments

Leave a comment

Comment policy: We love comments and appreciate the time that readers spend to share ideas and give feedback. However, all comments are manually moderated and those deemed to be spam or solely promotional will be deleted.

2020 UseThisTip | Part of Techlomedia Internet Pvt Ltd Developed By Deepanker