Welcome folks today in this blog post we will be using php
and mysql
database to integrate google oauth2
login in browser and display the details in browser. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new composer.json
file and copy paste the below code
composer.json
1 2 3 4 5 |
{ "require": { "google/apiclient": "^2.0" } } |
Now we need to execute the below command to install the package
which are listed below
composer update
And now it will create the vendor
folder inside the root directory as shown below in the directory structure as shown below
And then we need to go to google cloud
developer console and then we need to create the oauth2
client id and secret as shown below
Making the Database and Tables
And now we need to go to mysql
section and here we need to create a database and inside it we need to go to the sql
section and paste the below sql code as shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
-- phpMyAdmin SQL Dump -- version 5.2.0 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: May 30, 2022 at 05:47 PM -- Server version: 10.4.24-MariaDB -- PHP Version: 8.1.6 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `youtube-google-login` -- -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `id` int(11) NOT NULL, `email` varchar(100) NOT NULL DEFAULT '', `first_name` varchar(50) NOT NULL DEFAULT '', `last_name` 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 '' ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Indexes for dumped tables -- -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; |
As you can see we have defined the table as shown below
Connection to Database
Now we need to create the config.php
file and copy paste the below code to create the connection to the database as shown below
config.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<?php require_once 'vendor/autoload.php'; session_start(); // init configuration $clientID = '###accesstoken###'; $clientSecret = '###clientsecret###'; $redirectUri = '###redirecturi###'; // 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"; $username = "root"; $password = ""; $database = "youtube-google-login"; $conn = mysqli_connect($hostname, $username, $password, $database); |
And now we need to create the index.php
file where we will be redirecting
the user to the welcome.php
page if the access token is present inside the session as shown below
index.php
1 2 3 4 5 6 7 8 |
<?php require_once 'config.php'; if (isset($_SESSION['user_token'])) { header("Location: welcome.php"); } else { echo "<a href='" . $client->createAuthUrl() . "'>Google Login</a>"; } |
Displaying Profile Details
Now we need to show the profile
details of the user after successful login as shown below
welcome.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
<?php require_once 'config.php'; // 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_info = $google_oauth->userinfo->get(); $userinfo = [ 'email' => $google_account_info['email'], 'first_name' => $google_account_info['givenName'], 'last_name' => $google_account_info['familyName'], 'full_name' => $google_account_info['name'], 'picture' => $google_account_info['picture'], 'verifiedEmail' => $google_account_info['verifiedEmail'], 'token' => $google_account_info['id'], ]; // checking if user is already exists in database $sql = "SELECT * FROM users WHERE email ='{$userinfo['email']}'"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { // user is exists $userinfo = mysqli_fetch_assoc($result); $token = $userinfo['token']; } else { // user is not exists $sql = "INSERT INTO users (email, first_name, last_name, full_name, picture, verifiedEmail, token) VALUES ('{$userinfo['email']}', '{$userinfo['first_name']}', '{$userinfo['last_name']}','{$userinfo['full_name']}', '{$userinfo['picture']}', '{$userinfo['verifiedEmail']}', '{$userinfo['token']}')"; $result = mysqli_query($conn, $sql); 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 $sql = "SELECT * FROM users WHERE token ='{$_SESSION['user_token']}'"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { // user is exists $userinfo = mysqli_fetch_assoc($result); } } ?> <!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.0"> <title>Welcome</title> </head> <body> <img src="<?= $userinfo['picture'] ?>" alt="" width="90px" height="90px"> <ul> <li>Full Name: <?= $userinfo['full_name'] ?></li> <li>Email Address: <?= $userinfo['email'] ?></li> <li><a href="logout.php">Logout</a></li> </ul> </body> </html> |
As you can see all this profile information alongside with the accessToken
is inserted in the mysql
database as shown above.
Logout User
Now we need to define the logout.php
file as shown below
logout.php
1 2 3 4 5 6 |
<?php session_start(); unset($_SESSION['user_token']); session_destroy(); header("Location: index.php"); |