How can you store and retrieve data from a session in PHP?
In PHP, you can store and retrieve data from a session using the $_SESSION
superglobal variable. Sessions are a way to store information across multiple pages of a website or application, and can be used to keep track of user data, shopping carts, login status, and other types of information.
To store data in a session, you can use the $_SESSION
variable like an associative array. For example :
<?php
// Start a new session or resume an existing one
session_start();
// Store some data in the session
$_SESSION['username'] = 'johndoe';
$_SESSION['user_id'] = 1234;
?>
In this example, we are starting a new session or resuming an existing one using the session_start()
function, and then storing two pieces of data in the session using the $_SESSION
superglobal.
To retrieve data from a session, you can simply access the appropriate key in the $_SESSION
variable. For example:
// Start a new session or resume an existing one
session_start();
// Retrieve some data from the session
$username = $_SESSION['username'];
$user_id = $_SESSION['user_id'];
// Use the data in your code
echo "Welcome, $username (user ID: $user_id)";
In this example, we are retrieving the data we stored in the previous example from the $_SESSION
variable and assigning it to two variables. We can then use these variables in our code as needed. Note that we must start the session or resume an existing one using session_start()
before we can access the $_SESSION
superglobal.