Login with Google OAuth 2 Using PHP and MySQL

Posted by & filed under CSS, Google, HTML5, JQUERY, MYSQL, PHP, Uncategorized.

In this tutorial we are going to see how to implement Login with Google OAuth 2 Using PHP and MySQL to our web-application. Before continuing this please refer my previous tutorial on simple User Login and registration Using PHP and MySQLi.

http://www.smarttutorials.net/user-registration-and-login-using-php5-mysqli-jquery-and-bootstrap/

Next If you need please refer Facebook and Twitter Oauth Login Integration.

http://www.smarttutorials.net/facebook-oauth-2-login-using-php/

http://www.smarttutorials.net/sign-in-with-twitter-oauth-api-using-php/

 

 

 

 

 

Google Plus OAuth 2 Login Integration Using PHP

Google Plus OAuth 2 Login Integration Using PHP

Step 1:

First you need to create Google App to get Google Oauth Client ID and Client Secret. So please go through following URL to create to your Google Application.

https://code.google.com/apis/console

Now It will ask you to login with your Google account. Once you logged in please click on Create Project button on the top left corner. Now it will ask you to enter project name and save.

Steps to create Google Oauth Project in Google Api Console

Steps to create Google Oauth Project in Google Api Console

Now click on the project (CultivatingHappyness OAath 2) you just created now. To integrate Google OAuth 2 authentication in our web-application we need to enable Google+ API. So click on Enable an API button (Overview -> Enable an API) and turn Google+ api like in the below picture OR To enale Google+ API please click on API’s & Auth tab and select API. It will list all the API, now enable Google+ API.

Enable Google Plus API on Google API Console

Enable Google Plus API on Google API Console

Now click on API’s & Auth -> Credentials to create new client IDs.

Now It may ask you to enter some information on the consent screen, where you need to enter following information Email, Product Name, Home Page URL, Product Logo, Privacy Policy and etc…

 

Login with Google OAuth 2 Consent Screen

Now it will asks to select and enter application type, Authorised Javascript Origin and Authorised Redirect URI.

Steps to create Google Oauth Project in Google Api Console

Steps to create Google Oauth Project in Google Api Console

Now you have successfully created your client ID. Please note it down following information from the screen Client ID, Client Secret and Redirect URI.

Now on the Consent Screen enter following information Email, Product Name, Homepage URL and Logo URL and save. Now you are completed your application creation steps.

Step2 :

Create sample Database with table using following SQL queries.

