How can session variables be effectively used in PHP to control access to specific pages based on user input validation?

Session variables can be effectively used in PHP to control access to specific pages based on user input validation by storing a flag in a session variable after successful validation. This flag can then be checked on each restricted page to determine if the user should have access. If the flag is not set or is set to false, the user can be redirected to a different page.

<?php
session_start();

// Assume user input validation here

// If validation is successful, set a session variable
$_SESSION['authenticated'] = true;

// On restricted pages, check if the user is authenticated
if (!isset($_SESSION['authenticated']) || $_SESSION['authenticated'] !== true) {
    header("Location: unauthorized.php");
    exit();
}
?>