What best practices should be followed when using session variables in PHP for access control?

Session variables should never be directly manipulated to control access in PHP. Instead, use session variables to store user authentication status and roles, and then use these variables to determine access control throughout your application. Always validate user input and sanitize data to prevent any potential security vulnerabilities.

// Start the session
session_start();

// Check if the user is logged in
if(isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true){
    // User is logged in, allow access to restricted content
    echo "Welcome, you have access to this content.";
} else {
    // User is not logged in, redirect to login page
    header("Location: login.php");
    exit();
}