Working with Session Variables
Introduction
In PHP, a session is a way to store information that can be used across multiple pages. Unlike a cookie, session data is not stored on the user's computer, but on the server. A session variable holds information about one single user, and is available to all pages in one application.
In this article, we will learn how to work with session variables in PHP.
Starting a PHP Session
Before you can store any information in session variables, you must first start a PHP session. The session_start() function must be the very first thing in your document before any HTML tags.
<?php
session_start();
?>
Storing Session Data
To store data in a session variable, you use the PHP global variable $_SESSION. This variable is an associative array containing session variables available to the current script.
<?php
session_start();
// Set session variables
$_SESSION["username"] = "JohnDoe";
$_SESSION["email"] = "[email protected]";
echo "Session variables are set.";
?>
In the above example, we've set two session variables: "username" and "email".
Accessing Session Data
You can access PHP session variables with the global variable $_SESSION.
<?php
session_start();
// Echo session variables
echo "Hi, " . $_SESSION["username"]. ".<br>";
echo "Your email is " . $_SESSION["email"]. ".";
?>
In the above example, we're echoing the session variables we set in the previous example.
Modifying Session Data
To change a session variable, just overwrite it.
<?php
session_start();
// to change a session variable, just overwrite it
$_SESSION["username"] = "JaneDoe";
echo "Username is now " . $_SESSION["username"] . ".";
?>
In the above example, we've changed the "username" session variable from "JohnDoe" to "JaneDoe".
Destroying a Session
To end a session or destroy all session variables, you can use the session_unset() and session_destroy() functions.
<?php
session_start();
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
In the above example, we've first removed all session variables with session_unset(), and then destroyed the session with session_destroy().
Conclusion
Session variables are a great way to store information across multiple pages in a PHP application. They are easy to use and secure, as the information is stored on the server rather than the user's computer.
Remember to always start a session before using any session variables, and to destroy a session when you're done with it. Happy coding!