Introduction
Adding a Google login to your PHP website can enhance both user experience and security by allowing users to authenticate with their existing Google accounts. Instead of creating a separate registration system, you can integrate Google's OAuth 2.0 authentication, which is widely trusted and easy to implement. In this guide, we’ll walk you through each step—from creating a project in Google Cloud Console to writing PHP code that handles Google sign-in and displays user information.
Whether you're a beginner or an experienced developer, this tutorial will help you build a fully functional Google login system in PHP using the Google API Client.
Step 1: Create a Project on Google Cloud Console
1. First, go to this https://console.cloud.google.com/welcome.
2. Click on the "Select a Project" button that open a pop window.
4. Enter a project name and select an organization.
5. Click on the create button. Your project will now be created successfully.
Step 2: Select the Project and Enable APIs.
1. Click the "Select a Project" button again and choose the project you just created.
2. Click on the hamburger icon in the top left corner, and hover on the APIs and services and click on the OAuth consent screen.
3. Click on the "Get Started" button to set up the OAuth consent screen.
Step 3: Set Up OAuth Consent Screen
1. Add app name and user support email inside the App Information and click on the next button.
3. In contact information enter your email address for google to notify you about any changes to your project.
4. Tick on the check box and click to create button.
Step 4: Create OAuth Client Credentials
1. Go to the APIs and Services, then click on the Credentials.
2. Click on the create credentials and select OAuth client ID.
3. Choose Web Application as the application type.
4. Provide a name or use the default name.
5. Enter Authorized redirect URI.
6. Click on the create button. Now you get your Client ID and Client secret.
Step 5: Install Google API Client Package
1. Open terminal or command prompt and run this command.
composer require google/apiclient
2. This will create a vendor folder and install the Google API Client library inside vendor folder.
3. You must include the vendor/autoload.php file in your PHP login file to use the library.
Step 6: Code Example of Login with Google in PHP
File Structure of Code example
file name: home.php
<?php
session_start();
// If the user is not logged in, redirect to the login page
if(!isset($_SESSION['user_id'])){
header("location: login.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home</title>
// Bootstrap CDN Link
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-4Q6Gf2aSP4eDXB8Miphtr37CMZZQ5oXLH2yaXMJ2w8e2ZtHTl7GptT4jmndRuHDT"
crossorigin="anonymous"
/>
</head>
<body>
<div class="container d-flex justify-content-between mt-4">
<p>Welcome! <?php echo $_SESSION['user_name']; ?> Your are successfully login with your google account.</p>
<div>
<a href="logout.php?logout_id=<?php echo $_SESSION['user_id']; ?>" class="btn btn-primary p-2">Logout</a>
</div>
</div>
</body>
</html>
Explanation:
1. Check if user is logged in or not. If user_id is not set in the session means the user is not logged in and we redirect user to login.php.
2. Create a simple home page using HTML and Bootstrap for quick styling to avoid write css form stratch.
3. Store user_name in the global variable $_SESSION;
4. Create a logout button that points to logout.php page, which passes user_id as a query parameter.
<?php
session_start();
// If the user is already logged in, redirect to the home page
if(isset($_SESSION['user_id'])){
header("location: home.php");
}
// Include Google API configuration
require_once "google_login/google_config.php";
// Generate Google login URL $login_url = $client->createAuthUrl();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login with Google</title>
// Bootstrap CDN Link
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-4Q6Gf2aSP4eDXB8Miphtr37CMZZQ5oXLH2yaXMJ2w8e2ZtHTl7GptT4jmndRuHDT"
crossorigin="anonymous"
/>
</head>
<body>
<div class="container mt-4">
<a href="<?= $login_url ?>" class="btn btn-primary p-3">Login With Google</a>
</div>
</body>
</html>
Explanation:
1. Check if user is already logged in or not. if user_id is set in the session means that user is logged in and they are redirected user to home page.
2. google_config.php is included to load the Google Client configuration like client_id, client_secret, and redirect_uri.
3. $client->createAuthUrl() generates the google login URL using OAuth 2.0.
4. Inside the div element a login button is created using bootstrap. When user clicked it, it redirects users to Google for authentication.
file name: logout.php
<?php
session_start();
if(isset($_SESSION['user_id'])){
$logout_id = $_GET['logout_id'];
if(isset($logout_id)){
session_unset();
session_destroy();
header("location: login.php");
}
}
?>
1. Before logout check if user is logged in or not.
2. store logout_id in $logout_id variable.
3. if logout_id is set we use session_unset() to clear all session variables and session_destroy() to destroy the session completely and redirect user to the login page.
file name: google_config.php
<?php
require __DIR__ . "/../vendor/autoload.php";
$client = new Google\Client();
$client->setClientId("Your_Client_Id");
$client->setClientSecret("Your_Client_Secret");
$client->setRedirectUri("Your_Redirect_Uri");
$client->addScope("email");
$client->addScope("profile");
?>
Explanation:
1. require __DIR__ . "/../vendor/autoload.php" this line loads the composer autoloader which gives access to all classes provided by the google api client library.
2. Creates a new instance of the google client class, which handles all OAuth 2.0 logic and API calls.
3. Sets the Client ID and Client Secret which provided by google cloud console which we created in step 4 OAuth client credentials.
4. Now we request permission to access the user's email and basic profile information (like name and profile. We can request for more scopes based on our need.
file name: callback.php
<?php
session_start();
require_once "google_config.php"; // Your Google API config
if (!isset($_GET['code'])) {
header("Location: ../login.php");
exit;
}
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
if (!isset($token['access_token'])) {
exit("Google login failed.");
}
$client->setAccessToken($token['access_token']);
$oauth = new Google\Service\Oauth2($client);
$userinfo = $oauth->userinfo->get();
// Store Google user data in session (no database)
$_SESSION['user_id'] = $userinfo->id;
$_SESSION['user_name'] = $userinfo->name;
$_SESSION['user_image'] = $userinfo->picture;
$_SESSION['login_type'] = 'google';
header("Location: ../home.php");
exit;
?>
Explanation:
1. Starts the PHP session so that we can store user data after login.
2. Includes the google_config.php file that sets up the google client (Client ID, Client Secret, and Scopes).
3. Check if code exists in URL using isset($_GET['code']). This ensures that the user was redirected after successful google authentication otherwise, redirect user to login page.
4. Store token received form google in $token variable and check if token is set or not.
5. Sets the access token and retrieves user info such as name, email, and profile picture.
6. Saves the user's google account info in the session for use across pages.
7. After successfully login, the user is redirected to the home.php page.
Conclusion
Congratulations! You have successfully integrated Google Login into your PHP application using OAuth 2.0. This setup not only simplifies the login process for users but also ensures a secure and standardized method of authentication. As your application grows, you can extend this functionality further by storing user details in a database or using the Google APIs to access additional services.
Keep your client credentials secure, and don’t forget to set up HTTPS in production for better security. Happy coding!
Comments
Post a Comment