PHP and MySQL - Social login and register with Google Account Example

PHP and MySQL - Social login and register with Google Account Example

In this example, I will tell you how to login or signup with google account in PHP application.

Google login api allow user to sign into the website without filling signup form manually.

It helps to increase subscribers on the website because user can easily log in the website using their google account without any registration.

In this example, I will provide you simple step to authenticate users with their google account.

For this example, I will create a users table in MySQL database and include the Google API library in the form.

You must have Google Client ID to authenticate with Google account and you can get this key from Google API Console.

You can create any new project on console or you can go with existing project.

Step 1: Create Users Table

In this first step, I will create a users table for this example.

CREATE TABLE IF NOT EXISTS `users` (

  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,

  `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,

  `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,

  `password` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,

  `remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,

  `created_at` timestamp NULL DEFAULT NULL,

  `updated_at` timestamp NULL DEFAULT NULL,

  `social_id` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,

  PRIMARY KEY (`id`)

) ENGINE=InnoDB  DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci AUTO_INCREMENT=24 ;
Step 2: Create Login View File

In this second step, I will create HTML view having Google login button.

login.php
<!DOCTYPE html>
<html>
<head>
    <title>PHP and MySQL - Login with Google Account Example</title>
    <script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
    <script src="https://apis.google.com/js/platform.js" async defer></script>
    <meta name="google-signin-client_id" content="GOOGLE_SIGNIN_CLIENT_ID" >
</head>
<body>


<center>
    <div class="g-signin2" data-onsuccess="onSignIn"></div>
</center>        


<script type="text/javascript">
    function onSignIn(googleUser) {
      var profile = googleUser.getBasicProfile();


      if(profile){
          $.ajax({
                type: 'POST',
                url: 'social_login.php',
                data: {id:profile.getId(), name:profile.getName(), email:profile.getEmail()}
            }).done(function(data){
                window.location.href = 'dashboard.php';
            }).fail(function() { 
                alert( "Something went wrong !!" );
            });
      }


    }
</script>


</body>
</html>
Step 3: Create PHP file to authenticate user

In this step, I will create PHP file and confiure MySQL database.

social_login.php
<?php

    session_start();

    $_SESSION["id"] = $_POST["id"];
    $_SESSION["name"] = $_POST["name"];
    $_SESSION["email"] = $_POST["email"];

    $mysqli = new mysqli("localhost", "username", "password", "database");

    $query = "SELECT * FROM users WHERE email='".$_POST["email"]."'";
    $data = $mysqli->query($sql);

    if(!empty($data->fetch_assoc())){
        $query1 = "UPDATE users SET social_id='".$_POST["id"]."' WHERE email='".$_POST["email"]."'";
    }else{
        $query1 = "INSERT INTO users (name, email, social_id) VALUES ('".$_POST["name"]."', '".$_POST["email"]."', '".$_POST["id"]."')";
    }

    $mysqli->query($query1);

    echo "Successful authenticated";
?>

In above code, I create database object first and validate if email is exist or not in users table, If it exist then I update the social id generated from Google otherwise I will insert new record of a user in users table.

Step 4: Create User Dashboard Page

In this step, I will create dashboard.php file and you will be redirecting on this page after successfully authenticated with Google account.

dashboard.php
<!DOCTYPE html>
<html>
<head>
    <title>Welcome to ExpertPHP.in</title>
</head>
<body>

<h1>User Dashboard</h1>

<ul>
    <li>ID : <?php echo $_SESSION['id'];  ?></li>
    <li>Name : <?php echo $_SESSION['name'];  ?></li>
    <li>Email : <?php echo $_SESSION['email'];  ?></li>
</ul>

</body>
</html>

Phone: (+91) 8800417876
Noida, 201301