Validate login in php with google
To implement login with Google in PHP, you can use Google's OAuth 2.0 authentication system. Here are the steps to validate a user's login with Google in PHP:
Create a Google Cloud Platform (GCP) Project:
Go to the Google Cloud Console (https://console.cloud.google.com/).
Create a new project if you don't have one.
Set up OAuth 2.0 Credentials:
In your GCP project, navigate to the "APIs & Services" > "Credentials" section.
Click the "Create Credentials" button and select "OAuth client ID."
Choose "Web application" as the application type.
Add authorized JavaScript origins and redirect URIs. For development, you can use http://localhost as the redirect URI.
Click the "Create" button to generate your client ID and client secret.
Install Required Libraries:
You'll need to use the Google API client library for PHP. You can install it using Composer:
codecomposer require google/apiclient:"^2.0"
PHP Code for Google Login:
php code
<?php
require_once 'vendor/autoload.php'; // Include the Google API client library
session_start();
$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');
if (isset($_GET['code'])) {
try {
$client->fetchAccessTokenWithAuthCode($_GET['code']);
$userinfo = $client->verifyIdToken();
// $userinfo contains user data
$_SESSION['user_data'] = $userinfo;
// You can use $userinfo to authenticate the user and perform other actions
// For example, you can check if the user already exists in your database and log them in.
header('Location: logged-in.php'); // Redirect to a logged-in page
exit();
} catch (Exception $e) {
// Handle error
echo 'Error: ' . $e->getMessage();
}
} else {
$authUrl = $client->createAuthUrl();
echo '<a href="' . $authUrl . '">Login with Google</a>';
}
Replace 'YOUR_CLIENT_ID', 'YOUR_CLIENT_SECRET', and 'YOUR_REDIRECT_URI' with the values from your Google Cloud Console project.
Create a logged-in.php page to handle authenticated users. In this page, you can use the user data stored in $_SESSION['user_data'] for further actions.
This code sets up a basic Google login system in PHP using OAuth 2.0. Users will be redirected to Google for authentication, and upon successful login, their user data will be stored in the $_SESSION variable. You can then use this data to authenticate and authorize users in your application.
Comments
Post a Comment