Monday, 2 November 2026

subscribe popup code in java script

 <style>


#subscribeFloat{


    position:fixed;

    left:-235px;

    top:50%;

    transform:translateY(-50%);


    z-index:9999;


    transition:0.4s;

}


#subscribeFloat:hover{

    left:0;

}


#subscribeFloat a{


    display:flex;

    align-items:center;

    gap:10px;


    background:linear-gradient(90deg,#ff9800,#ff5722);


    color:#fff;

    font-weight:bold;

    text-decoration:none;


    padding:14px 18px;


    border-radius:0 12px 12px 0;


    box-shadow:0 4px 15px rgba(0,0,0,0.25);


    font-size:16px;


    letter-spacing:0.3px;


    white-space:nowrap;

}


#subscribeFloat .icon{

    font-size:22px;

}


/* Mobile */


@media(max-width:768px){


    #subscribeFloat{

        left:-195px;

        top:70%;

    }


    #subscribeFloat a{


        font-size:13px;


        padding:10px 14px;

    }


}


</style>


<!-- Floating Subscribe Button -->


<div id='subscribeFloat'>


<a href="javascript:void(0);" onclick="goSubscribe()">


<span class='icon'>📩</span>


<span>Subscribe Newsletter</span>


<span class='icon'>➤</span>


</a>


</div>


<script>


function goSubscribe(){


    let currentUrl =

    window.location.pathname +

    window.location.search;


    window.location.href =

    'subscribe.php?url=' +

    encodeURIComponent(currentUrl);

}


</script>

Saturday, 10 October 2026

How to show popup once per session on link click

 Learn how to display a custom ad popup only once per session when a user clicks any link on your website using pure HTML, CSS, and JavaScript. This script intercepts the link click, shows the popup, uses sessionStorage to track the user, and smoothly redirects them to their destination.

Complete Code (HTML + CSS + JavaScript)

<!-- CSS Styling for Popup Overlay -->

<style>
#adquashPopupOverlay{
    display:none;
    position:fixed;
    inset:0;
    background:rgba(0,0,0,.75);
    z-index:999999;
    justify-content:center;
    align-items:center;
    padding:15px;
    box-sizing:border-box;
}

#adquashPopup{
    width:100%;
    max-width:500px;
    background:#fff;
    border-radius:14px;
    padding:15px;
    position:relative;
    text-align:center;
    box-shadow:0 10px 30px rgba(0,0,0,.35);
    animation:popupFade .3s ease;
}

#adquashPopup img{
    width:100%;
    display:block;
    border-radius:10px;
}

#adquashClose{
    position:absolute;
    top:20px;
    right:12px;
    width:36px;
    height:36px;
    line-height:36px;
    border-radius:50%;
    background:red;
    color:#fff;
    font-size:24px;
    font-weight:bold;
    cursor:pointer;
    user-select:none;
}

#adquashBtn{
    display:inline-block;
    margin-top:15px;
    padding:12px 24px;
    background:#ff6b00;
    color:#fff;
    text-decoration:none;
    border-radius:8px;
    font-weight:bold;
}

@keyframes popupFade{
    from{opacity:0;transform:scale(.9);}
    to{opacity:1;transform:scale(1);}
}
</style>

<!-- HTML Markup for Popup -->
<div id="adquashPopupOverlay">
    <div id="adquashPopup">
        <div id="adquashClose">&times;</div>
        <a href="https://gridbot.adquash.com/kucoin-dca-bot.html" target="_blank">
            <img src="https://aksharhanumandham.in/ads/kucoin.png" loading="lazy" alt="Advertisement">
        </a>
        <a href="https://gridbot.adquash.com/kucoin-dca-bot.html" target="_blank" id="adquashBtn">
            Visit Now
        </a>
    </div>
</div>

