Using Sessions in PHP
Introduction to Sessions
Sessions are a way to store information (in variables) to be used across multiple pages. Unlike cookies, the information is not stored on the user's computer. Sessions are used to store user information to be used across multiple pages (e.g., username, favorite color, etc.). By default, session variables last until the user closes the browser.
Starting a Session
A session is started with the session_start() function. Session variables are set with the global $_SESSION variable.
Example:
<?php session_start(); ?>
This function must be called before any HTML tags. Once started, you can set session variables using the $_SESSION superglobal array.
Setting Session Variables
After starting a session, you can set session variables.
Example:
<?php session_start(); $_SESSION['username'] = 'JohnDoe'; echo 'Session variables are set.'; ?>
Accessing Session Variables
You can access session variables from any page. Simply start the session and use the session variables.
Example:
<?php session_start(); echo 'Username is ' . $_SESSION['username']; ?>
Modifying Session Variables
If you need to change a session variable, just overwrite it.
Example:
<?php session_start(); $_SESSION['username'] = 'JaneDoe'; echo 'Username is ' . $_SESSION['username']; ?>
Destroying a Session
To end a session and clear all session variables, use the session_destroy() function.
Example:
<?php session_start(); session_destroy(); echo 'Session destroyed.'; ?>
This will destroy the session, but to remove existing session variables, you must unset them.
Unsetting Session Variables
To remove a specific session variable, use the unset() function.
Example:
<?php session_start(); unset($_SESSION['username']); echo 'Session variable username is unset.'; ?>