Skip to content
PHP

Sessions and Cookies in PHP

Store user data across requests with sessions and cookies in PHP.

By EZ4Code Team
sessioncookieintermediate

Code

<?php

// Start session (must be before any output)
session_start();

// Store data
$_SESSION["user_id"] = 42;
$_SESSION["username"] = "alice";

// Read data
if (isset($_SESSION["user_id"])) {
    echo "Welcome, " . $_SESSION["username"];
}

// Flash message pattern
$_SESSION["flash"] = "Saved successfully!";
// ... redirect, then on next request:
if (isset($_SESSION["flash"])) {
    echo $_SESSION["flash"];
    unset($_SESSION["flash"]);
}

// Destroy session
session_unset();   // clear variables
session_destroy(); // destroy session

// Set cookie
setcookie("theme", "dark", time() + 86400, "/");

Explanation

session_start must be called before any output to access $_SESSION for server-side per-user storage. The flash message pattern stores a value, displays it on the next request, then unsets it. setcookie stores data client-side with an expiry; sessions are more secure for sensitive data.

More PHP Snippets