<!-- JavaScript Logic -->
<script>
(function(){
    if(sessionStorage.getItem("adquashPopupShown")){
        return;
    }

    let targetUrl="";
    const overlay=document.getElementById("adquashPopupOverlay");
    const popup=document.getElementById("adquashPopup");

    document.addEventListener("click",function(e){
        const link=e.target.closest("a");
        if(!link) return;

        // Popup ke andar ke links normal chalenge
        if(link.closest("#adquashPopup")) return;

        // Agar pehle hi dikh chuka hai
        if(sessionStorage.getItem("adquashPopupShown")) return;

        e.preventDefault();
        targetUrl=link.href;
        sessionStorage.setItem("adquashPopupShown","1");
        overlay.style.display="flex";
    },true);

    // Close button event
    document.getElementById("adquashClose").onclick=function(){
        overlay.style.display="none";
        if(targetUrl){
            location.href=targetUrl;
        }
    };

    // Outside click event
    overlay.addEventListener("click",function(e){
        if(e.target===overlay){
            overlay.style.display="none";
            if(targetUrl){
                location.href=targetUrl;
            }
        }
    });

    // Popup ke andar click hone par close na ho
    popup.addEventListener("click",function(e){
        e.stopPropagation();
    });
})();
</script>

Sunday, 2 August 2026

UPI QR Code generator code in html

Generate your own UPI QR Code easily with this simple HTML code.

Just copy and paste this code into your website or GitHub Pages, replace "yourupiid@amazonpay" with your own UPI ID, and save the file.

Enter the name and donation amount to create a custom UPI QR Code. Anyone can scan the QR code using any UPI app and make a payment directly to your UPI account.

No database, no server, and no setup required — it works completely on the browser.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8" />

<meta name="viewport" content="width=device-width, initial-scale=1.0" />


<title>UPI QR Code Generator</title>


<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>


<style>

    body{

        font-family: Arial, sans-serif;

        background:#f4f4f4;

        margin:0;

        padding:20px;

    }


    .container{

        max-width:420px;

        margin:auto;

        background:#fff;

        padding:25px;

        border-radius:12px;

        box-shadow:0 0 10px rgba(0,0,0,0.1);

        text-align:center;

    }


    h2{

        margin-bottom:20px;

    }


    input{

        width:100%;

        padding:12px;

        margin-bottom:15px;

        border:1px solid #ccc;

        border-radius:8px;

        font-size:16px;

        box-sizing:border-box;

    }


    button{

        width:100%;

        padding:12px;

        border:none;

        border-radius:8px;

        background:#0d6efd;

        color:#fff;

        font-size:16px;

        cursor:pointer;

    }


    button:hover{

        background:#0b5ed7;

    }


    #message{

        margin-top:20px;

        font-size:18px;

        font-weight:bold;

        color:#222;

    }


    #qrcode{

        margin-top:20px;

        display:flex;

        justify-content:center;

    }


    .upi-text{

        margin-top:10px;

        color:#666;

        font-size:14px;

    }

</style>

</head>

<body>


<div class="container">


    <h2>UPI QR Generator</h2>


    <input type="text" id="name" placeholder="Enter Name" />


    <input type="number" id="amount" placeholder="Enter Amount" />


    <button onclick="generateQR()">Generate QR Code</button>


    <div id="message"></div>


    <div id="qrcode"></div>


    <div class="upi-text">

        UPI ID: yourupiid@amazonpay

    </div>


</div>


<script>


function generateQR(){


    let name = document.getElementById("name").value.trim();

    let amount = document.getElementById("amount").value.trim();


    if(name === "" || amount === ""){

        alert("Please fill all fields");

        return;

    }


    let upiID = "yourupiid@amazonpay";


    let note = `Prayer and blessings for ${name} donate amount`;


    let upiLink = `upi://pay?pa=${upiID}&pn=${encodeURIComponent(name)}&am=${amount}&cu=INR&tn=${encodeURIComponent(note)}`;


    document.getElementById("message").innerHTML =

        `Prayer and blessings for <b>${name}</b> donate ₹${amount}`;


    document.getElementById("qrcode").innerHTML = "";


    new QRCode(document.getElementById("qrcode"), {

        text: upiLink,

        width: 250,

        height: 250

    });


}


