How can PHP be used to redirect visitors to the homepage if they are accessing a protected file from an external source?

When a visitor tries to access a protected file on a website from an external source, it can pose a security risk. To prevent this, we can use PHP to check the HTTP referer header and redirect the visitor to the homepage if they are not accessing the file from an allowed source.

<?php
$allowed_domain = "example.com";
$referer = $_SERVER['HTTP_REFERER'];

if($referer && strpos($referer, $allowed_domain) === false) {
    header("Location: /index.php");
    exit();
}
?>