Back to Curriculum

Sessions and Cookies

📚 Lesson 7 of 12 ⏱️ 40 min

Sessions and Cookies

40 min

Sessions and cookies enable state management in stateless HTTP, allowing web applications to remember users and maintain data across page requests. Sessions store data on the server (more secure), while cookies store data on the client's browser (more accessible). Understanding when to use sessions vs cookies is crucial for building secure, functional web applications. Both are essential for user authentication, shopping carts, user preferences, and maintaining application state.

Sessions in PHP store data on the server and use a session ID (stored in a cookie) to associate requests with session data. Sessions are started with `session_start()`, which must be called before any output is sent to the browser. Session data is stored in the `$_SESSION` superglobal array and persists until the session is destroyed or expires. Sessions are more secure than cookies because data stays on the server, but they require server storage and can be lost if the session ID cookie is deleted.

Cookies are small pieces of data stored in the user's browser and sent with each request to the same domain. Cookies are set with `setcookie()` and accessed via the `$_COOKIE` superglobal. Cookies have expiration dates, paths, and domains that control when and where they're sent. Cookies are useful for user preferences, tracking, and non-sensitive data. However, cookies can be modified by users and are sent with every request, so they shouldn't store sensitive information.

Security considerations are crucial for sessions and cookies. Session IDs should be regenerated on login to prevent session fixation attacks. Use `session_regenerate_id()` after authentication. Set secure cookie flags (`Secure` for HTTPS only, `HttpOnly` to prevent JavaScript access). Use `session_set_cookie_params()` to configure secure session cookies. Never store sensitive data in cookies—use sessions instead. Understanding security helps you protect user data and prevent attacks.

Session management includes starting sessions, storing data, retrieving data, regenerating session IDs for security, and destroying sessions on logout. Sessions can be configured with `session_set_cookie_params()` and `ini_set()` for session settings. Session data is automatically serialized and stored (typically in files or databases). Understanding session management helps you build secure authentication and state management.

Best practices include always calling `session_start()` before output, regenerating session IDs after login, using secure cookie settings, storing only necessary data in sessions, cleaning up session data properly, and destroying sessions on logout. Sessions should timeout appropriately, and sensitive data should never be stored in cookies. Understanding sessions and cookies enables you to build secure, stateful web applications.

Key Concepts

  • Sessions store data on the server; cookies store data in the browser.
  • Sessions use session IDs (stored in cookies) to track users.
  • Sessions are more secure for sensitive data than cookies.
  • session_start() must be called before any output.
  • Cookies are useful for user preferences and non-sensitive data.

Learning Objectives

Master

  • Using sessions to store and retrieve user data
  • Working with cookies for client-side data storage
  • Understanding security considerations for sessions and cookies
  • Implementing secure session management

Develop

  • Security thinking for state management
  • Understanding stateless HTTP and state management solutions
  • Designing secure authentication and session systems

Tips

  • Always call session_start() before any output (including whitespace).
  • Regenerate session IDs after login: session_regenerate_id(true).
  • Use secure cookie settings (Secure, HttpOnly flags).
  • Store sensitive data in sessions, not cookies.

Common Pitfalls

  • Calling session_start() after output, causing headers already sent errors.
  • Not regenerating session IDs, allowing session fixation attacks.
  • Storing sensitive data in cookies, creating security vulnerabilities.
  • Not destroying sessions on logout, leaving security holes.

Summary

  • Sessions store server-side data; cookies store client-side data.
  • Sessions are more secure for sensitive information.
  • session_start() must be called before any output.
  • Security considerations are crucial for sessions and cookies.
  • Understanding sessions and cookies enables stateful web applications.

Exercise

Create a simple login system using sessions and demonstrate cookie usage.

<?php
session_start();

// Simple user database (in real app, use actual database)
$users = [
    "admin" => password_hash("admin123", PASSWORD_DEFAULT),
    "user" => password_hash("user123", PASSWORD_DEFAULT)
];

$message = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = $_POST["username"] ?? "";
    $password = $_POST["password"] ?? "";
    
    if (isset($users[$username]) && password_verify($password, $users[$username])) {
        $_SESSION["user"] = $username;
        $_SESSION["login_time"] = time();
        
        // Set a cookie for user preference
        setcookie("theme", "dark", time() + 3600, "/");
        
        $message = "Login successful!";
    } else {
        $message = "Invalid username or password";
    }
}

// Handle logout
if (isset($_GET["logout"])) {
    session_destroy();
    setcookie("theme", "", time() - 3600, "/");
    header("Location: " . $_SERVER["PHP_SELF"]);
    exit();
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Login System</title>
</head>
<body>
    <?php if (isset($_SESSION["user"])): ?>
        <h1>Welcome, <?php echo htmlspecialchars($_SESSION["user"]); ?>!</h1>
        <p>Login time: <?php echo date("Y-m-d H:i:s", $_SESSION["login_time"]); ?></p>
        <p>Theme: <?php echo $_COOKIE["theme"] ?? "light"; ?></p>
        <a href="?logout=1">Logout</a>
    <?php else: ?>
        <h1>Login</h1>
        <?php if ($message): ?>
            <p style="color: <?php echo strpos($message, 'successful') !== false ? 'green' : 'red'; ?>">
                <?php echo htmlspecialchars($message); ?>
            </p>
        <?php endif; ?>
        
        <form method="POST">
            <div>
                <label for="username">Username:</label>
                <input type="text" id="username" name="username" required>
            </div>
            <br>
            <div>
                <label for="password">Password:</label>
                <input type="password" id="password" name="password" required>
            </div>
            <br>
            <button type="submit">Login</button>
        </form>
        
        <p><small>Try: admin/admin123 or user/user123</small></p>
    <?php endif; ?>
</body>
</html>

Code Editor

Output