Here, I'm going to share a very simple example for Login Google using PHP. First of all, we need set up Google API Console.
After setting up Google API Console, we have Client ID and Client secret. Okay, next step, we need library installing from Google to project.
$ composer require google/apiclient:"^2.0"
or your download: https://github.com/googleapis/google-api-php-client/releases
Ok, we have to project directory create define.php file, you can copy the following code given below, paste to file define.php.
<?php
define('GOOGLE_APP_ID','CLIENG_ID');
define('GOOGLE_APP_SECRET','CLIENT_SECRET');
define('GOOGLE_APP_CALLBACK_URL','http://localhost/LoginGoogle/redirect-google.php');
define('LOCALHOST','localhost');
define('USERNAME','root');
define('PASSWORD','');
define('DATABASE','ABC');
?>
Next step, we need to project directory create redirect-google.php file, you can copy the following below code, pass to it:
<?php
require_once('define.php');
$conn = mysqli_connect(LOCALHOST,USERNAME,PASSWORD,DATABASE);
if (!$conn) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
require_once 'google-api-php-client-2.4.0/vendor/autoload.php';
$client = new Google_Client();
$client->setClientId(GOOGLE_APP_ID);
$client->setClientSecret(GOOGLE_APP_SECRET);
$client->setRedirectUri(GOOGLE_APP_CALLBACK_URL);
$client->addScope("email");
$client->addScope("profile");
if (isset($_GET['code'])) {
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
$client->setAccessToken($token['access_token']);
$google_oauth = new Google_Service_Oauth2($client);
$google_account_info = $google_oauth->userinfo->get();
$email = $google_account_info->email;
$name = $google_account_info->name;
$check = "SELECT * FROM `users` WHERE `email`='".$email."' and `name`='".$name."'";
$result = mysqli_query($conn,$sql);
$rowcount=mysqli_num_rows($result);
if($rowcount>0){
header('location:home');
}
else{
}
} else {
echo "<a href='".$client->createAuthUrl()."'>Google Login</a>";
}
Okay, we have configution success, you can run test: http://localhost/LoginGoogle/redirect-google.php. you will see it.
Success!
History
- 27th September, 2019: Initial version
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.