Course Content
About Lesson

PHP $_SESSION and $_COOKIE

Web applications need a way to store information about users while they navigate pages. HTTP is stateless, which means each request is independent and does not remember previous requests.To handle this, PHP provides:

  • Sessions – server-side storage of user data.
  • Cookies – client-side storage of user data in the browser.

A session is a way to store information (variables) on the server for a specific user across multiple pages.

Key points:

  • Stored on server.
  • Identified using a unique session ID (sent via cookie PHPSESSID or URL).
  • Can store sensitive data securely because it’s on server, not client.
  • Automatically expires after a set time (default 24 minutes in PHP).
PHP
<?php
session_start(); // Start a session or resume the existing one

// Set session variables
$_SESSION['username'] = "JohnDoe";
$_SESSION['email'] = "john@example.com";

echo "Session variables are set.";
?>
PHP
<?php
session_start(); // Always start the session first

echo "Username: " . $_SESSION['username'];
echo "Email: " . $_SESSION['email'];
?>
PHP
<?php
session_start();

// Unset all session variables
session_unset();

// Destroy the session
session_destroy();

echo "Session destroyed. User logged out.";
?>

A cookie is a small file stored on the user’s browser containing information about the user.

Key points:

  • Stored on client-side.
  • Can store user preferences or authentication tokens.
  • Set with an expiration time (otherwise it disappears when browser closes).
  • Less secure than sessions (user can modify it).
PHP
<?php
// Set a cookie named "user" with value "John" for 1 day
setcookie("user", "John", time() + 86400); // 86400 seconds = 1 day

echo "Cookie has been set.";
?>
PHP
<?php
if(isset($_COOKIE['user'])){
    echo "User is: " . $_COOKIE['user'];
} else {
    echo "Cookie is not set.";
}
?>
PHP
<?php
setcookie("user", "", time() - 3600); // Set expiration in past

echo "Cookie deleted.";
?>
FeatureSessionCookie
StorageServerClient (Browser)
SecurityMore secureLess secure
LifetimeUntil browser closed or destroyedCan persist based on expiry
Size LimitCan store large dataMax 4KB
SpeedSlightly slower (server access)Faster (client access)