How can PHP be used to restrict access to downloadable files based on the referring URL?

To restrict access to downloadable files based on the referring URL, you can use PHP to check the HTTP referer header and only allow access if it matches a specific URL. This can help prevent unauthorized access to your files by ensuring that they are only accessed from approved sources.

<?php
$allowed_referer = 'https://www.example.com';

if(isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'] == $allowed_referer) {
    // Serve the downloadable file
    $file = 'path/to/downloadable/file.pdf';
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    readfile($file);
} else {
    // Redirect or display an error message
    echo 'Access denied.';
}
?>