PHP Session Handling

PHP Session Handling – Storing User Data Across Pages ๐Ÿ—‚๏ธ

Ever wondered how websites remember who you are after you log in? ๐Ÿค” Thatโ€™s PHP sessions at work! Sessions allow you to store user data across multiple pages, making them essential for login systems, shopping carts, and more.


๐Ÿ”น Starting a PHP Session

To start a session in PHP, use the session_start() function. This must be called at the **very beginning** of the script before any HTML output.

๐Ÿ“ Example: Starting a Session

<?php
session_start(); // Start the session
?>

Try It Now

Tip: Always call session_start() before outputting anything!


๐Ÿ”น Storing and Retrieving Session Variables

Session variables are stored in the $_SESSION superglobal array.

๐Ÿ“ Example: Setting and Getting Session Data

<?php
session_start(); // Start session

// Set session variables
$_SESSION["username"] = "JohnDoe";
$_SESSION["role"] = "Admin";

// Retrieve session data
echo "Welcome, " . $_SESSION["username"] . "! Your role is: " . $_SESSION["role"];
?>

Try It Now

Output: Welcome, JohnDoe! Your role is: Admin


๐Ÿ”น Checking If a Session Variable Exists

Use isset() to check if a session variable is set.

๐Ÿ“ Example: Checking Session Variables

<?php
session_start();

if (isset($_SESSION["username"])) {
    echo "User is logged in as: " . $_SESSION["username"];
} else {
    echo "No user is logged in.";
}
?>

Try It Now


๐Ÿ”น Destroying a Session (Logout)

To log out a user, you must remove their session data.

๐Ÿ“ Example: Ending a Session

<?php
session_start();
session_unset(); // Remove session variables
session_destroy(); // Destroy session

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

Try It Now

Warning: After calling session_destroy(), session variables will no longer be accessible.


๐ŸŽฏ Key Takeaways

  • session_start() โ†’ Must be called before any output.
  • $_SESSION โ†’ Stores session variables.
  • isset($_SESSION["var"]) โ†’ Checks if a session variable exists.
  • session_unset() โ†’ Clears session variables.
  • session_destroy() โ†’ Ends the session.

๐Ÿ“ Practice Time!

Modify the session example and try storing a shopping cart ๐Ÿ›’ or login system. Can you check if a user is logged in before displaying content? ๐Ÿค”