PHP simple Login & Remember me script using Cookies

A “Remember me” checkbox on a login form is very common. But the way it is built matters a lot. In this tutorial you will learn two safe methods: remember the username in the form, and keep the user logged in with a secure token.

Note: Never save the password in a cookie. Cookies are stored in the browser, anyone can read or steal them, and a password in a cookie is a password in the open. Older tutorials (including an old version of this one) did this. Do not copy that idea.

Method 1: remember the username

This is the simple case: the form shows the username automatically the next time, and the user types only the password. We save only the username in a cookie.

login.php

<?php
session_start();

$username = $_COOKIE["remembered_user"] ?? "";   // value for the form
$message = "";

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $username = trim($_POST["username"] ?? "");
    $password = $_POST["password"] ?? "";

    // Replace this check with your real login check (see the login and registration script)
    $valid = ($username === "robin" && $password === "secret123");

    if ($valid) {
        session_regenerate_id(true);
        $_SESSION["user"] = $username;

        if (!empty($_POST["remember"])) {
            setcookie("remembered_user", $username, [
                "expires"  => time() + 30 * 24 * 3600,   // 30 days
                "path"     => "/",
                "secure"   => true,
                "httponly" => true,
                "samesite" => "Lax"
            ]);
        } else {
            setcookie("remembered_user", "", time() - 3600, "/");   // delete it
        }

        header("Location: dashboard.php");
        exit;
    }

    $message = "Wrong username or password.";
}
?>
<form method="post">
    <p>Username: <input type="text" name="username" value="<?php echo htmlspecialchars($username); ?>"></p>
    <p>Password: <input type="password" name="password"></p>
    <p><label><input type="checkbox" name="remember" <?php echo $username !== "" ? "checked" : ""; ?>> Remember my username</label></p>
    <p><button type="submit">Login</button></p>
</form>
<p><?php echo htmlspecialchars($message); ?></p>

Result: If the user checks the box, the username is already in the field the next time. If the box is not checked, the cookie is deleted and the field is empty.


Method 2: keep the user logged in (stay signed in)

Many sites keep the user logged in for days, even after the browser is closed. For this you must not store the user id or the password in the cookie. Do this:

  • When the user logs in with “remember me”, create two random values: a selector (to find the record) and a validator (the secret).
  • Save the selector and a hash of the validator in a database table. Put selector:validator in the cookie.
  • On the next visit, find the record by the selector and compare the hash of the cookie validator with hash_equals(). If it matches, log the user in and create a new token.
  • On logout, delete the token from the database and the cookie.

Database table

CREATE TABLE remember_tokens (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    user_id INT UNSIGNED NOT NULL,
    selector CHAR(18) NOT NULL UNIQUE,
    token_hash CHAR(64) NOT NULL,
    expires_at DATETIME NOT NULL
);

Create the token after a successful login (save this function in a file named functions.php, and include that file in your login page and in auth.php. Call it right after the password check. $conn is a mysqli connection)

<?php
function rememberUser(mysqli $conn, int $userId): void
{
    $selector  = bin2hex(random_bytes(9));      // 18 characters
    $validator = bin2hex(random_bytes(32));
    $hash      = hash("sha256", $validator);
    $expires   = date("Y-m-d H:i:s", time() + 30 * 24 * 3600);

    $stmt = $conn->prepare("INSERT INTO remember_tokens (user_id, selector, token_hash, expires_at) VALUES (?, ?, ?, ?)");
    $stmt->bind_param("isss", $userId, $selector, $hash, $expires);
    $stmt->execute();

    setcookie("remember", $selector . ":" . $validator, [
        "expires"  => time() + 30 * 24 * 3600,
        "path"     => "/",
        "secure"   => true,
        "httponly" => true,
        "samesite" => "Lax"
    ]);
}
?>

auth.php: include this at the top of every protected page, after your database connection file and functions.php. It logs the user in from the cookie when there is no session.

<?php
session_start();

if (empty($_SESSION["user_id"]) && !empty($_COOKIE["remember"])) {
    $parts = explode(":", $_COOKIE["remember"], 2);

    if (count($parts) === 2) {
        [$selector, $validator] = $parts;

        $stmt = $conn->prepare("SELECT id, user_id, token_hash FROM remember_tokens WHERE selector = ? AND expires_at > NOW()");
        $stmt->bind_param("s", $selector);
        $stmt->execute();
        $row = $stmt->get_result()->fetch_assoc();

        if ($row && hash_equals($row["token_hash"], hash("sha256", $validator))) {
            session_regenerate_id(true);
            $_SESSION["user_id"] = $row["user_id"];

            // Remove the used token and create a new one
            $del = $conn->prepare("DELETE FROM remember_tokens WHERE id = ?");
            $del->bind_param("i", $row["id"]);
            $del->execute();
            rememberUser($conn, (int) $row["user_id"]);
        }
    }
}

if (empty($_SESSION["user_id"])) {
    header("Location: login.php");
    exit;
}
?>

On logout, delete the row of that token from remember_tokens, delete the cookie with setcookie("remember", "", time() - 3600, "/"), and destroy the session.


Why this is safe

  • The cookie has a random secret that means nothing without the database. A stolen database does not give working cookies, because only a hash is saved.
  • The token changes every time it is used, and it expires after 30 days.
  • httponly hides the cookie from JavaScript, secure sends it only over HTTPS and samesite helps against CSRF.

Run this only on HTTPS. Learn the basics in PHP Cookies and PHP Session, and see the login and registration code in PHP Simple Login and Registration Script.


Learn more about the similar topics:
Tutorials
PHP Cookies
PHP Session
Exercises & Assignments
No Content Found.
Interview Questions & Answers
Difference Between Cookies and Session
How can we create a session in php?
How to get the current session id in PHP?