Skip to content

Instantly share code, notes, and snippets.

@daveh
Last active September 11, 2024 14:46
Show Gist options
  • Save daveh/8955757edc2c1717dbc8ca00aea8dffa to your computer and use it in GitHub Desktop.
Save daveh/8955757edc2c1717dbc8ca00aea8dffa to your computer and use it in GitHub Desktop.
Create a Google Login Page in PHP (code to accompany https://youtu.be/yi2b9U1kQyc)
<?php
require __DIR__ . "/vendor/autoload.php";
$client = new Google\Client;
$client->setClientId("your client ID here");
$client->setClientSecret("your client secret here");
$client->setRedirectUri("http://localhost/redirect.php");
$client->addScope("email");
$client->addScope("profile");
$url = $client->createAuthUrl();
?>
<!DOCTYPE html>
<html>
<head>
<title>Google Login Example</title>
</head>
<body>
<a href="<?= $url ?>">Sign in with Google</a>
</body>
</html>
<?php
require __DIR__ . "/vendor/autoload.php";
$client = new Google\Client;
$client->setClientId("your client ID here");
$client->setClientSecret("your client secret here");
$client->setRedirectUri("http://localhost/redirect.php");
if ( ! isset($_GET["code"])) {
exit("Login failed");
}
$token = $client->fetchAccessTokenWithAuthCode($_GET["code"]);
$client->setAccessToken($token["access_token"]);
$oauth = new Google\Service\Oauth2($client);
$userinfo = $oauth->userinfo->get();
var_dump(
$userinfo->email,
$userinfo->familyName,
$userinfo->givenName,
$userinfo->name
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment