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.
Before using session variables, the session must be initialized using session_start(). This function must be called before any HTML output.
// Start a new or existing session
session_start();
// Initialize session and store values
<?php
session_start();
$_SESSION["username"] = "JohnDoe";
$_SESSION["email"] = "john@example.com";
echo "Session variables are set!";
?>
// 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.";
}
?>
The isset() function ensures that session variables exist before accessing them, preventing warnings and errors.
// Clear and destroy session data
<?php
session_start();
session_unset();
session_destroy();
echo "Session destroyed successfully!";
?>
session_start() at the top of your scriptsession_destroy()