jassy
answered Apr 27 '23 00:00
To maintain a session between pages in PHP, you need to start a session with session_start() at the beginning of each PHP script that needs to access session variables.
Once a session is started, you can set session variables using the $_SESSION superglobal array, and retrieve them on other pages by starting the session and accessing the same array.
Here's an example of how to maintain a session between pages in PHP:
Page 1 (login.php)
// Start the session
session_start();
// Set a session variable
$_SESSION['user_id'] = 123;
// Redirect to another page
header('Location: dashboard.php');
exit;
In this example, a session is started with session_start(), and a session variable named user_id is set to 123 using $_SESSION['user_id'] = 123.
The user is then redirected to the dashboard.php page using the header() function, which sends an HTTP header to the browser to redirect the user to the specified URL.
Page 2 (dashboard.php)
// Start the session
session_start();
// Check if the user is logged in
if (!isset($_SESSION['user_id'])) {
// Redirect to the login page
header('Location: login.php');
exit;
}
// Retrieve the user ID from the session
$user_id = $_SESSION['user_id'];
// Display the user ID
echo "User ID: " . $user_id;
In this example, the session is started with session_start() , and it is checked if the user_id session variable is set. If the variable is not set, the user is redirected to the login page using header().
If the user_id variable is set, it is retrieved from the session using $_SESSION['user_id'] , and it is displayed on the web page using echo.
Note that the session variables will be available on any PHP script that starts the same session using session_start(). To end a session, you can use session_unset() to remove all session variables, and session_destroy() to destroy the session data on the server.