How can PHP and Apache configurations be optimized to enhance file download security?

To enhance file download security in PHP and Apache configurations, you can restrict direct access to files outside the web root directory by using PHP scripts to serve the files. This ensures that files are only accessible through the PHP script, adding an extra layer of security.

<?php
$file = '/path/to/secure/file.pdf'; // Path to the file on the server
if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/pdf'); // Specify the file type
    header('Content-Disposition: attachment; filename=' . basename($file));
    header('Content-Length: ' . filesize($file));
    readfile($file); // Output the file
    exit;
} else {
    echo 'File not found.';
}
?>