What are the best practices for securely serving files in PHP applications?

When serving files in PHP applications, it is important to ensure that the files are served securely to prevent unauthorized access or potential security vulnerabilities. One common best practice is to store files outside of the web root directory to prevent direct access. Additionally, it is recommended to use PHP's readfile() function to serve files, as it handles the file streaming and security checks automatically.

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

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