Last active
January 19, 2020 02:46
-
-
Save perials/271424bb42dd916a2001a8fa5022bee9 to your computer and use it in GitHub Desktop.
Google login using PHP and Google Client Library version 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* Please install Google client library using composer. Use below command | |
* composer require google/apiclient:"^2.0" | |
*/ | |
// Turn ON error reporting | |
error_reporting(E_ALL); | |
ini_set('display_errors', 1); | |
// include autoload.php for including Google client library installed using composer | |
require('vendor/autoload.php'); | |
// Set below keys | |
define('GOOGLE_CLIENT_ID', 'enter-google-client-id'); | |
define('GOOGLE_CLIENT_SECRET', 'enter-google-client-secret'); | |
define('GOOGLE_REDIRECT_URL', 'redirect-url-which-is-url-to-current-script'); | |
$client = new Google_Client(); | |
$client->setApplicationName('Sample Google Login by Perials'); | |
$client->setClientId(GOOGLE_CLIENT_ID); | |
$client->setClientSecret(GOOGLE_CLIENT_SECRET); | |
$client->setRedirectUri(GOOGLE_REDIRECT_URL); | |
if (isset($_GET['code'])) { | |
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']); | |
// store the token in Session | |
$_SESSION['access_token'] = $token; | |
} | |
// if access_token session is set then user has already logged in | |
if($_SESSION['access_token']) { | |
$attributes = $client->verifyIdToken($_SESSION['access_token']['id_token'], GOOGLE_CLIENT_ID); | |
print_r($attributes); | |
// Above will print an array which should contain below keys | |
// name | |
// picture | |
} | |
else { | |
$scopes = [ Google_Service_Oauth2::USERINFO_PROFILE, Google_Service_Oauth2::USERINFO_EMAIL ]; | |
$authUrl = $client->createAuthUrl($scopes); | |
?> | |
<a href="<?php echo $authUrl; ?>">Click to login via Google</a> | |
<?php | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment