PHP Sessions
Sessions in PHP are used to store information about a user across multiple pages. Unlike cookies, session data is stored on the server, making it more secure.
Starting a Session
<?php
session_start(); // Start the session
?>
Explanation: This code snippet starts a session. It must be called before any output is sent to the browser.
Storing Session Variables
<?php
session_start();
$_SESSION["username"] = "JohnDoe"; // Store session variable
?>
Explanation: This example stores a session variable named username
with the value JohnDoe
.
Retrieving Session Variables
<?php
session_start();
if(isset($_SESSION["username"])) {
echo "Username: " . $_SESSION["username"];
} else {
echo "Username is not set.";
}
?>
Explanation: This example checks if the username
session variable is set and retrieves its value. If not set, it displays a message indicating that.
Destroying a Session
<?php
session_start();
session_unset(); // Unset all session variables
session_destroy(); // Destroy the session
?>
Explanation: This example unsets all session variables and destroys the session.