Skip to content
PHP Logo

How can the $_SESSION superglobal be properly utilized in PHP?

The $_SESSION superglobal in PHP can be properly utilized to store and access session variables across multiple pages. To use it, you need to start the session using session_start() at the beginning of each PHP script where you want to access session variables. You can then set session variables using $_SESSION['variable_name'] = 'value' and retrieve them using $_SESSION['variable_name'].

php
<?php
// Start the session
session_start();

// Set session variables
$_SESSION['username'] = 'john_doe';
$_SESSION['email'] = 'john.doe@example.com';

// Retrieve session variables
$username = $_SESSION['username'];
$email = $_SESSION['email'];

// Output session variables
echo "Username: $username <br>";
echo "Email: $email";
?>