Sessions and Cookies
In PHP, sessions and cookies are used to store data across
multiple pages. While both serve the purpose of remembering user information,
they differ in how and where the data is stored.
PHP Sessions
What is a
Session?
A session
is a way to store information (variables) to be used across multiple pages. The
data is stored on the server, and
only a unique session ID is stored in the user’s browser.
Starting a
Session
<?php
session_start();
// Must be at the top of the page
$_SESSION[
"username"] =
"JohnDoe";
echo
"Session is set for user: " .
$_SESSION[
"username"];
?>
Accessing
Session Data
<?php
session_start();
echo
"Welcome back, " .
$_SESSION[
"username"];
?>
Destroying
a Session
<?php
session_start();
session_unset();
// Remove session variables
session_destroy();
// Destroy the session
?>
PHP Cookies
What is
a Cookie?
A cookie
is a small file stored on the user’s browser. Cookies are used to remember
information such as user preferences or login status. The data is stored client-side.
Setting
a Cookie
<?php
setcookie(
"user",
"JohnDoe",
time() + (
86400 *
7),
"/");
// Cookie expires in 7 days
?>
Accessing
a Cookie
<?php
if (
isset(
$_COOKIE[
"user"])) {
echo
"Welcome back, " .
$_COOKIE[
"user"];
}
else {
echo
"User cookie not set.";
}
?>
Deleting
a Cookie
<?php
setcookie(
"user",
"",
time() -
3600,
"/");
// Expire in the past
?>
Sessions vs Cookies
Feature |
Sessions (Server-side) |
Cookies (Client-side) |
Storage |
Stored on the server |
Stored in the browser |
Security |
More secure (data not visible to user) |
Less secure (data visible in browser) |
Capacity |
Large (depends on server) |
Limited (~4KB) |
Use Case |
Login systems, shopping carts |
User preferences, remembering settings |