PHP Sessions
A session is a way to store information (in variables) to be used across multiple pages. Unlike cookies, session data is stored on the server, which makes it more secure.
1. Starting a Session
To use sessions in PHP, you must first start the session using
session_start(). This function must be placed at the top of the page before any HTML output.
session_start();
?>
2. Creating Session Variables
Session variables are stored in the $_SESSION superglobal array.
session_start();
$_SESSION["username"] = "ExpertAdmin";
$_SESSION["email"] = "admin@example.com";
echo "Session variables are set.";
?>
3. Accessing Session Variables
You can access session variables on other pages after calling
session_start().
session_start();
echo "Username: " . $_SESSION["username"];
echo "<br>";
echo "Email: " . $_SESSION["email"];
?>
4. Checking if Session Exists
Use isset() to check whether a session variable is set.
session_start();
if(isset($_SESSION["username"])) {
echo "Session is active";
} else {
echo "No active session found";
}
?>
5. Destroying a Session
To remove all session variables and destroy the session, use
session_unset() and session_destroy().
session_start();
session_unset();
session_destroy();
echo "Session destroyed successfully.";
?>
session_start() at the very beginning of your PHP file.
Session data is stored on the server, which makes it more secure than cookies.