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 ?>
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"]; ?>
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."; } ?>
๐น 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."; ?>
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? ๐ค