How can routing be implemented in PHP to protect pages without manual intervention for each page?

To implement routing in PHP to protect pages without manual intervention for each page, you can create a central routing file that checks the requested URL against a list of allowed routes and redirects to a login page if the user is not authenticated. This way, you can easily protect multiple pages without having to manually add authentication checks to each individual page.

<?php
// Define allowed routes
$allowed_routes = [
    'home' => 'home.php',
    'about' => 'about.php',
    // Add more routes as needed
];

// Check if requested route is allowed
$route = $_GET['route'] ?? 'home';
if (!array_key_exists($route, $allowed_routes)) {
    header('Location: login.php');
    exit;
}

// Include the requested page
include $allowed_routes[$route];