What best practices should be followed when using PHP sessions to maintain state across web pages?

When using PHP sessions to maintain state across web pages, it is important to follow best practices to ensure security and efficiency. Always start the session at the beginning of each page where session data is needed, and remember to destroy the session when it is no longer needed. Additionally, avoid storing sensitive information directly in the session data and always sanitize and validate user input before storing it in the session.

// Start the session
session_start();

// Store data in the session
$_SESSION['username'] = 'JohnDoe';

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

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