How can PHP headers be utilized to ensure secure file downloads from external directories?

To ensure secure file downloads from external directories in PHP, you can use headers to set the content type, content disposition, and file size before outputting the file. This helps to prevent unauthorized access and ensures that the file is downloaded securely.

<?php
$file = '/path/to/external/file.pdf';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename=' . basename($file));
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
} else {
    echo 'File not found.';
}
?>