</script>


</body>

</html>

Wednesday, 15 April 2026

One click open two link upgraded version

 

One click open two link

Craete single link for double link. Given code open two link first link send https://www.profitablecpmratenetwork.com and second link open same page

Just copy and paste this code and replace url link as per your need.

view old code 

Click for Demo

<a href="https://www.profitablecpmratenetwork.com/ka9w8m66?key=9ef4829d333930832621abd4b2481d67" id="smartLink">Click</a>


<script>

(function(){


  document.addEventListener("touchstart", function(){}, {once:true});


  var link = document.getElementById("smartLink");


  const KEY_TIME = "popTime";

  const KEY_DONE = "popDone";

  const EXPIRY = 30 * 60 * 1000; // 30 minutes


  function isExpired(){

      let t = sessionStorage.getItem(KEY_TIME);

      if(!t) return true;


      let now = Date.now();

      return (now - parseInt(t)) > EXPIRY;

  }


  link.addEventListener("click", function(e){


    let sessionActive = sessionStorage.getItem(KEY_DONE) === "1";

    let expired = isExpired();


    // 👉 If session exists AND NOT expired → open blogspot same tab

    if(sessionActive && !expired){


        e.preventDefault();


        window.location.href = "https://simplephpcoding.blogspot.com/2026/04/one-click-open-two-link-upgraded-version.html";

        return;

    }


    // 👉 FIRST CLICK or EXPIRED SESSION → AD FLOW

    sessionStorage.setItem(KEY_DONE, "1");

    sessionStorage.setItem(KEY_TIME, Date.now());


    var w = window.open(

        "https://simplephpcoding.blogspot.com/2026/04/one-click-open-two-link-upgraded-version.html",

        "_blank"

    );


    if(w){

        w.blur();

        window.focus();

    }


});


})();

</script>

Monday, 2 March 2026

Combine GZIP, Browser Caching, and 304 Not Modified for Maximum Website Performance

 If you want serious speed improvements on shared hosting (especially DirectAdmin), enabling just one optimization is not enough. For best performance, you should combine:

  • GZIP Compression
  • Browser Caching
  • 304 Not Modified Headers

Together, these three techniques reduce bandwidth usage, server load, and page load time — without changing your PHP application logic.


1️⃣ GZIP Compression – Reduce File Size by 50–80%

GZIP compresses HTML, CSS, JS, and JSON files before sending them to the browser. The browser automatically decompresses the files.

Why It Matters

  • Smaller file size
  • Faster mobile loading
  • Reduced bandwidth usage
  • Better Core Web Vitals

Enable GZIP in .htaccess

 

<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/css application/javascript application/json
</IfModule>

 

No PHP changes required.


2️⃣ Browser Caching – Prevent Re-Downloading Static Files

Browser caching tells the visitor’s browser:

“Keep this file for X days. Don’t download it again.”

This is especially powerful for:

  • CSS files
  • JavaScript
  • Images
  • Logos

Add Browser Caching Rules

 

<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/css "access plus 7 days"
ExpiresByType application/javascript "access plus 7 days"
ExpiresByType image/jpeg "access plus 30 days"
ExpiresByType image/png "access plus 30 days"
</IfModule>

 

Now returning visitors won’t re-download the same files again.


3️⃣ 304 Not Modified – Skip Sending Unchanged Content

When a visitor reloads a page, the browser asks:

“Has this file changed?”

If it hasn’t, the server responds with:

 

HTTP/1.1 304 Not Modified

 

No file is sent again.

Why This Is Powerful

  • Saves server bandwidth
  • Reduces server processing
  • Speeds up reload time
  • Helps search engine crawlers

Basic 304 Support (Automatic in Apache)

