Creating and Destroying Sessions
In this tutorial, we will be discussing sessions in PHP. A session is a global variable stored on the server, that aids in managing information across different pages of an entire website. It is widely used to track user activity on a website. In this article, we will learn how to create and destroy sessions in PHP.
Creating a Session
Before you can store user information in your PHP session, you must first start the session. Session variables are stored in the $_SESSION
superglobal array.
To start a new session, you use the session_start()
function. This function should be the first thing in your document before any HTML tags.
<?php
// Starting a new session
session_start();
?>
After starting a session, you can store information by setting the $_SESSION
variable.
<?php
// Starting a new session
session_start();
// Storing information
$_SESSION["username"] = "John Doe";
$_SESSION["email"] = "[email protected]";
?>
In the example above, we stored two session variables: "username" and "email".
Accessing Session Variables
To access the session variables, you again start a new session and then just reference the session variable that you wish to access.
<?php
// Start the session
session_start();
// Access session variables
echo "Hi, " . $_SESSION["username"] . ".<br>";
echo "Your email is " . $_SESSION["email"] . ".";
?>
Modifying Session Variables
You can easily modify session variables. Like before, start a new session and then assign a new value to the session variable.
<?php
// Start the session
session_start();
// Change session variables
$_SESSION["username"] = "Jane Doe";
?>
In the example above, we changed the value of the "username" session variable to "Jane Doe".
Destroying a Session
There are several ways to destroy a session in PHP. The session_unset()
function frees all session variables. The session_destroy()
function destroys all of the data associated with the current session.
<?php
// Start the session
session_start();
// Remove all session variables
session_unset();
// Destroy the session
session_destroy();
?>
In the example above, we first removed all session variables and then destroyed the session.
Conclusion
In this tutorial, we've learned how to create, access, modify and destroy sessions in PHP. Sessions are a powerful tool that allows you to store user information on the server for later use. But remember, sessions are temporary and will be deleted after the user has left your website.
This knowledge is essential for creating dynamic and interactive websites where user information needs to be preserved across multiple pages. So keep practicing and experimenting with PHP sessions and their practical applications.