Thursday, 24 April 2025

Login with gmail in php

Single page Login with gmail in php. 

Login with gmail

store email , name in database.  

<?php

session_start();

$client_id = 'YOUR_GOOGLE_CLIENT_ID'; $client_secret = 'YOUR_GOOGLE_CLIENT_SECRET';
$redirect_uri = 'https://yourdomain.com/login.php';
$scope = 'email profile';
include "connect.php";
// Step 1: Save previous page in cookie if not coming back from Google
if (!isset($_GET['code']) && !isset($_SESSION['email'])) {
   // $referrer = $_SERVER['HTTP_REFERER'] ?? '/';
    $referrer = $_SERVER['HTTP_REFERER'] ?? '/';
if (str_contains($referrer, 'logout.php')) {
    $referrer = '/';
}
    setcookie('redirect_after_login', $referrer, time() + 300, '/'); // valid for 5 min
}

// Step 2: If not yet authenticated, redirect to Google
if (!isset($_SESSION['email']) && !isset($_GET['code'])) {
    $auth_url = "https://accounts.google.com/o/oauth2/v2/auth?"
        . "client_id=$client_id"
        . "&redirect_uri=" . urlencode($redirect_uri)
        . "&response_type=code"
        . "&scope=" . urlencode($scope)
        . "&access_type=offline";

    header("Location: $auth_url");
    exit;
}

// Step 3: Handle Google Redirect
if (isset($_GET['code'])) {
    $code = $_GET['code'];

    // Get access token
    $token_url = 'https://oauth2.googleapis.com/token';
    $post_data = http_build_query([
        'code' => $code,
        'client_id' => $client_id,
        'client_secret' => $client_secret,
        'redirect_uri' => $redirect_uri,
        'grant_type' => 'authorization_code'
    ]);

    $ch = curl_init($token_url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $token_response = curl_exec($ch);
    curl_close($ch);

    $token = json_decode($token_response, true);
    $access_token = $token['access_token'];

    // Get user info
    $ch = curl_init("https://www.googleapis.com/oauth2/v2/userinfo?access_token=$access_token");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $user_info = curl_exec($ch);
    curl_close($ch);

    $user = json_decode($user_info, true);
    $_SESSION['email'] = $user['email'];
    $_SESSION['name'] = $user['name'];
    $_SESSION['picture'] = $user['picture'];
$email = $_SESSION['email'];
$name = $user['name'];
$_SESSION['username'] = $user['email'];
$sql = mysqli_fetch_assoc(mysqli_query($connection,"select * from user where email = '$email'"));
if($sql > 0){ echo " username " . $sql["email"]; }
else{$sqli = mysqli_query($connection,"INSERT INTO user (email,name) value('$email','$name')");}
    // Step 4: Redirect to original page from cookie
    $redirect = $_COOKIE['redirect_after_login'] ?? '/';
    setcookie('redirect_after_login', '', time() - 3600, '/'); // clear cookie
    header("Location: $redirect");
    exit;
}

//Step 5: Already Logged In

echo "<h2>Welcome, {$_SESSION['name']}!</h2>";
echo "<img src='{$_SESSION['picture']}' width='100'><br>";
echo "<p>Email: {$_SESSION['email']}</p>";
echo "<a href='logout.php'>Logout</a>";
echo "<a href='".$_SERVER['HTTP_REFERER']."'>Go Back</a>";
?>