← Back to Chapters

PHP Session Variables

? PHP Session Variables

?️ Quick Overview

Sessions are used to store data across multiple pages. Unlike cookies, which are stored on the client's browser, session data is stored on the server. The session variables are unique to each user and last until the user closes the browser or the session is destroyed.

? Key Concepts

  • Sessions store user-specific data on the server
  • Each user gets a unique session ID
  • Session data persists across multiple pages
  • Sessions end when destroyed or expired

? Syntax / Theory

Before using session variables, the session must be initialized using session_start(). This function must be called before any HTML output.

? View Code Example
// Start a new or existing session
session_start();

? Code Example: Starting a Session

? View Code Example
// Initialize session and store values
<?php
session_start();
$_SESSION["username"] = "JohnDoe";
$_SESSION["email"] = "john@example.com";
echo "Session variables are set!";
?>

? Code Example: Accessing Session Variables

? View Code Example
// Access stored session values safely
<?php
session_start();
if(isset($_SESSION["username"]) && isset($_SESSION["email"])) {
echo "Welcome " . $_SESSION["username"];
echo "<br>Email: " . $_SESSION["email"];
} else {
echo "No session variables are set.";
}
?>

? Live Output / Explanation

The isset() function ensures that session variables exist before accessing them, preventing warnings and errors.

?️ Additional Example: Destroying a Session

? View Code Example
// Clear and destroy session data
<?php
session_start();
session_unset();
session_destroy();
echo "Session destroyed successfully!";
?>

? Use Cases

  • User authentication systems
  • Shopping carts in e-commerce
  • Maintaining user preferences
  • Multi-page form handling

? Tips & Best Practices

  • Always call session_start() at the top of your script
  • Validate session data before use
  • Regenerate session IDs for security
  • Destroy sessions on logout

? Try It Yourself

  • Create a login system using session variables
  • Check login status using sessions
  • Update session values dynamically
  • Implement logout using session_destroy()