What are some alternative methods in PHP for offering downloads from protected directories without exposing .htaccess access credentials?

When offering downloads from protected directories in PHP, it is important to ensure that the .htaccess access credentials are not exposed to users. One alternative method is to use PHP to read the file contents and then serve them to the user. This way, the actual file path is not exposed, providing an extra layer of security.

<?php
$filename = 'path/to/protected/file.txt';

if (file_exists($filename)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($filename));
    readfile($filename);
    exit;
} else {
    echo 'File not found.';
}
?>