Dear Reader, let us we know that “How to create a google plus login in PHP“. So in this Tutorial, We Learn Step By Step google plus login Process in PHP.
Login and Registration is the very common requirement. In other words, we can say Login and Registration are very necessary for websites and applications. Visitors do not want to fill the registration form and wants an easy process for the same.
We are going to Implement Login and Registration using Google Plus. Google plus login and Registration is very simple.
In this tutorial on a single click, we will store the user details in the database.
Now let’s start the Google Plus Login Process in step by step.
First, we see a Snapshot of the Google plus login button.
And you can also see Live “Demo” by click on below Demo button
Step 1:- First of all we need to create a Google plus App from
How to create Google plus App and App Secret
Step 2:- Please download Google API client from here
Step 3:- Now we need to create the database like “php_demo”
Step 4:- Now create a table “users” in a database using the below SQL code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `oauth_provider` enum('','facebook','google','twitter') COLLATE utf8_unicode_ci NOT NULL, `oauth_uid` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `first_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL, `last_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL, `email` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `gender` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, `locale` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, `cover` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `picture` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `link` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created` datetime NOT NULL, `modified` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; |
Step 5:- Now we need to create a user_config.php file in the root directory and paste the below code
like “http://localhost/php_demo/login-with-gmail/user_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 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 |
<?php /* * User Class * This class is used for database related (connect, insert, and update) operations * @author webpreparations.com * @url http://www.webpreparations.com * @license http://www.webpreparations.com/license */ class User { private $dbHost = "localhost"; private $dbUsername = "root"; private $dbPassword = ""; private $dbName = "php_demo"; private $userTbl = 'users'; function __construct() { if(!isset($this->db)) { // Connect to the database $conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName); if($conn->connect_error) { die("Failed to connect with MySQL: " . $conn->connect_error); } else { $this->db = $conn; } } } function checkUser($userData = array()) { if(!empty($userData)) { // Check whether user data already exists in the database $prevQuery = "SELECT * FROM ".$this->userTbl." WHERE oauth_provider = '".$userData['oauth_provider']."' AND oauth_uid = '".$userData['oauth_uid']."'"; $prevResult = $this->db->query($prevQuery); if($prevResult->num_rows > 0) { // Update user data if already exists $query = "UPDATE ".$this->userTbl." SET first_name = '".$userData['first_name']."', last_name = '".$userData['last_name']."', email = '".$userData['email']."', gender = '".$userData['gender']."', locale = '".$userData['locale']."', picture = '".$userData['picture']."', link = '".$userData['link']."', modified = NOW() WHERE oauth_provider = '".$userData['oauth_provider']."' AND oauth_uid = '".$userData['oauth_uid']."'"; $update = $this->db->query($query); } else { // Insert user data in the database $query = "INSERT INTO ".$this->userTbl." SET oauth_provider = '".$userData['oauth_provider']."', oauth_uid = '".$userData['oauth_uid']."', first_name = '".$userData['first_name']."', last_name = '".$userData['last_name']."', email = '".$userData['email']."', gender = '".$userData['gender']."', locale = '".$userData['locale']."', picture = '".$userData['picture']."', link = '".$userData['link']."', created = NOW(), modified = NOW()"; $insert = $this->db->query($query); } // Get user data from the database $result = $this->db->query($prevQuery); $userData = $result->fetch_assoc(); } // Return user data return $userData; } } |
Step 6:- Now we need to create an index.php file in the root directory and paste the below code
like “http://localhost/php_demo/login-with-gmail/index.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 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 |
<?php /*--------for include config and user config start ------*/ require_once 'gp_config.php'; require_once 'user_config.php'; /*--------for include config and user config close ------*/ if(isset($_GET['code'])) { $gClient->authenticate($_GET['code']); $_SESSION['token'] = $gClient->getAccessToken(); header('Location: ' . filter_var($redirectURL, FILTER_SANITIZE_URL)); } if(isset($_SESSION['token'])) { $gClient->setAccessToken($_SESSION['token']); } if($gClient->getAccessToken()) { // Get user profile data from google $gp_user_profile = $google_oauthV2->userinfo->get(); // Initialize User class $user = new User(); // Getting user profile info $gp_user_data = array(); $gp_user_data['oauth_uid'] = !empty($gp_user_profile['id'])?$gp_user_profile['id']:''; $gp_user_data['first_name'] = !empty($gp_user_profile['given_name'])?$gp_user_profile['given_name']:''; $gp_user_data['last_name'] = !empty($gp_user_profile['family_name'])?$gp_user_profile['family_name']:''; $gp_user_data['email'] = !empty($gp_user_profile['email'])?$gp_user_profile['email']:''; $gp_user_data['gender'] = !empty($gp_user_profile['gender'])?$gp_user_profile['gender']:''; $gp_user_data['locale'] = !empty($gp_user_profile['locale'])?$gp_user_profile['locale']:''; $gp_user_data['picture'] = !empty($gp_user_profile['picture'])?$gp_user_profile['picture']:''; $gp_user_data['link'] = !empty($gp_user_profile['link'])?$gp_user_profile['link']:''; // Insert or update user data to the database $gp_user_data['oauth_provider'] = 'google'; $user_data = $user->checkUser($gp_user_data); // Storing user data in the session $_SESSION['$user_data'] = $user_data; // Render user profile data if(!empty($user_data)){ $output = '<h2>Google+ Profile Details </h2>'; $output .= '<img src="'.$user_data['picture'].'">'; $output .= '<p>Google ID : ' . $user_data['oauth_uid'].'</p>'; $output .= '<p>Name : ' . $user_data['first_name'].' '.$user_data['last_name'].'</p>'; $output .= '<p>Email : ' . $user_data['email'].'</p>'; $output .= '<p>Gender : ' . $user_data['gender'].'</p>'; $output .= '<p>Locale : ' . $user_data['locale'].'</p>'; $output .= '<p>Logged in with : Google</p>'; //$output .= '<p><a href="'.$userData['link'].'" target="_blank">Click to visit Google+</a></p>'; $output .= '<a href="'.$user_data['link'].'" target="_blank"><button class="btn btn-success">Click here to visit Google+</button></a><br><br>'; //$output .= '<p>Logout from <a href="logout.php">Google</a></p>'; $output .= '<a href="logout.php"><button class="btn btn-danger">Logout from Google</button></a><br><br><br>'; }else{ $output = '<h3 style="color:red">Some problem occurred, please try again.</h3>'; } } else { // Get login url $authUrl = $gClient->createAuthUrl(); // Render google login button $output = '<a href="'.filter_var($authUrl, FILTER_SANITIZE_URL).'"><img src="images/google-sign-in.png" alt=""/></a>'; } ?> <!--<div class="container"> Display login button / Google profile information <?php echo $output; ?> </div>--> <!DOCTYPE html> <html lang="en"> <head> <title>How to create google plus login in PHP</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class="container-fluid"> <center> <h1 class="alert alert-success">How to create google plus login in PHP</h1> </center> <div class="row"> <div class="col-sm-4 col-md-4"> </div> <div class="col-sm-4 col-md-4"> <?php echo $output; ?> </div> <div class="col-sm-4 col-md-4"> </div> </div> </div> </body> </html> |
Step 7:- Now we need to create a gp_config.php file in the root directory and paste the below code
like “http://localhost/php_demo/login-with-gmail/gp_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 27 28 29 30 31 32 33 34 35 |
<?php if(!session_id()) { session_start(); } /*---------- for include google library start--------------*/ include_once 'google-api-php-client/src/Google_Client.php'; include_once 'google-api-php-client/src/contrib/Google_Oauth2Service.php'; /*---------- for include google library close--------------*/ /* * Configuration and setup Google API */ /* * Configuration and setup Google API */ $clientId = '956419711890-hd1iua5i7g1m9aan2afoggdblki57jr3.apps.googleusercontent.com'; $clientSecret = 'JUcWChW0Qm4LeHyXvqTqwJbl'; $redirectURL = 'http://localhost/php_demo/login-with-gmail/index.php'; //Callback URL // Call Google API $gClient = new Google_Client(); $gClient->setApplicationName('Login to Writoversal'); $gClient->setClientId($clientId); $gClient->setClientSecret($clientSecret); $gClient->setRedirectUri($redirectURL); $google_oauthV2 = new Google_Oauth2Service($gClient); |
Step 8:- At last we need to create a logout.php file in the root directory and paste the below code
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 |
<?php /*-------------- for include config file start -------------*/ require_once 'gp_config.php'; /*-------------- for include config file close -------------*/ // Remove token and user data from the session /*------------ for removing token and user data start --------*/ unset($_SESSION['token']); unset($_SESSION['$user_data']); /*------------ for removing token and user data close --------*/ /*------------ for reset oauth access token start --------*/ $gClient->revokeToken(); /*------------ for reset oauth access token close --------*/ // for destroy entire session data session_destroy(); // for redirection to home page header("Location:index.php"); ?> |
Step 9:- Now run your project, so we need to type in browser localhost/your_project_name/index.php
like
“http://localhost/php_demo/login-with-gmail/index.php” then you can see the result as in below snapshot, you can click on google plus login
Congratulations you have successfully created “How to create a google plus login in PHP“, if you like this post and was helpful for you then share this post on social media and if you have any query then please contact us or comment below, Thanks