How can the code snippet be improved to ensure that only permitted sites are included and to prevent unauthorized access?

To ensure that only permitted sites are included and to prevent unauthorized access, we can implement a whitelist check for the referring URL. This means that we will only allow requests from specific sites that we trust. By checking the referring URL against a list of permitted sites, we can restrict access to only those that are authorized.

$permittedSites = array("https://example.com", "https://trustedsite.com");

$referrer = $_SERVER['HTTP_REFERER'];

if (in_array($referrer, $permittedSites)) {
    // Proceed with including the file
    include('file-to-include.php');
} else {
    // Redirect or display an error message
    header("Location: unauthorized.php");
    exit;
}