Apache usually handles 304 automatically when:

  • Last-Modified header is present
  • ETag header is enabled

Most shared hosting environments already support this.


How These Three Work Together

OptimizationWhat It ReducesImpact
GZIPFile sizeFaster first load
Browser CacheRepeat downloadsFaster returning visits
304 HeaderUnnecessary re-sendingFaster reloads

Real-World Example

Without optimization:

  • Homepage size: 120KB
  • Every reload: 120KB transferred

With all three enabled:

  • First visit: ~30–40KB (compressed)
  • Next visit: Almost zero transfer (cached + 304)

That’s a massive difference — especially during traffic spikes.


Why This Matters for Shared Hosting

If you’re running:

  • A JSON-based homepage
  • A cached PHP site
  • A blog, news portal, or affiliate site
  • A high-traffic single server setup

This combination helps you:

  • Handle more users on the same hosting plan
  • Reduce CPU load
  • Lower bandwidth consumption
  • Improve SEO rankings

Final Recommendation

If you are using DirectAdmin or shared hosting, add:

  1. GZIP rules
  2. Browser caching rules
  3. Ensure 304 headers are active

These three together create a lightweight, high-performance environment — even without upgrading your server.

How to Enable GZIP Compression in DirectAdmin Step-by-Step Guide

If you're using DirectAdmin hosting and want to speed up your website without changing any PHP code, enabling GZIP compression is one of the easiest and most effective optimizations you can make.

GZIP reduces the size of your website files before they are sent to the visitor’s browser. The browser automatically decompresses them, so users never notice anything—except faster loading speed.


What Is GZIP Compression?

GZIP is a server-side compression method. When a user visits your site:

  1. The server compresses HTML, CSS, JS, and JSON files.
  2. The browser downloads a much smaller file.
  3. The browser decompresses it automatically.

This can reduce page size by 50–80%, especially for text-based content.


Why Enable GZIP in DirectAdmin?

If you're running:

  • A JSON-based homepage
  • A no-database setup
  • A cached website
  • A high-traffic blog or news portal

Then enabling GZIP will:

  • Reduce bandwidth usage
  • Improve mobile load speed
  • Improve SEO performance
  • Lower server load during traffic spikes

How to Enable GZIP in DirectAdmin

Step 1: Log into DirectAdmin

Access your hosting panel.

Step 2: Open File Manager

Go to your website's main folder:

 

public_html

 

Step 3: Edit .htaccess

Open the .htaccess file.
If it does not exist, create a new one.

Step 4: Add This Code

 

<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/css application/javascript application/json
</IfModule>

 

Save the file.

That's it. No changes needed in your PHP files.


How to Check If GZIP Is Working

  1. Open your website.
  2. Right-click → Inspect.
  3. Go to the Network tab.
  4. Reload the page.
  5. Click on the main HTML file.
  6. Look for:

 

Content-Encoding: gzip

 

If you see that, GZIP is active.


Does DirectAdmin Support GZIP?

In most shared hosting environments using DirectAdmin, mod_deflate is already enabled. If the above code works without error, you're good to go.

If your server uses Nginx as a reverse proxy, GZIP may already be enabled at the server level.


Final Thoughts

Enabling GZIP in DirectAdmin is:

  • Safe
  • Easy
  • Free
  • Code-independent
  • Highly effective

For best performance, combine GZIP with browser caching and 304 Not Modified headers.

If you're building a fast, scalable, low-IO website, this is a must-have optimization.

Saturday, 6 December 2025

Auto review system using gemini api in php

 Auto review system using gemini api in php

Google AI key लो (free):

https://aistudio.google.com/app/apikey 

apna api key or prompt replace karo.

<?php

// 🔑 Gemini API Key
$apiKey = "YOUR-API-KEY";

