PHP Cookies Tutorial

11/22/2025
All Articles

PHP cookies tutorial with remember me and theme preference examples

PHP Cookies Tutorial

PHP Cookies Tutorial: Storing User Data in the Browser

Cookies are small pieces of data stored on the user's browser. In PHP, cookies are commonly used to remember user preferences, track sessions, and create "remember me" features.

This beginner-friendly tutorial explains:

  • What cookies are

  • How to set and read cookies in PHP

  • Cookie lifetime and scope

  • Updating and deleting cookies

  • Practical examples (remembering username, theme selection)

  • Best practices and security tips


πŸ”Ή What Is a Cookie?

A cookie is a small text file stored in the user's browser. It contains data in key–value format and is sent back to the server with every HTTP request to that domain.

Typical uses:

  • Remembering login ("Keep me signed in")

  • Storing language or theme preference

  • Tracking cart items (before user logs in)

  • Analytics and tracking (with consent)

In PHP, cookies are managed mainly using:

  • setcookie() – to create or update

  • $_COOKIE – to read values


πŸ›  Setting a Cookie in PHP

You can create a cookie using the setcookie() function. It must be called before any HTML output.

Basic Syntax

setcookie(name, value, expire, path, domain, secure, httponly);

Simple Example: Set a Cookie

<?php
// Set a cookie named "username" with value "Shubham"
setcookie("username", "Shubham", time() + 3600); // Expires in 1 hour

echo "Cookie has been set!";
?>
  • "username" → cookie name

  • "Shubham" → cookie value

  • time() + 3600 → expiry time (current time + 1 hour)


πŸ“– Reading a Cookie in PHP

Cookies are read using the $_COOKIE superglobal array.

<?php
if (isset($_COOKIE['username'])) {
    echo "Welcome back, " . $_COOKIE['username'];
} else {
    echo "Hello, new visitor!";
}
?>

Use isset() to avoid undefined index warnings.


🎯 Example: Remembering Username on a Login Page

login.php

<?php
$username = "";

if (isset($_COOKIE['saved_username'])) {
    $username = $_COOKIE['saved_username'];
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
</head>
<body>

<h2>Login</h2>
<form action="login_action.php" method="POST">
    <label>Username:</label><br>
    <input type="text" name="username" value="<?php echo htmlspecialchars($username); ?>"><br><br>

    <label>Password:</label><br>
    <input type="password" name="password"><br><br>

    <input type="checkbox" name="remember" value="1"> Remember Me<br><br>

    <button type="submit">Login</button>
</form>

</body>
</html>

login_action.php

<?php
$username = $_POST['username'] ?? '';
$password = $_POST['password'] ?? '';

// Dummy example – real apps must verify from database
if ($username === 'admin' && $password === '12345') {

    if (isset($_POST['remember'])) {
        // Save username in cookie for 7 days
        setcookie('saved_username', $username, time() + (7 * 24 * 60 * 60));
    }

    echo "Login successful!";
} else {
    echo "Invalid credentials";
}
?>

⏳ Cookie Lifetime and Expiry

The third parameter of setcookie() defines how long a cookie will live.

Examples:

// Cookie valid for 1 hour
setcookie("test", "value", time() + 3600);

// Cookie valid for 1 day
setcookie("test", "value", time() + 24 * 3600);

// Cookie valid for 30 days
setcookie("test", "value", time() + 30 * 24 * 3600);

If you pass 0 or omit the time, the cookie will last until the browser is closed (session cookie).


🌍 Cookie Path and Domain

You can control where the cookie is sent using the path and domain parameters.

setcookie("username", "Shubham", time() + 3600, "/blog/");
  • Path /blog/ → cookie is available only under URLs starting with /blog/.


πŸ”„ Updating a Cookie

To update a cookie, simply call setcookie() again with the same name and a new value or expiry.

setcookie("username", "NewName", time() + 3600);

❌ Deleting a Cookie

To delete a cookie, set its expiration time in the past.

setcookie("username", "", time() - 3600);

Also, for path-specific cookies, use the same path:

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

🎨 Example: Dark/Light Theme Using Cookies

<?php
$theme = "light";

if (isset($_COOKIE['theme'])) {
    $theme = $_COOKIE['theme'];
}

if (isset($_GET['set'])) {
    $theme = $_GET['set'];
    setcookie('theme', $theme, time() + (30 * 24 * 60 * 60)); // 30 days
    header("Location: theme.php");
    exit;
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Theme Example</title>
</head>
<body style="background-color: <?php echo $theme === 'dark' ? '#333' : '#fff'; ?>; color: <?php echo $theme === 'dark' ? '#fff' : '#000'; ?>;">

<h2>Current Theme: <?php echo ucfirst($theme); ?></h2>
<a href="?set=light">Light Mode</a> | <a href="?set=dark">Dark Mode</a>

</body>
</html>

πŸ›‘ Cookie Security Best Practices

  • Do not store sensitive data (passwords, credit card details) in cookies.

  • Use the httponly flag to prevent JavaScript from accessing cookies:

setcookie("session_id", "abc123", time() + 3600, "/", "", true, true);
// last true = httponly
  • Use the secure flag for HTTPS-only cookies.

  • Always validate and sanitize any data coming from $_COOKIE.

  • Use cookies together with server-side sessions for authentication.


βœ… Summary

In this tutorial, you learned how to:

  • Set cookies with setcookie()

  • Read values using $_COOKIE

  • Control cookie lifetime, path, and scope

  • Update and delete cookies

  • Build real examples like remembering username and theme selection

Cookies are simple but powerful for personalizing user experiences in PHP applications.

 

Article