Login with Google Account Using PHP + MySQL (Source Code)

login with google account using PHP + MySQL. In this tutorial, i am going to show you how to create google login application in PHP + MySQL.

And through this tutorial, i will provide you complete source code of login with google account using PHP + MySQL. As well as you can free use it.

Login with Google Account Using PHP + MySQL (Source Code)

  • Step 1 – Start Apache Web Server
  • Step 2 – Create PHP Project
  • Step 3 – Create Table and Database Connection File
  • Step 4 – Create Google API Console Account
  • Step 5 – Download Google Auth Library
  • Step 6 – Create Login.php File
  • Step 7 – Create Home.php File
  • Step 8 – Create Logout.php File
  • Step 9 – Test This PHP App

Step 1 – Start Apache Web Server

Now, you need to start your apache web server. And as well as start Apache and mysql web server. You can see in the image below how to start apache and mysql server:

start xampp apache mysql server
start xampp apache mysql server

Step 2 – Create PHP Project

In step 2, navigate to your xampp/htdocs/ directory. And inside xampp/htdocs/ directory, create one folder. And you can name this folder anything.

Here, I will “demo” the name of this folder. Then open this folder in any text editor (i will use sublime text editor).

Step 3 – Create Table and Database Connection File

In step 3,, you need to create database and table. So run the following sql query to create database and table:

CREATE DATABASE my_db;


CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `google_id` varchar(150) COLLATE utf8mb4_unicode_ci NOT NULL,
 `name` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
 `email` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
 `profile_image` text COLLATE utf8mb4_unicode_ci NOT NULL,
 PRIMARY KEY (`id`),
 UNIQUE KEY `google_id` (`google_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Then create a php file that named db_connection.php. Which is used to connect phpmyadmin mysql database to project folder(demo).

So, now create db_connection.php file and add the below given code into your file:

<?php
session_start();
session_regenerate_id(true);
// change the information according to your database
$db_connection = mysqli_connect("localhost","root","","my_db");
// CHECK DATABASE CONNECTION
if(mysqli_connect_errno()){
    echo "Connection Failed".mysqli_connect_error();
    exit;
}

Step 4 – Create Google API Console Account

Create google api console account and setup it: Then get Google OAuth 2.0 Client Secret and Client ID.

So follow the below steps to get Google OAuth 2.0 Client Secret & the Client ID:

  1. Login to Google API ConsoleFirst, go to the Google API Console and login with your Google account.
  2. Create a New Project, After login to your account, Go to Select a project > New Project, and create a new.
  3. Select your projectAfter creating a new project, Now select the project.select the project
  4. Configure Consent ScreenNow go to the credentials and configure the consent screen –configure the consent screen
  5. Last step of configuring consent screenEnter the application name and save it –Last step of configuring consent screen
  6. Creating OAuth CredentialsAgain go to the credentials and create OAuth Credential:Creating OAuth Credentials
  7. OAuth for web applicationChoose the web application > type the name > enter the redirect URL > Click on the create button:OAuth  for web application
  8. The Client id and Client secretNow you have got the client id and client secret, copy them and save elsewhere:
  9. .oauth client id and client secret

Step 5 – Download Google Auth Library

In this step 5, You have to download the Google APIs Client Library for PHP. Then Extract the Google APIs Zip file and rename it to google-api into your php app.

Step 6 – Create Login.php File

Create login.php file; which is used to display google login button. So add into login.php file; as shown below:

<?php
require 'db_connection.php';

if(isset($_SESSION['login_id'])){
    header('Location: home.php');
    exit;
}

require 'google-api/vendor/autoload.php';

// Creating new google client instance
$client = new Google_Client();

// Enter your Client ID
$client->setClientId('YOUR_CLIENT_ID');
// Enter your Client Secrect
$client->setClientSecret('YOUR_CLIENT_SECRECT');
// Enter the Redirect URL
$client->setRedirectUri('http://localhost/google_login/login.php');

// Adding those scopes which we want to get (email & profile Information)
$client->addScope("email");
$client->addScope("profile");


if(isset($_GET['code'])):

    $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);

    if(!isset($token["error"])){

        $client->setAccessToken($token['access_token']);

        // getting profile information
        $google_oauth = new Google_Service_Oauth2($client);
        $google_account_info = $google_oauth->userinfo->get();
    
        // Storing data into database
        $id = mysqli_real_escape_string($db_connection, $google_account_info->id);
        $full_name = mysqli_real_escape_string($db_connection, trim($google_account_info->name));
        $email = mysqli_real_escape_string($db_connection, $google_account_info->email);
        $profile_pic = mysqli_real_escape_string($db_connection, $google_account_info->picture);

        // checking user already exists or not
        $get_user = mysqli_query($db_connection, "SELECT `google_id` FROM `users` WHERE `google_id`='$id'");
        if(mysqli_num_rows($get_user) > 0){

            $_SESSION['login_id'] = $id; 
            header('Location: home.php');
            exit;

        }
        else{

            // if user not exists we will insert the user
            $insert = mysqli_query($db_connection, "INSERT INTO `users`(`google_id`,`name`,`email`,`profile_image`) VALUES('$id','$full_name','$email','$profile_pic')");

            if($insert){
                $_SESSION['login_id'] = $id; 
                header('Location: home.php');
                exit;
            }
            else{
                echo "Sign up failed!(Something went wrong).";
            }

        }

    }
    else{
        header('Location: login.php');
        exit;
    }
    
else: 
    // Google Login Url = $client->createAuthUrl(); 
?>

    <a class="login-btn" href="<?php echo $client->createAuthUrl(); ?>">Login</a>

<?php endif; ?>

Step 7 – Create Home.php File

In step 7, create one file that named home.php file. This php file code will display logged in user data; so add the following code into home.php file:

<?php
require 'db_connection.php';

if(!isset($_SESSION['login_id'])){
    header('Location: login.php');
    exit;
}

$id = $_SESSION['login_id'];

$get_user = mysqli_query($db_connection, "SELECT * FROM `users` WHERE `google_id`='$id'");

if(mysqli_num_rows($get_user) > 0){
    $user = mysqli_fetch_assoc($get_user);
}
else{
    header('Location: logout.php');
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title><?php echo $user['name']; ?></title>
    <style>
        *,
        *::before,
        *::after {
            box-sizing: border-box;
            -webkit-box-sizing: border-box;
        }
        body{
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f7f7ff;
            padding: 10px;
            margin: 0;
        }
        ._container{
            max-width: 400px;
            background-color: #ffffff;
            padding: 20px;
            margin: 0 auto;
            border: 1px solid #cccccc;
            border-radius: 2px;
        }

        ._img{
            overflow: hidden;
            width: 100px;
            height: 100px;
            margin: 0 auto;
            border-radius: 50%;
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
        }
        ._img > img{
            width: 100px;
            min-height: 100px;
        }
        ._info{
            text-align: center;
        }
        ._info h1{
            margin:10px 0;
            text-transform: capitalize;
        }
        ._info p{
            color: #555555;
        }
        ._info a{
            display: inline-block;
            background-color: #E53E3E;
            color: #fff;
            text-decoration: none;
            padding:5px 10px;
            border-radius: 2px;
            border: 1px solid rgba(0, 0, 0, 0.1);
        }
    </style>
</head>
<body>
    <div class="_container">
        <div class="_img">
            <img src="<?php echo $user['profile_image']; ?>" alt="<?php echo $user['name']; ?>">
        </div>
        <div class="_info">
            <h1><?php echo $user['name']; ?></h1>
            <p><?php echo $user['email']; ?></p>
            <a href="logout.php">Logout</a>
        </div>
    </div>
</body>
</html>

Step 8 – Create Home.php File

In step 8, create one file that named logout.php file. This php file code will destroy logged in user session; so add the following code into logout.php file:

<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();

// Unset all of the session variables.
$_SESSION = array();

// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}

// Finally, destroy the session.
session_destroy();
header("Location: login.php");
exit;
?>

Step 9 – TestThis PHP App

Finally, you need to open your browser and type http://localhost/demo/login.php this run project on local machine.

Conclusion

login with google account using PHP + MySQL. In this tutorial, You have learned how to create google login application in PHP + MySQL.

Recommended PHP Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *