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
Arrays and Array Functions in PHP
Create indexed, associative, and multidimensional arrays with map and filter.
String Functions in PHP
Manipulate strings with substr, replace, explode, and sprintf in PHP.
Read and Write Files in PHP
Read, write, append, and iterate files with PHP filesystem functions.
PDO Database Queries in PHP
Connect and run prepared statements safely with PDO in PHP.
Classes and Inheritance in PHP
Define classes with constructors, visibility, and inheritance in PHP.