Skip to content

Instantly share code, notes, and snippets.

Last active January 19, 2020 02:46
What would you like to do?
Google login using PHP and Google Client Library version 2
* Please install Google client library using composer. Use below command
* composer require google/apiclient:"^2.0"
// Turn ON error reporting
ini_set('display_errors', 1);
// include autoload.php for including Google client library installed using composer
// 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');
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);
// Above will print an array which should contain below keys
// name
// picture
// email
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment