Skip to content

Instantly share code, notes, and snippets.

@Jerry0022
Last active February 27, 2021 22:37
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Jerry0022/27248ce51369e261829a to your computer and use it in GitHub Desktop.
Save Jerry0022/27248ce51369e261829a to your computer and use it in GitHub Desktop.
Google oAuth2, sign up, sign in, logout and show user data. Need to set REDIRECT_URL from google developer console and the https://github.com/google/google-api-php-client cloned in the web directory.
<?php
// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
$google_redirect_url = 'REDIRECT_URL';
//start session
session_start();
//include google api files
include_once 'google-api-php-client/src/Google/autoload.php';
// New Google client
$gClient = new Google_Client();
$gClient->setApplicationName('ApplicationName');
$gClient->setAuthConfigFile('client_secret.json');
$gClient->addScope(Google_Service_Oauth2::USERINFO_PROFILE);
$gClient->addScope(Google_Service_Oauth2::USERINFO_EMAIL);
// New Google Service
$google_oauthV2 = new Google_Service_Oauth2($gClient);
// LOGOUT?
if (isset($_REQUEST['logout']))
{
unset($_SESSION["auto"]);
unset($_SESSION['token']);
$gClient->revokeToken();
header('Location: ' . filter_var($google_redirect_url, FILTER_SANITIZE_URL)); //redirect user back to page
}
// GOOGLE CALLBACK?
if (isset($_GET['code']))
{
$gClient->authenticate($_GET['code']);
$_SESSION['token'] = $gClient->getAccessToken();
header('Location: ' . filter_var($google_redirect_url, FILTER_SANITIZE_URL));
return;
}
// PAGE RELOAD?
if (isset($_SESSION['token']))
{
$gClient->setAccessToken($_SESSION['token']);
}
// Autologin?
if(isset($_GET["auto"]))
{
$_SESSION['auto'] = $_GET["auto"];
}
// LOGGED IN?
if ($gClient->getAccessToken()) // Sign in
{
//For logged in user, get details from google using access token
try {
$user = $google_oauthV2->userinfo->get();
$user_id = $user['id'];
$user_name = filter_var($user['givenName'], FILTER_SANITIZE_SPECIAL_CHARS);
$email = filter_var($user['email'], FILTER_SANITIZE_EMAIL);
$gender = filter_var($user['gender'], FILTER_SANITIZE_SPECIAL_CHARS);
$profile_url = filter_var($user['link'], FILTER_VALIDATE_URL);
$profile_image_url = filter_var($user['picture'], FILTER_VALIDATE_URL);
$personMarkup = "$email<div><img src='$profile_image_url?sz=50'></div>";
$_SESSION['token'] = $gClient->getAccessToken();
// Show user
echo '<br /><a href="'.$profile_url.'" target="_blank"><img src="'.$profile_image_url.'?sz=100" /></a>';
echo '<br /><a class="logout" href="?logout=1">Logout</a>';
$boolarray = Array(false => 'false', true => 'true');
echo '<p>Was automatical login? '.$boolarray[isset($_SESSION["auto"])].'</p>';
//list all user details
echo '<pre>';
print_r($user);
echo '</pre>';
} catch (Exception $e) {
// The user revoke the permission for this App! Therefore reset session token
unset($_SESSION["auto"]);
unset($_SESSION['token']);
header('Location: ' . filter_var($google_redirect_url, FILTER_SANITIZE_URL));
}
}
else // Sign up
{
//For Guest user, get google login url
$authUrl = $gClient->createAuthUrl();
// Fast access or manual login button?
if(isset($_GET["auto"]))
{
header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));
}
else
{
echo '<p>Login?</p>';
echo '<a class="login" href="'.$authUrl.'"><img src="images/google-login-button.png" /></a>';
}
}
?>
@vr2xiq
Copy link

vr2xiq commented Jul 15, 2018

this is an excellent demo. thanks.
If i use this as an authorise of my webpage2.php
should i check the $_SESSION['token'] in webpage2.php?

@vr2xiq
Copy link

vr2xiq commented Jul 15, 2018

When I click "sign out" form this page. I tried to go to gmail by typing the URL, and I can go to inbox directly.
Do I missed something , thanks.

@edwardsmarkf
Copy link

edwardsmarkf commented Mar 5, 2019

Jerry - having wrecked my morning trying several PHP-oAuth2 examples that will not work, your example is the only one that actually does work.

THANK YOU for sharing this. i wish i had seen this first, or at least have google-oAuth2 include your excellent example.

my only minor suggestion might be to also include setup instructions:

cat > client_secret.json ;
  <<YOUR DOWNLOADED client_secret.json FILE HERE>>
ctrl-D

yum -y install git; 
git clone  -b v1-master  https://github.com/googleapis/google-api-php-client.git  ;
git clone  https://gist.github.com/Jerry0022/27248ce51369e261829a  ;
mv  ./27248ce51369e261829a/'PHP Google oAuth2.php'  ./index.php ;
rm -Rf   ./27248ce51369e261829a/ ;   ##optional but tidy

vi  index.php:
line 6 OLD: $google_redirect_url = 'REDIRECT_URL';
line 6 NEW: $google_redirect_url = '//' . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'] ;
    ### line 100 optional but makes it pretty:
line 100 OLD: echo '<a class="login" href="'.$authUrl.'"><img src="images/google-login-button.png" /></a>';
line 100 NEW: echo '<a class="login" href="'.$authUrl.'"><img src="https://developers.google.com/identity/images/btn_google_signin_dark_normal_web.png" /></a>';

@Uriel1339
Copy link

I wished I found this a week or two ago. I struggled so much with the logout functionality and overall OAuth 2.0 from googles utterly confusing documentation.

You are my hero @Jerry0022 ! I might use this as building block for an article on Medium or such and hope more people find here. Please feel free to contact me for details and whether or not you would consider officially putting this under the GPL license so that people can use this in their projects.

Sincerely,

Andreas Lopez aka Uriel1339 ( @uriel1339 )

@Jerry0022
Copy link
Author

Jerry0022 commented May 8, 2019 via email

@Uriel1339
Copy link

Uriel1339 commented May 8, 2019 via email

@josepm88
Copy link

Excellent example!

Thank you.

@s3va
Copy link

s3va commented Jul 18, 2020

$gClient->revokeToken();
It does't work without argument now. At least for me.
I had to change it to:
$gClient->revokeToken($_SESSION['token']);
And of coz unset $_SESSION['token'] after revokeToken. Not before.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment