Working With Sessions and Cookies in PHP

    How PHP stores user data, remembers login states, and powers modern web applications.

    8 min read
    PHP
    Sessions
    Authentication
    Web Development

    Introduction

    Whenever you login to a website, add items to your cart, or return to a page and find it remembers your preferences — that's thanks to sessions and cookies.

    These two features are essential to all web applications:

    • Cookies store small bits of data in the browser.
    • Sessions store secure data on the server.

    If you're building login systems, shopping carts, dashboards, or anything requiring user state — you must understand how both work.

    This guide explains them simply with examples you can use right away.

    1. What Are Cookies?

    A cookie is a small piece of text stored on the user's browser.

    They are used for:

    • ✔ Remembering users ("Stay logged in")
    • ✔ Tracking preferences (dark mode, language)
    • ✔ Analytics & ad tracking
    • ✔ Saving cart items for guests

    Setting a Cookie in PHP

    setcookie("username", "Boopie", time() + 3600); // 1 hour

    Reading a Cookie

    echo $_COOKIE["username"];

    Deleting a Cookie

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

    Cookies are client-side, meaning they live in the user's browser.

    2. What Are Sessions?

    A session stores user data on the server and assigns it a unique ID.

    Sessions are used for:

    • ✔ Login systems
    • ✔ Shopping carts
    • ✔ User permissions
    • ✔ Remembering choices across pages

    Starting a Session

    Every PHP session starts with:

    session_start();

    This must appear at the top of the page, before any HTML output.

    Storing Data in a Session

    $_SESSION['username'] = "Boopie";

    Accessing Session Data

    echo $_SESSION['username'];

    Destroying a Session

    session_start();
    session_destroy();

    Sessions are more secure than cookies because the data stays on your server, not in the user's browser.

    3. How Sessions and Cookies Work Together

    When a session starts, PHP:

    1. Generates a random session ID
    2. Stores the data on the server
    3. Sends a cookie named PHPSESSID to the browser

    Example of the cookie:

    PHPSESSID=fc2390abc912acd1129

    This cookie does not contain data, only the session ID.

    The user cannot read or modify the session data — it's all server-side.

    This is why sessions are used for:

    • User authentication
    • Admin dashboards
    • Sensitive settings

    4. Cookies vs Sessions (Quick Comparison)

    FeatureCookiesSessions
    StoredBrowserServer
    Size Limit~4KBServer memory
    SecurityLowHigh
    LifetimeControlled by expiryUntil session timeout
    Best ForPreferences, trackingLogin, cart, secure data

    General Rule:

    Store sensitive data in sessions, not cookies.

    5. Practical Example: Login System Flow

    Here's the typical login workflow:

    1. User logs in via form

    if ($validUser) {
        session_start();
        $_SESSION["logged_in"] = true;
        $_SESSION["username"] = $username;
    }

    2. Accessing protected pages

    session_start();
    
    if (!isset($_SESSION["logged_in"])) {
        header("Location: login.php");
        exit();
    }

    3. Logging out

    session_start();
    session_unset();
    session_destroy();

    This pattern powers every real login system.

    6. Secure Cookie Tips

    Never store passwords or sensitive data in cookies

    Always store those in the session.

    For security:

    setcookie(
        "token",
        $token,
        time() + 3600,
        "/",           // Available across the site
        "",            // Domain
        true,          // Secure flag (HTTPS only)
        true           // HttpOnly (JS can't read)
    );

    Use:

    • secure = protects from man-in-the-middle
    • httponly = prevents JavaScript stealing cookies
    • samesite = prevents CSRF attacks

    7. When to Use Cookies vs Sessions

    Use Cookies When:

    • You need long-term remembering
    • Data is non-sensitive (theme, language)
    • You want preferences saved even after browser closes

    Use Sessions When:

    • User is logged in
    • Sensitive data is stored
    • Temporary workflow (checkout, form steps)
    • You want server-side control

    8. Summary

    You now understand:

    • ✔ What cookies are
    • ✔ What sessions are
    • ✔ How PHP generates session IDs
    • ✔ How to read, write, and delete both
    • ✔ When to use each
    • ✔ Security best practices
    • ✔ Login system examples

    Sessions and cookies form the foundation of all web apps. Master these and you can build authentication systems, dashboards, e-commerce carts, and more.

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service