What is the best practice for storing and retrieving user-specific data in PHP using sessions?

When storing user-specific data in PHP using sessions, it is best practice to securely store sensitive information in the session variables and retrieve them as needed. This can help prevent unauthorized access to user data and ensure data privacy. To do this, you can use the $_SESSION superglobal array to store and retrieve user-specific data.

// Start the session
session_start();

// Store user-specific data in session variables
$_SESSION['user_id'] = 123;
$_SESSION['username'] = 'john_doe';

// Retrieve user-specific data from session variables
$user_id = $_SESSION['user_id'];
$username = $_SESSION['username'];

// Use the retrieved data as needed
echo "User ID: " . $user_id . "<br>";
echo "Username: " . $username;