💡 Ask Tutor

PHP Sessions and Cookies – Managing User State

What Are Sessions and Cookies?

Web applications are stateless by default — each HTTP request is independent. This means the server doesn’t “remember” the user between pages.

To solve this, PHP provides:

  • Sessions – Store data on the server (recommended for sensitive info)
  • Cookies – Store data on the user’s browser

Together, they enable features like:

  • Login/logout systems
  • Shopping carts
  • User preferences (dark/light theme)
  • Remember-me functionality

Difference Between Sessions and Cookies

FeatureSessionsCookies
Stored InServerUser’s browser
SecurityMore secureLess secure (user can modify)
Size LimitLarger (~20MB server-side)Smaller (~4KB)
LifetimeUntil browser/session ends (or manually expired)Can persist for days or months
Use CasesLogin data, cart contentsRemember me, preferences

How PHP Sessions Work

  1. You call session_start() at the beginning of your script.
  2. PHP assigns a session ID to the user.
  3. Data is stored server-side and linked to the ID.
  4. The ID is stored as a cookie in the browser.

Starting and Storing a Session

session_start() (must be first)

PHP
<?php
session_start();
$_SESSION['username'] = "Jay";
echo "Session started!";
?>

Accessing Session Data

PHP
<?php
session_start();
echo $_SESSION['username']; // Output: Jay
?>

Destroying a Session

PHP
<?php
session_start();
session_unset(); // Clears session variables
session_destroy(); // Ends session
?>

Creating and Using Cookies

PHP
setcookie("username", "Jay", time() + (86400 * 7)); // 7 days
  • time() + seconds sets expiration
  • This must be called before any HTML output
PHP
echo $_COOKIE["username"];
PHP
setcookie("username", "", time() - 3600);

Example: Simple Login System Using Sessions

📄 login.php

PHP
<?php
session_start();

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $user = $_POST['username'];
  $pass = $_POST['password'];

  if ($user === "admin" && $pass === "1234") {
    $_SESSION['loggedin'] = true;
    $_SESSION['username'] = $user;
    header("Location: dashboard.php");
  } else {
    echo "Invalid credentials!";
  }
}
?>

<form method="post">
  Username: <input type="text" name="username"><br>
  Password: <input type="password" name="password"><br>
  <input type="submit" value="Login">
</form>

📄 dashboard.php

PHP
<?php
session_start();

if (!isset($_SESSION['loggedin'])) {
  header("Location: login.php");
  exit;
}

echo "Welcome, " . $_SESSION['username'] . "!<br>";
echo "<a href='logout.php'>Logout</a>";
?>

📄 logout.php

PHP
<?php
session_start();
session_destroy();
header("Location: login.php");
?>

Best Practices

  • Always call session_start() at the top of every session-using file
  • Use cookies for non-sensitive data (like theme, preferences)
  • Always sanitize data before storing in a session or cookie
  • Set cookie expiration and secure flags where possible:
PHP
setcookie("example", "value", time()+3600, "/", "", true, true);
  • Destroy sessions properly on logout (session_unset() + session_destroy())

Common Mistakes

  • Sending output before calling session_start() or setcookie()
  • Not checking isset() before accessing session or cookie variables
  • Storing sensitive data in cookies (always use sessions instead)
  • Not destroying sessions after logout (security risk)

Notes:

  • Sessions store user data on the server and are more secure
  • Cookies store small pieces of data on the client (browser)
  • Sessions are ideal for login/authentication
  • Always destroy sessions on logout and avoid storing raw passwords in any storage

Practice Tasks

Task 1: Build a Welcome Page
If $_SESSION['username'] is set, show a personalized message. Otherwise, redirect to login.php.

Task 2: Remember Theme Using Cookies
Create a dropdown that lets the user choose “Dark” or “Light” mode. Store the selection in a cookie and remember it for 7 days.

Task 3: Auto-Login via Cookie
After login, offer a “Remember Me” checkbox. If selected, set a cookie remember_user. On next visit, auto-login based on that cookie.