PHP Goggle Login for Website
How To Add Google Login to PHP Website
Nowadays, many websites allow the users to instantly log in with their social media accounts such as Google, Facebook, Twitter, Linked-in etc. With this, he doesn't need to create a separate account in that website in order to use it.
This tutorial will teach you, how to integrate a Google login to a PHP website.
There are only four steps to log in with Google PHP SDK:
- Create a Google credentials for your application, using this link .
- Create an application on the web server. Create Database usersdb in MySQL.
- Download Google SDK.
- Integrate Google Login and Get User Information
1. Create a Google credentials for an application.
Once you got credentials, start creating project in server. And follow the step-2.
2. Create an Application on Server and Create Database in MySQL.
Project folder:
Query for Table:
Create the table in the database, with this query, given down below.
-- -- Table structure for table `users` -- CREATE TABLE `users` ( `id` int(11) NOT NULL, `email` varchar(100) NOT NULL DEFAULT '', `uname` varchar(60) NOT NULL, `first_name` varchar(50) NOT NULL DEFAULT '', `last_name` varchar(50) NOT NULL DEFAULT '', `gender` varchar(50) NOT NULL DEFAULT '', `full_name` varchar(100) NOT NULL DEFAULT '', `picture` varchar(255) NOT NULL DEFAULT '', `verifiedEmail` int(11) NOT NULL DEFAULT 0, `token` varchar(255) NOT NULL DEFAULT '', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; -- -- Dumping data for table `users`
3. Download PHP Google SDK.
Composer is the recommended method of installing libraries on the platform and I will use it to install Google SDK.
Run the given command to install google login SDK.
1. Open command prompt, and move to your project folder and give the following command as shown
C:\xampp3\htdocs\google-login> composer require google/auth
It will create a composer.json, composer.lock files and vendor folder in the application folder.
4. How to Use PHP SDK to Integrate Google Login and Get User Information.
Create given files in the application folder: config.php, Index.php and welcome.php,logout.php
Add the following code to config.php file. Comments are added to explain the code.
config.php
<?php require_once 'vendor/autoload.php'; session_start(); /* ********* init configuration *********** */ $clientID = "Your_clientID"; $clientSecret = "Your_clientSecret"; $redirectUri = "http://localhost/google-login/welcome.php"; /* ********* Create Client Request to access Google API *********** */ $client = new Google_Client(); $client->setClientId($clientID); $client->setClientSecret($clientSecret); $client->setRedirectUri($redirectUri); $client->addScope("email"); $client->addScope("profile"); /* *********Connect to database *********** */ $hostname = "localhost"; $dbusername = "root"; $dbpassword = ""; $database = "usersdb"; $conn = mysqli_connect($hostname, $dbusername, $dbpassword, $database);
?>
Goto TOP☝ Menu
index.php
index page is a Home page, displays a Google login button link.
In this file, you need to include 2 things.
1. Google Login Credentials.
2. Redirecting page link.
<?php
/* **************** Linking Library************* */
include("vendor/autoload.php"); $client = new Google\Client; $client->setClientId("Your_clientID"); $client->setClientSecret("Your_clientSecret"); $client->setRedirectUri("http://localhost/google-login/welcome.php"); $client->addScope("email"); $client->addScope("profile"); $url = $client->createAuthUrl(); ?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Google Login Example using PHP</title> <meta content='width=device-width, initial-scale=1, maximum-scale=1' name='viewport'/> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> </head> <body> <div class="container"> <br /> <h2 align="center">PHP Login With Google</h2> <br /> <div class="panel panel-default"> <?php echo '<div align="center">'; ?> <a href="<?= $url ?>" alt="google-login"><img src="login.png" /><br>google_login</a> </div> </div> </div> </body> </html>
On successful logging, you will be redirected to welcome.php. This file should be registered in google developer's console.
http://google-login/welcome.php
Create the welcome.php with following code as shown down below.
welcome.php
This file performs authentication. Collects user information on successful login, and inserts this data in database if the user first time logged in. Next, It reads data from the database and initiates a session, and stores user data in the session variable.
<?php require_once 'config.php'; $userinfo =array(); /* **************** authenticate code from Google OAuth Flow************* */ if (isset($_GET['code'])) { $token = $client->fetchAccessTokenWithAuthCode($_GET['code']); $client->setAccessToken($token['access_token']); /* **************** get profile info ************* */ $google_oauth = new Google_Service_Oauth2($client); $google_account_details = $google_oauth->userinfo->get(); $userinfo = [ 'email' => $google_account_details['email'], 'first_name' => $google_account_details['givenName'], 'last_name' => $google_account_details['familyName'], 'gender' => $google_account_details['gender'], 'full_name' => $google_account_details['name'], 'picture' => $google_account_details['picture'], 'verifiedEmail' => $google_account_details['verifiedEmail'], 'token' => $google_account_details['id'], ]; /* ********* Checking if user availablity in Database ************* */ $sql_query = "SELECT * FROM users WHERE email ='{$userinfo['email']}'"; $result = mysqli_query($conn, $sql_query); if (mysqli_num_rows($result) > 0) { /* **************** user is exists ************* */ $userinfo = mysqli_fetch_assoc($result); $token = $userinfo['token']; } else { /* **************** user is not exists ************* */ $_SESSION['user_token'] = $token; $sql_query = "INSERT INTO users (email, first_name, last_name, gender, full_name, picture, verifiedEmail, token) VALUES ('{$userinfo['email']}', '{$userinfo['first_name']}', '{$userinfo['last_name']}', '{$userinfo['gender']}', '{$userinfo['full_name']}', '{$userinfo['picture']}', '{$userinfo['verifiedEmail']}', '{$userinfo['token']}')"; $result = mysqli_query($conn, $sql_query); if ($result) { $token = $userinfo['token']; } else { echo "User is not created"; die(); } } /* **************** save user data into session ************* */ $_SESSION['user_token'] = $token; } else { if (!isset($_SESSION['user_token'])) { header("Location: index.php"); die(); } /* ************** checking if user is already exists in database************* */ $_SESSION['user_token'] = $token; $sql_query = "SELECT * FROM users WHERE token ='{$_SESSION['user_token']}'"; $result = mysqli_query($conn, $sql_query); if (mysql_queryi_num_rows($result) > 0) { // user is exists $userinfo = mysql_queryi_fetch_assoc($result); } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Google Login Example using PHP</title> <meta content='width=device-width, initial-scale=1, maximum-scale=1' name='viewport'/> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Welcome</title> </head> <body align="center"> <div class="container"> <br /> <h1 align="center">PHP Login With Google</h1> <br /> <div class="panel panel-default"> <h2 align="center" > welcome </h2> <img id ="myImage" src="<?php echo $userinfo['picture']; ?>" alt="" width="90px" height="90px"> <ul> <li><b>Full Name: </b><?= $userinfo['full_name'] ?></li> <li><b>Email Address:</b> <?= $userinfo['email'] ?></li> <li><b>Gender: </b><?= $userinfo['gender'] ?></li> <li><b><a href="logout.php">Logout</a></b></li> </ul> </div> </body> </html>
Goto TOP Menu
Logout.php
When user clicks logout. He will be redirected to home page(index.php).
<?php /* ********* Clears the Session and redirects to Index page ************* */ session_start(); unset($_SESSION['user_token']); session_destroy(); header("Location: index.php"); ?>
Output:
On successful login it displays a welcome page with user profile details(name, email, gender etc.).
Comments
Post a Comment