How can PHP be used to serve files for download while preventing external access?

To serve files for download while preventing external access in PHP, you can check if the request is coming from the same server using the $_SERVER['HTTP_HOST'] variable. If the request is not from the same server, you can deny access by sending a 403 Forbidden header.

<?php
$allowed_host = 'yourdomain.com';

if($_SERVER['HTTP_HOST'] !== $allowed_host){
    header('HTTP/1.0 403 Forbidden');
    die('Access forbidden');
}

$file_path = '/path/to/your/file.txt';
$file_name = basename($file_path);

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $file_name . '"');
readfile($file_path);
exit;
?>