What are the important rules and guidelines to follow when working with sessions in PHP?

When working with sessions in PHP, it is important to follow certain rules and guidelines to ensure proper functionality and security. Some important rules include starting the session at the beginning of the script, using session variables securely by validating and sanitizing user input, and destroying the session when it is no longer needed to prevent unauthorized access.

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

// Validate and sanitize user input
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);

// Check if the username and password are valid
if ($username === 'admin' && $password === 'password') {
    $_SESSION['authenticated'] = true;
} else {
    echo 'Invalid username or password';
}

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