Are there any best practices or recommendations for securely including pages in PHP to prevent unauthorized access?

To securely include pages in PHP and prevent unauthorized access, it is recommended to use a combination of authentication and authorization techniques. This can involve checking if the user is logged in and has the necessary permissions before including the page. Additionally, it is important to sanitize user input to prevent any potential security vulnerabilities.

<?php
session_start();

// Check if user is logged in
if(!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

// Check if user has necessary permissions
if($_SESSION['role'] !== 'admin') {
    header("Location: unauthorized.php");
    exit();
}

// Sanitize user input
$page = filter_input(INPUT_GET, 'page', FILTER_SANITIZE_STRING);

// Include the page
include($page);
?>