Please support us by disabling ad blocker for ...

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.

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






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.

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`
USE `user_login`;

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

-- Table structure for table `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,
  PRIMARY KEY (`user_id`),
  UNIQUE KEY `email` (`email`),
  KEY `login` (`password`)

Step 3:

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

@author muni

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_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.

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('','', ''));

$plus       = new Google_PlusService($client);
$oauth2     = new Google_Oauth2Service($client);

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'])) {

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 ******/

	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();
	if(isset($_SESSION['logged_in']) && $_SESSION['logged_in']){
		header('Location: home.php');
<!DOCTYPE html>
<html lang="en">
    <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='' 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=""></script>
      <script src=""></script>
    <!-- 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>
	<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>
			<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> -->
			<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 class="col-xs-6 col-sm-6 col-md-6">
						<i class="fa fa-check"></i>
						<a href="register.php"> Sign Up </a>
	<!-- /container -->
    <script src="js/jquery.validate.min.js"></script>
    <script src="js/login.js"></script>
<?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;

			$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;
				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] muni[at]

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.

  • Tukaram Dokhale

    This is work perfectly. But user information does not stored in database.Please help me.

  • print insert query and run that query manually using PHPmyAdmin… Please that query with me..

  • Tukaram Dokhale

    I have tried google login not signup then login.

  • Sorry…

  • Tukaram Dokhale

    Please give me solution.

  • shatnersbassoon

    Teh Facebook login works fine but cant get the Google one to work correctly. Im not sure whats wrong.

  • ZH ZA

    I have subscribed to download the script for than 12 hours ago. Unfortunately I did not receive any email for the download link. Please help. Tq.

  • Pavan.Maganti

    Working perfectly. Thanks

  • If wrong username and password is entered it is not showing pasword mismatch . As it is showing in the demo


    Fatal error: Class ‘Cl_User’ not found in index.php help me

  • Dimas Djumadi

    Working… Thanks

  • Radhika

    Hi can i get the source code…I have tried downloading but it didn’t work…

  • WebMedia TV

    Great tutorial but im getting an error when login with google with the following: Fatal error: Uncaught exception ‘Google_IOException’ with
    message ‘HTTP Error: (0) Failed to connect to port
    443: Network unreachable’ in
    Stack trace:
    #0 C:xampphtdocsgoogleGooglesrcauthGoogle_OAuth2.php(101):
    #1 C:xampphtdocsgoogleGooglesrcGoogle_Client.php(131):
    Google_OAuth2->authenticate(Array, NULL)
    #2 C:xampphtdocsgoogleindex.php(26):
    #3 {main}
    thrown in C:xampphtdocsgoogleGooglesrcioGoogle_CurlIO.php on line 128

  • Deepak Yadav

    Great Job… Very helpful post…. Thankx aton.

  • jagatsatish chollangi

    where we have to insert google_login method in php project.

  • Karishma

    Very helpfull… Perfect code… Thank you so much
    Can you help me where to insert and how to insert google_login method in the code…

    Thank You…

  • Ramkumar G (BEN)

    Fatal error: Class ‘Cl_User’ not found in index.php help me

    same error did you solve this

Get Instant Script Download Access!