What are some best practices for securely allowing file downloads through PHP?

When allowing file downloads through PHP, it is important to ensure that the files are securely served to prevent unauthorized access or malicious attacks. One best practice is to store the files outside of the web root directory to prevent direct access. Additionally, use PHP to authenticate and authorize users before allowing them to download files. Finally, consider implementing measures such as file type checking, limiting download speeds, and using HTTPS to encrypt the data transfer.

<?php
// Check user authentication and authorization here

$filePath = '/path/to/secure/files/filename.pdf';

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