📲 Download Utility Tools Apps

EMI Calculator

Download EMI Calculator

SOA Games

Download SOA Games

SOA Technology App

Download SOA Technology

BMI Checker

Download BMI Checker

Task Jira

Download Task Jira

Laughing Adda

Download Laughing Adda

📅 हिंदी कैलेंडर ऐप डाउनलोड करें

Download Shubhcalendar App

Advanced login system (Remember Me cookie)

upgraded your system in the canvas to include a secure “Remember Me” feature 🔐

Here’s what’s happening behind the scenes (important to understand):


🚀 How “Remember Me” Works

1. User logs in with checkbox

  • If checked, system:
    • Generates a secure random token
    • Stores it in:
      • Database (remember_token)
      • Cookie (remember_token)

2. Next visit (auto login)

  • If session is not set but cookie exists:
    • System checks token in DB
    • Logs user in automatically

3. Logout

  • Deletes:
    • Session
    • Cookie
    • Token from database

🔐 Security Features Included

random_bytes() → secure token
HttpOnly cookie → JS cannot access
Secure flag → works on HTTPS
✅ Prepared statements → no SQL injection
✅ Token removed on logout


⚠️ Next-Level Improvements (Highly Recommended)

If you want production-level system:

1. Token Hashing (VERY IMPORTANT)

Instead of storing token directly:

hash('sha256', $token);

2. Use Expiry Column

Add:

remember_expiry DATETIME

3. Bind Token to Device

Store:

  • IP address
  • User agent

4. Separate Files (Professional Structure)

Right now it’s single file for learning.

Real structure:

config.php
login.php
register.php
dashboard.php
logout.php
auth.php

💡 Interview Question They Ask from This

👉 “Why not store password in cookie instead of token?”

Answer:
➡️ Because it’s unsafe. Tokens are random and can be revoked.

<?php
// ================= CONFIG =================
$host = "localhost";
$user = "root";
$pass = "";
$db   = "test_db";

$conn = new mysqli($host, $user, $pass, $db);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

session_start();

// ================= AUTO LOGIN (REMEMBER ME) =================
if (!isset($_SESSION['user']) && isset($_COOKIE['remember_token'])) {
    $token = $_COOKIE['remember_token'];

    $stmt = $conn->prepare("SELECT * FROM users WHERE remember_token=?");
    $stmt->bind_param("s", $token);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $_SESSION['user'] = $row['username'];
    }
}

// ================= REGISTER =================
if (isset($_POST['register'])) {
    $username = $_POST['username'];
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);

    $stmt = $conn->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
    $stmt->bind_param("ss", $username, $password);

    if ($stmt->execute()) {
        echo "Registered successfully";
    } else {
        echo "Error";
    }
}

// ================= LOGIN =================
if (isset($_POST['login'])) {
    $username = $_POST['username'];
    $password = $_POST['password'];

    $stmt = $conn->prepare("SELECT * FROM users WHERE username=?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();

        if (password_verify($password, $row['password'])) {
            session_regenerate_id(true);
            $_SESSION['user'] = $row['username'];

            // REMEMBER ME
            if (isset($_POST['remember'])) {
                $token = bin2hex(random_bytes(32));

                $stmt = $conn->prepare("UPDATE users SET remember_token=? WHERE id=?");
                $stmt->bind_param("si", $token, $row['id']);
                $stmt->execute();

                setcookie("remember_token", $token, time() + (86400 * 30), "/", "", true, true);
            }

            header("Location: dashboard.php");
            exit();
        } else {
            echo "Invalid Password";
        }
    } else {
        echo "User not found";
    }
}

// ================= LOGOUT =================
if (isset($_GET['logout'])) {
    if (isset($_SESSION['user'])) {
        // remove token from DB
        $stmt = $conn->prepare("UPDATE users SET remember_token=NULL WHERE username=?");
        $stmt->bind_param("s", $_SESSION['user']);
        $stmt->execute();
    }

    setcookie("remember_token", "", time() - 3600, "/");

    session_unset();
    session_destroy();

    header("Location: login.php");
    exit();
}
?>

<!-- ================= REGISTER ================= -->
<h2>Register</h2>
<form method="POST">
    <input type="text" name="username" placeholder="Username" required><br><br>
    <input type="password" name="password" placeholder="Password" required><br><br>
    <button name="register">Register</button>
</form>

<!-- ================= LOGIN ================= -->
<h2>Login</h2>
<form method="POST">
    <input type="text" name="username" placeholder="Username" required><br><br>
    <input type="password" name="password" placeholder="Password" required><br><br>
    <label>
        <input type="checkbox" name="remember"> Remember Me
    </label><br><br>
    <button name="login">Login</button>
</form>

<!-- ================= DASHBOARD ================= -->
<?php if (isset($_SESSION['user'])): ?>
    <h2>Welcome <?php echo $_SESSION['user']; ?></h2>
    <a href="?logout=true">Logout</a>
<?php endif; ?>

/* ================= DATABASE =================
ALTER TABLE users ADD remember_token VARCHAR(255) DEFAULT NULL;
*/


AI Spiritual Tools & Interactive Experiences

Explore powerful AI-driven tools for daily guidance, spirituality, fun quizzes, and self-discovery.

Today’s Quote

Get inspiring daily quotes powered by AI to motivate and guide your day.

Explore Now

AI Tarot Card Reader

Reveal insights about your future, love, and career with AI tarot readings.

Read Tarot

Love Match Calculator

Check compatibility and love predictions using AI-based analysis.

Check Match

Fortune Cookie

Open an AI fortune cookie and receive wisdom, luck, and fun messages.

Open Cookie

Quiz Categories

Engage with knowledge-based and fun quizzes across multiple categories.

Start Quiz

Panchang Calendar

View daily Panchang, auspicious timings, tithi, nakshatra, and festivals.

View Panchang

Online Numerology

Discover your destiny number, life path, and numerology predictions.

Calculate Now

Spiritual Feeds

Stay connected with spiritual thoughts, mantras, and divine content.

View Feeds

Quiz Hub

Attempt trending quizzes on GK, spirituality, festivals, and more.

Explore Quizzes