// 1) Fetch available models
function listModels($apiKey) {
    $url = "https://generativelanguage.googleapis.com/v1beta/models?key=" . urlencode($apiKey);
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => ["Content-Type: application/json"],
        CURLOPT_TIMEOUT => 10
    ]);
    $resp = curl_exec($ch);
    if ($resp === false) {
        return null;
    }
    $json = json_decode($resp, true);
    if (!isset($json['models']) || !is_array($json['models'])) {
        return null;
    }
    return $json['models'];
}

// 2) Choose first model that supports generateContent
function pickModel($models) {
    foreach ($models as $m) {
        if (isset($m['supportedGenerationMethods'])
            && in_array("generateContent", $m['supportedGenerationMethods'])) {
            return $m['name'];  // model name like "models/gemini-2.5-flash"
        }
    }
    return null;
}

// 3) Use chosen model to review article
function reviewArticle($modelFullName, $title, $content, $apiKey) {
    // modelFullName example: "models/gemini-2.5-flash"
    $url = "https://generativelanguage.googleapis.com/v1beta/" . $modelFullName . ":generateContent?key=" . urlencode($apiKey);

   $systemPrompt = <<<EOT
You are a strict content-review and JSON-only generator for an automated article approval system.

Your rules:
- Analyze the given title + content.
- Return ONLY clean JSON.
- NO markdown, NO code fences, NO backticks, NO explanations.
- JSON MUST be valid, directly parsable, and must follow the exact structure below.

JSON STRUCTURE (strict):
{
  "allowed": true or false,
  "category": "short category string",
  "risk_score": 0-100,
  "violations": ["list of policy violations"]
}

--------------------------------------
ALLOWED CONTENT (DO NOT BLOCK):
--------------------------------------
These categories must ALWAYS be allowed, even if exaggerated or promotional:
- Business, finance, trading, investing
- Financial marketing or promotional claims
- Exaggerated or misleading profit claims (allowed)
- Pricing information
- Automation systems, trading bots, algorithmic trading
- API integration and technical tools
- Tutorials, guides, general education
- Motivational, spiritual, religious content
- Normal product or service descriptions

IMPORTANT:
Misleading or exaggerated financial statements MUST NOT cause rejection.
Instead return:
- allowed: true
- category: "Financial Exaggeration"
- risk_score: 10–40
- violations: ["Financial exaggeration warning"] (optional)

--------------------------------------
REJECT ONLY IF TEXT CONTAINS:
--------------------------------------
These 9 critical banned categories MUST be blocked:
1. Illegal activity or instructions
2. Explicit adult/sexual content
3. Hate speech or targeted harassment
4. Violence, violent threats, or harm encouragement
5. Weapons, explosives, or illegal drugs
6. Political propaganda, election influence, political bias
7. Terrorism or extremist content
8. Serious medical misinformation that can cause harm
9. Fraud, scam instructions, or identity theft techniques

If ANY of these appear → allowed = false.

--------------------------------------
RISK SCORE RULE:
--------------------------------------
0–20  = Very Safe  
20–40 = Mild Risk (still allowed)  
40–70 = High Risk (allowed unless prohibited category)  
70–100 = Reject (only if in banned category list)

--------------------------------------
FINAL RULE:
--------------------------------------
Unless the content violates the banned categories,
you MUST return allowed: true.

Return ONLY the clean JSON object.
EOT;



    $fullText = "TITLE: " . $title . "\n\nCONTENT:\n" . $content;

    $payload = [
        "contents" => [[
            "parts" => [[ "text" => $systemPrompt . "\n\n" . $fullText ]]
        ]]
    ];

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => ["Content-Type: application/json"],
        CURLOPT_POSTFIELDS => json_encode($payload),
        CURLOPT_TIMEOUT => 20
    ]);
    $resp = curl_exec($ch);
    if ($resp === false) {
        return ["error" => "cURL request failed"];
    }
    $json = json_decode($resp, true);
    if (!isset($json['candidates'][0]['content']['parts'][0]['text'])) {
        return ["error" => "No candidate text in API response", "raw" => $resp];
    }
    $out = json_decode($json['candidates'][0]['content']['parts'][0]['text'], true);
    if (!is_array($out)) {
        return ["error" => "Invalid JSON from model", "raw" => $json['candidates'][0]['content']['parts'][0]['text']];
    }
    return $out;
}

