Sessions and cookies are essential for maintaining state and storing data across multiple pages or visits in PHP applications.

Starting a Session

Sessions allow you to store user data across multiple pages. To start a session, use the session_start() function.

  • Starting a Session:
  <?php
session_start(); // Must be called at the beginning of the script
?>
  

Session Variables

Session variables are used to store data that you want to persist across different pages during a user’s visit.

  • Setting Session Variables:
  <?php
session_start();
$_SESSION['username'] = 'JohnDoe';
?>
  
  • Accessing Session Variables:
  <?php
session_start();
echo $_SESSION['username']; // Outputs: JohnDoe
?>
  
  • Unsetting Session Variables:
  <?php
session_start();
unset($_SESSION['username']);
?>
  
  • Destroying a Session:
  <?php
session_start();
session_unset(); // Remove all session variables
session_destroy(); // Destroy the session
?>
  

Managing Sessions

Sessions can be configured and managed through PHP’s php.ini settings or programmatically.

  • Configuring Session Settings:

    • session.gc_maxlifetime - Maximum lifetime of session data in seconds.
    • session.save_path - Directory where session files are stored.
  • Custom Session Handlers:

  • You can implement custom session handling mechanisms using session_set_save_handler().

Working with Cookies

Cookies are small pieces of data stored on the client’s browser. They can be used to remember user preferences or session data.

  • Setting Cookies:
  <?php
setcookie('user', 'JohnDoe', time() + 3600); // Expires in 1 hour
?>
  
  • Accessing Cookies:
  <?php
echo $_COOKIE['user']; // Outputs: JohnDoe
?>
  
  • Deleting Cookies:
  <?php
setcookie('user', '', time() - 3600); // Expired in the past
?>
  
  • Cookie Attributes:

    • Expiration Time: Set with the third parameter of setcookie().
    • Path: The path on the server where the cookie will be available.
    • Domain: The domain where the cookie is valid.
    • Secure: Indicates if the cookie should only be sent over secure connections.
    • HttpOnly: Makes the cookie accessible only through the HTTP protocol.

Sessions and cookies are fundamental for managing user state and preferences in web applications. Proper implementation ensures that user data is handled securely and efficiently.

Session Configuration in php.ini

  session.cookie_httponly = 1
session.cookie_secure = 1
session.cookie_samesite = Strict
session.use_strict_mode = 1
session.gc_maxlifetime = 1440
  

session.use_strict_mode rejects session IDs not created by the server, mitigating fixation attacks.

Regenerating Session ID on Privilege Change

  session_start();

// After successful login
session_regenerate_id(true);
$_SESSION['user_id'] = $userId;
$_SESSION['logged_in'] = true;
  

Call session_regenerate_id(true) after login and role elevation; the true parameter deletes the old session file.

Flash Messages

Store one-time messages across redirects:

  function flash(string $key, ?string $message = null): ?string {
    if ($message !== null) {
        $_SESSION['_flash'][$key] = $message;
        return null;
    }
    $value = $_SESSION['_flash'][$key] ?? null;
    unset($_SESSION['_flash'][$key]);
    return $value;
}

// Set before redirect
flash('success', 'Profile updated');
header('Location: /profile');

// Read on next page
echo flash('success');
  
  setcookie('theme', 'dark', [
    'expires' => time() + 86400 * 30,
    'path' => '/',
    'secure' => true,
    'httponly' => true,
    'samesite' => 'Lax',
]);
  

Session Storage Backends

For multi-server deployments, store sessions in Redis instead of flat files:

  session.save_handler = redis
session.save_path = "tcp://127.0.0.1:6379"
  

Common Pitfalls

  • Calling session_start() after output has been sent causes “headers already sent” errors.
  • Storing large objects in $_SESSION bloats session files and slows every request.
  • Using cookies for sensitive data — cookies are client-visible; sessions stay server-side.