How does the HTTP_REFERER variable impact the behavior of the PHP script when downloading files?

The HTTP_REFERER variable contains the URL of the page that linked to the current page. This variable can be used to restrict access to files based on where the request originated from. By checking the HTTP_REFERER variable in the PHP script that handles file downloads, you can ensure that files are only downloaded when the request comes from an authorized source.

if(isset($_SERVER['HTTP_REFERER']) && strpos($_SERVER['HTTP_REFERER'], 'example.com') !== false){
    // Allow file download
    $file_path = 'path/to/file.pdf';
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="file.pdf"');
    readfile($file_path);
} else {
    // Redirect or display an error message
    header('Location: unauthorized.php');
}