// --- Main flow ---
$error = "";
$result = null;
$modelName = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title'] ?? "");
    $content = trim($_POST['content'] ?? "");

    if ($title === "" || $content === "") {
        $error = "Title और Content दोनों भरना ज़रूरी है.";
    } else {
        $models = listModels($apiKey);
        if (!$models) {
            $error = "Failed to fetch models list from Gemini API.";
        } else {
            $modelName = pickModel($models);
            if (!$modelName) {
                $error = "कोई suitable model नहीं मिला जो generateContent support करता हो.";
            } else {
                $result = reviewArticle($modelName, $title, $content, $apiKey);
            }
        }
    }
}
?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Auto-Model Detect Review</title>
  <style>
    body { font-family: Arial; background: #f4f6f8; padding: 30px; }
    .box { max-width:800px; margin:auto; background:#fff; padding:20px; border-radius:8px; box-shadow:0 4px 12px rgba(0,0,0,0.1); }
    textarea, input[type=text] { width:100%; padding:8px; margin-top:8px; border:1px solid #ccc; border-radius:4px; }
    button { padding:10px 16px; margin-top:12px; background:#111; color:#fff; border:none; border-radius:4px; cursor:pointer; }
    .badge { display:inline-block; padding:6px 12px; border-radius:4px; color:#fff; font-weight:bold; }
    .good { background:#28a745; }
    .bad  { background:#dc3545; }
    .debug { background:#eee; padding:10px; margin-top:10px; white-space:pre-wrap; }
  </style>
</head>
<body>
  <div class="box">
    <h2>Auto-Model Detect + Content Review</h2>
    <form method="post">
      <label>Title</label>
      <input type="text" name="title" required value="<?= htmlspecialchars($_POST['title'] ?? '') ?>">
      <label>Content</label>
      <textarea name="content" rows="8" required><?= htmlspecialchars($_POST['content'] ?? '') ?></textarea>
      <button type="submit">Review Article</button>
    </form>

    <?php if ($error): ?>
      <div class="debug"><b>Error:</b> <?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <?php if ($result): ?>
      <hr>
      <h3>Result (using model: <code><?= htmlspecialchars($modelName) ?></code>)</h3>
      <?php if (!empty($result['allowed'])): ?>
        <div class="badge good">✅ APPROVED</div>
      <?php else: ?>
        <div class="badge bad">❌ REJECTED</div>
      <?php endif; ?>
      <div style="margin-top:12px;">
        <b>Category:</b> <?= htmlspecialchars($result['category'] ?? '') ?><br>
        <b>Risk Score:</b> <?= htmlspecialchars($result['risk_score'] ?? '') ?>/100
      </div>
      <div style="margin-top:12px;">
        <b>Violations:</b>
        <?php if (!empty($result['violations']) && is_array($result['violations'])): ?>
          <ul>
            <?php foreach ($result['violations'] as $v): ?>
              <li><?= htmlspecialchars($v) ?></li>
            <?php endforeach; ?>
          </ul>
        <?php else: ?>
          <div>None reported.</div>
        <?php endif; ?>
      </div>
      <div class="debug"><b>Full JSON Output:</b><br><?= htmlspecialchars(json_encode($result, JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE)) ?></div>
    <?php endif; ?>
  </div>
</body>
</html>

Saturday, 7 June 2025

PHP MySQL Update Data

 

Update Data In a MySQL Table Using MySQLi

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}

$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";

if (mysqli_query($conn, $sql)) {
  echo "Record updated successfully";
} else {
  echo "Error updating record: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

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>";
?>