Home PHP Login with Google using PHP

Login with Google using PHP

Author

Date

Category

To allow users to log in with Google using PHP, you will need to use the Google API PHP Client library. Here are the basic steps:

  1. Create a new Google Cloud Platform project in the Google Cloud Console and enable the Google Sign-In API.
  2. Create OAuth 2.0 credentials for your app. You can create these credentials by clicking on the “Credentials” section in the Google Cloud Console and then clicking the “Create Credentials” button. Choose “OAuth client ID” as the credential type and select “Web application” as the application type. Then enter the authorized JavaScript origins and authorized redirect URIs for your app. These values will be used later in your PHP code.
  3. Download and install the Google API PHP Client library. You can download the library from the Google APIs Client Library for PHP GitHub repository or install it using Composer.
  4. Include the Google API PHP Client library in your PHP script by requiring the autoload.php file:
require_once 'path/to/autoload.php';
PHP
  1. Create a Google login button on your webpage and link it to the Google login page:
<a href="<?php echo $client->createAuthUrl(); ?>">Log in with Google</a>
PHP
  1. When the user clicks the login button, they will be redirected to the Google login page. After the user logs in and grants permission to your app, Google will redirect them back to the specified redirect URI. You can handle the login callback in your PHP script:
$client = new Google_Client();
$client->setAuthConfigFile('path/to/client_secret.json');
$client->setRedirectUri('http://your-redirect-uri');
$client->addScope(Google_Service_Oauth2::USERINFO_EMAIL);

if (isset($_GET['code'])) {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
}

if (isset($_SESSION['access_token'])) {
  $client->setAccessToken($_SESSION['access_token']);
  $oauth2 = new Google_Service_Oauth2($client);
  $user_info = $oauth2->userinfo->get();

  // Logged in
  echo '<h3>Access Token</h3>';
  var_dump($_SESSION['access_token']);

  echo '<h3>User Info</h3>';
  var_dump($user_info);
}
PHP


This code will retrieve the access token and user info for the logged-in user. From here, you can use the access token to make API requests on behalf of the user. Replace “path/to/client_secret.json” with the actual path to your OAuth 2.0 credentials JSON file, and replace “http://your-redirect-uri” with the actual redirect URI you specified when creating your credentials.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Subhash Shipu

PHP Expert

Hey there! I'm a PHP geek on a mission to blog my way through the coding chaos. When I'm not chasing semicolons, I'm busy cuddling my pet Coco, who thinks debugging means chasing her own tail. Join the fun!

Subscribe

Recent posts