Incorporating Google authentication (OAuth 2.0) into a PHP website provides users with an easy and secure way to log in using their Google accounts. This method not only improves security by eliminating the need for storing passwords but also enhances user experience with a simple, one-click login process. Here’s a step-by-step guide on how to add Google authentication to your PHP website.
Prerequisites
- PHP Setup: Ensure your website is running on PHP 7.0 or higher.
- Composer: PHP dependency manager to install Google Client libraries.
- Google Account: You need to register your app with Google to obtain client credentials.
- HTTPS: Google authentication requires HTTPS for redirect URIs.
Steps to Add Google Authentication
Step 1: Create a Google Developer Console Project
- Go to the Google Developer Console.
- Create a new project by clicking on the “New Project” button.
- Name your project and click “Create”.
- After the project is created, navigate to APIs & Services > OAuth consent screen.
- Select External (for public applications) and provide the required information, such as app name, email, and authorized domain.
- Save the consent screen settings and move to Credentials.
- Click Create Credentials and select OAuth 2.0 Client IDs.
- Choose Web application and set the Redirect URIs (e.g.,
https://your-domain.com/callback.php
). - After creating credentials, you will get a Client ID and Client Secret. These will be used in your PHP application.
Step 2: Install Google Client Library
The simplest way to use Google APIs in PHP is by installing the Google Client Library via Composer. Run the following command in the root directory of your PHP project:
composer require google/apiclient:^2.0
Step 3: Setting Up Google OAuth 2.0
Now, create a login.php
file that will initiate the Google authentication process and a callback.php
file that will handle the callback from Google after authentication.
login.php
This script redirects users to Google for authentication.
<?php
require_once 'vendor/autoload.php';
session_start();
// Create Client Request to access Google API
$client = new Google_Client();
$client->setClientId('YOUR_CLIENT_ID');
$client->setClientSecret('YOUR_CLIENT_SECRET');
$client->setRedirectUri('https://your-domain.com/callback.php');
$client->addScope("email");
$client->addScope("profile");
// Redirect to Google for authentication
$authUrl = $client->createAuthUrl();
header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));
callback.php
This script handles the response from Google and retrieves the user’s profile data.
<?php
require_once 'vendor/autoload.php';
session_start();
$client = new Google_Client();
$client->setClientId('YOUR_CLIENT_ID');
$client->setClientSecret('YOUR_CLIENT_SECRET');
$client->setRedirectUri('https://your-domain.com/callback.php');
if (isset($_GET['code'])) {
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
$client->setAccessToken($token['access_token']);
// Get profile info
$google_oauth = new Google_Service_Oauth2($client);
$google_account_info = $google_oauth->userinfo->get();
$email = $google_account_info->email;
$name = $google_account_info->name;
// Use the data (e.g., store in database, create a session, etc.)
$_SESSION['email'] = $email;
$_SESSION['name'] = $name;
// Redirect to the home page or another secure page
header('Location: index.php');
exit;
} else {
echo "Authentication failed.";
}
Step 4: Display User Info After Login
You can create an index.php
file where logged-in users are redirected. If the user is logged in, it displays the user’s profile information.
<?php
session_start();
if (isset($_SESSION['email'])) {
echo "Welcome, " . $_SESSION['name'];
echo "<br>Your email: " . $_SESSION['email'];
echo "<br><a href='logout.php'>Logout</a>";
} else {
echo "Please <a href='login.php'>login with Google</a>.";
}
Step 5: Add Logout Functionality
You can create a simple logout.php
file to clear the session and log out the user.
<?php
session_start();
session_destroy();
header('Location: index.php');
Step 6: Testing the Application
- Open the
login.php
page in your browser. You will be redirected to Google for authentication. - After logging in, you’ll be redirected back to your site, and the
callback.php
file will handle the response. - If successful, the user’s name and email will be displayed on the homepage (
index.php
).
Conclusion
Adding Google authentication to your PHP website is a great way to enhance user experience and security. By using OAuth 2.0, you avoid the complexities of managing and securing passwords yourself. This method provides a simple login process that users will appreciate, and it integrates seamlessly with your existing PHP application.