What best practices should be followed when storing and retrieving session data in PHP applications?

When storing and retrieving session data in PHP applications, it is important to follow best practices to ensure security and efficiency. This includes using secure session handling functions, properly validating and sanitizing user input, and setting appropriate session configurations to prevent session hijacking or data tampering.

// Start the session
session_start();

// Set session data
$_SESSION['user_id'] = 123;
$_SESSION['username'] = 'john_doe';

// Retrieve session data
$user_id = $_SESSION['user_id'];
$username = $_SESSION['username'];

// Destroy the session when no longer needed
session_destroy();