php-cookies-y-sesiones-en-php

Cookies and Sessions in PHP

  • 4 min

Cookies and sessions are mechanisms for preserving information between HTTP requests.

By default, the HTTP protocol (the web) is “stateless”. This means the server has amnesia: it doesn’t remember anything you did on the previous page. For the server, every click you make is as if you were a new user who just arrived.

To solve this and have “memory” between reloads, we use Cookies and Sessions.

Cookies: saving data in the browser

A Cookie is a small text file that your server asks the user’s browser to save.

  • Where does it live? On the user’s computer (Chrome, Firefox, etc.).
  • What is it used for? Remembering non-sensitive preferences (e.g., “Dark Theme”, “Spanish Language”, “Accept Cookie Policy”) or for tracking (Google Analytics).
  • Security: Low. The user can block, delete, or modify them. Never store passwords here.

How to use:

// Create a cookie (Name, Value, Expiration)
// time() + 3600 means "expires in 1 hour"
// IMPORTANT! setcookie must be placed BEFORE any HTML or echo
setcookie("preferred_language", "en", time() + 3600);

// Read a cookie (if it exists)
if (isset($_COOKIE['preferred_language'])) {
    echo "Your language is: " . $_COOKIE['preferred_language'];
} else {
    echo "No language chosen.";
}

// Delete a cookie
// This is done by setting an expiration date in the past
setcookie("preferred_language", "", time() - 3600);
Copied!

Sessions ($_SESSION): saving data on the server

In a session, data is usually stored on the server and the browser keeps a session identifier. This prevents exposing the content directly, although the identifier must be protected against theft or session fixation.

  • Where does it live? The actual data on your server; the key on the user’s side.
  • What is it used for? User logins, shopping carts, administrative data.
  • Security: The user cannot directly modify the data, but you must protect the cookie with HTTPS, HttpOnly, SameSite, and appropriate configuration.

How to use:

Call session_start() before sending any content on every PHP request that needs to access the session.

// 1. Start the engine (ALWAYS at the beginning of the file)
session_start();

// 2. Save data (Persists even if you reload the page)
$_SESSION['user_id'] = 45;
$_SESSION['name'] = "Laura";
$_SESSION['role'] = "Admin";

// 3. Read data on another page (or after reloading)
if (isset($_SESSION['name'])) {
    echo "Welcome back, " . $_SESSION['name'];
}

// 4. Logout
// session_destroy(); // Destroy the data on the server
Copied!

Key differences (summary table)

FeatureCookiesSessions
LocationUser’s browserData on the server; identifier in a cookie
TrustUser can modify themThe ID can be stolen; it needs protection
CapacitySmall (typically around 4 KB per cookie)Depends on server storage
ExpirationSet by the applicationDepends on the cookie and server cleanup
Ideal UseNon-sensitive preferencesLogin, cart, and user-associated state

Practical example: simple login

This is the logical skeleton of any authentication system in PHP.

<?php
session_start(); // Step 1: Turn on the session system

// Simulate correct credentials
$realUser = "admin";
$realHash = password_hash("demo-password", PASSWORD_DEFAULT);

// If the form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $u = $_POST['user'];
    $p = $_POST['pass'];

    if ($u === $realUser && password_verify($p, $realHash)) {
        // LOGIN SUCCESSFUL: Save the "signature" in the session
        session_regenerate_id(true);
        $_SESSION['logged_in'] = true;
        $_SESSION['user'] = $u;
        echo "Login successful! Reload the page to see the change.";
    } else {
        echo "Incorrect credentials.";
    }
}

// Check if already logged in
if (isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true) {
    echo "<h1>Control Panel for " . htmlspecialchars($_SESSION['user'], ENT_QUOTES, 'UTF-8') . "</h1>";
    echo "<a href='logout.php'>Logout</a>";
} else {
    echo "<h1>Welcome, Guest</h1>";
    // The HTML login form would go here...
}
?>
Copied!