Two ways to remember user data across page loads.
Understanding sessions and cookies
Both store information about a user. The difference is where: sessions live on the server; cookies live in the user’s browser.
Cookies: the browser’s memory
Cookies are small files on the user’s computer. Sites use them for login tokens, preferences, and similar small bits of state.
Setting cookies in PHP
Use the setcookie() function:
<?php
setcookie("user", "John Doe", time() + 3600, "/"); // 3600 = 1 hour
?>
This creates a cookie named user, sets its value to John Doe, and expires it in one hour.
Accessing cookies
Read cookies from the $_COOKIE superglobal:
<?php
if(!isset($_COOKIE["user"])) {
echo "Welcome, guest!";
} else {
echo "Welcome back, " . $_COOKIE["user"] . "!";
}
?>
Deleting cookies
Set the expiry to a time in the past:
<?php
setcookie("user", "", time() - 3600, "/");
?>
Sessions: maintaining user state on the server
Sessions store data on the server for each user. PHP creates a session file and keeps your variables there until the session ends.
Starting a PHP session
Call session_start() before you read or write session data:
<?php
session_start();
?>
This must run before any HTML output – put it at the very top of the file.
Storing and accessing session data
Use the $_SESSION superglobal:
<?php
// Store session data
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
// Access session data
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
Ending a session
Clear session data with session_unset(), then destroy the session with session_destroy():
<?php
session_unset(); // remove all session variables
session_destroy(); // destroy the session
?>
Practical use of sessions and cookies
On a shop site, cookies might remember language or theme. Sessions typically hold the shopping cart and login state.
Example: a simple login system
A bare-bones login flow using sessions:
// On login page
<?php
session_start();
// Check login credentials
if ($_POST["username"] == "JohnDoe" && $_POST["password"] == "password") {
$_SESSION["loggedin"] = true;
header("Location: welcome.php"); // Redirect to welcome page
} else {
echo "Invalid credentials";
}
?>
// On welcome page
<?php
session_start();
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
echo "Welcome, John Doe!";
} else {
header("Location: login.php"); // Redirect to login page
}
?>
Security considerations
Sessions and cookies are useful, but handle them carefully:
- Sensitive data: do not store passwords or similar secrets in cookies.
- Session security: regenerate session IDs after login to reduce hijacking risk; use HTTPS.
- Cookie security: set
HttpOnlyandSecureflags where you can.
Sessions and cookies are how PHP sites remember who someone is and what they were doing. Get the basics down, then focus on the security habits above.

