Are there any best practices or security considerations to keep in mind when allowing file downloads through PHP?
When allowing file downloads through PHP, it is important to validate user input to prevent directory traversal attacks. Additionally, consider storing files outside of the web root to prevent direct access. Implementing proper file permissions and using secure download links can also enhance security.
<?php
$file = 'path/to/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.';
}
?>