--
-- Database: `user_login`
--
CREATE DATABASE IF NOT EXISTS `user_login` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `user_login`;

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE IF NOT EXISTS `users` (
  `user_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `email` varchar(60) NOT NULL,
  `password` varchar(60) NOT NULL,
  `social_id` varchar(100) NOT NULL,
  `picture` varchar(250) NOT NULL,
  `created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`user_id`),
  UNIQUE KEY `email` (`email`),
  KEY `login` (`password`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;

Step 3:

Now Create config.php file and define application related constants, and replace your Client ID, Client Secret and Redirect URI.

<?php
/**
@author muni
@copyright http:www.smarttutorials.net
 */

require_once 'messages.php';

//site specific configuration declartion
define( 'BASE_PATH', 'http://localhost/user_login/index.php');
define( 'DB_HOST', 'localhost' );
define( 'DB_USERNAME', 'root');
define( 'DB_PASSWORD', '');
define( 'DB_NAME', 'user_login');

//Google App Details
define('GOOGLE_APP_NAME', 'CultivatingHappyness Google+ login');
define('GOOGLE_OAUTH_CLIENT_ID', 'YOUR CLIENT ID');
define('GOOGLE_OAUTH_CLIENT_SECRET', 'YOUR CLIENT SECRET');
define('GOOGLE_OAUTH_REDIRECT_URI', 'http://localhost/user_login/');
define("GOOGLE_SITE_NAME", 'http://localhost/');

function __autoload($class)
{
	$parts = explode('_', $class);
	$path = implode(DIRECTORY_SEPARATOR,$parts);
	require_once $path . '.php';
}

Step 4:

Create index.php and add below script to make OAuth API request to google while user clicking on the Signin with Google+ button.

<?php 
ob_start();
session_start();
require_once 'config.php'; 

//initalize user class
$user_obj = new Cl_User();

/*******Google ******/
require_once 'Google/src/config.php';
require_once 'Google/src/Google_Client.php';
require_once 'Google/src/contrib/Google_PlusService.php';
require_once 'Google/src/contrib/Google_Oauth2Service.php'; 

 $client = new Google_Client();
$client->setScopes(array('https://www.googleapis.com/auth/plus.login','https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/plus.me'));
$client->setApprovalPrompt('auto');

$plus       = new Google_PlusService($client);
$oauth2     = new Google_Oauth2Service($client);
//unset($_SESSION['access_token']);

if(isset($_GET['code'])) {
	$client->authenticate(); // Authenticate
	$_SESSION['access_token'] = $client->getAccessToken(); // get the access token here
	header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}

if(isset($_SESSION['access_token'])) {
	$client->setAccessToken($_SESSION['access_token']);
}

if ($client->getAccessToken()) {
	$_SESSION['access_token'] = $client->getAccessToken();
	$user         = $oauth2->userinfo->get();
	try {
		$user_obj->google_login( $user );
	}catch (Exception $e) {
		$error = $e->getMessage();
	}
}  
/*******Google ******/

?>
<?php 
	if( !empty( $_POST )){
		try {

			$data = $user_obj->login( $_POST );
			if(isset($_SESSION['logged_in']) && $_SESSION['logged_in']){
				header('Location: home.php');
			}
		} catch (Exception $e) {
			$error = $e->getMessage();
		}
	}
	//print_r($_SESSION);
	if(isset($_SESSION['logged_in']) && $_SESSION['logged_in']){
		header('Location: home.php');
	}
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Smart Login Page</title>
	<link href='http://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'>
    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/font-awesome.min.css" rel="stylesheet">
    <link href="css/login.css" rel="stylesheet">
    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="js/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>
  </head>
  <body>
	<div class="container">
		<?php require_once 'templates/ads.php';?>
		<div class="login-form">
			<?php require_once 'templates/message.php';?>
			<h1 class="text-center">Smart Tutorials</h1>
			<div class="form-header">
				<i class="fa fa-user"></i>
			</div>
			<form id="login-form" method="post" class="form-signin" role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>">
				<input name="email" id="email" type="email" class="form-control" placeholder="Email address" autofocus> 
				<input name="password" id="password" type="password" class="form-control" placeholder="Password"> 
				<button class="btn btn-block bt-login" type="submit">Sign in</button>

				<h4 class="text-center login-txt-center">Alternatively, you can log in using:</h4>

				<!-- <a class="btn btn-default facebook" href="<?php //echo $helper->getLoginUrl(array('email'));?>"> <i class="fa fa-facebook modal-icons"></i> Sign In with Facebook </a> -->  
				<a class="btn btn-default google" href="<?php echo $client->createAuthUrl();?>"> <i class="fa fa-google-plus modal-icons"></i> Sign In with Google+ </a>  
				<!-- <a class="btn btn-default twitter" href="<?php //echo $url;?>"> <i class="fa fa-twitter modal-icons"></i> Sign In with Twitter </a> -->
			</form>
			<div class="form-footer">
				<div class="row">
					<div class="col-xs-6 col-sm-6 col-md-6">
						<i class="fa fa-lock"></i>
						<a href="forget_password.php"> Forgot password? </a>

					</div>

					<div class="col-xs-6 col-sm-6 col-md-6">
						<i class="fa fa-check"></i>
						<a href="register.php"> Sign Up </a>
					</div>
				</div>
			</div>
		</div>
	</div>
	<!-- /container -->
    <script src="js/jquery.validate.min.js"></script>
    <script src="js/login.js"></script>
  </body>
</html>
<?php ob_end_flush(); ?>

 

Step5 :

The google_login() method in the User class will insert response in Database and let user to login to web-application. As well it validates response and gives validation results.

/**
	 * This method will handle google login
	 * @param array $data
	 * @throws Exception
	 * @return boolean true or false based on success or failure
	 */

	public function google_login( array $data )
	{
		if( !empty( $data ) ){
			// Trim all the incoming data:
			$trimmed_data = array_map('trim', $data);
		}

		// escape variables for security
		$name = mysqli_real_escape_string( $this->_con, $trimmed_data['name'] );
		$email = mysqli_real_escape_string( $this->_con, $trimmed_data['email'] );
		$social_id = mysqli_real_escape_string( $this->_con, $trimmed_data['id'] );
		$picture = mysqli_real_escape_string( $this->_con, $trimmed_data['picture'] );

		$query = "SELECT user_id, name, email, created FROM users where email = '$email' and social_id = '$social_id' ";
		$result = mysqli_query($this->_con, $query);
		$data = mysqli_fetch_assoc($result);
		$count = mysqli_num_rows($result);
		if( $count == 1){
			$_SESSION = $data;
			$_SESSION['logged_in'] = true;
			return true;
		}else{

			$query = "INSERT INTO users (user_id, name, email, social_id, picture, created) VALUES (NULL, '$name', '$email', '$social_id', '$picture', CURRENT_TIMESTAMP)";
			if(mysqli_query($this->_con, $query));
			$query = "SELECT user_id, name, email, created FROM users where email = '$email' and social_id = '$social_id' ";
			$result = mysqli_query($this->_con, $query);
			$data = mysqli_fetch_assoc($result);
			$count = mysqli_num_rows($result);
			if( $count == 1){
				$_SESSION = $data;
				$_SESSION['logged_in'] = true;
				return true;
			}else{
				throw new Exception( LOGIN_FAIL );
			}
		}
	}

 .

Download Premium Only Scripts & 80+ Demo scripts Instantly at just 1.95 USD per month + 10% discount to all Exclusive Scripts

If you want any of my script need to be customized according to your business requirement,

Please feel free to contact me [at] muni2explore[at]gmail.com

Note: But it will be charged based on your customization requirement

Get Updates, Scripts & Other Useful Resources to your Email

Join 10,000+ Happy Subscribers on feedburner. Click to Subscribe (We don't send spam)
Every Email Subsciber could have access to download 100+ demo scripts & all future scripts.

Get Instant Script Download Access!