What are the best practices for managing file downloads in PHP scripts, considering the use of readfile() and exit()?
When managing file downloads in PHP scripts using readfile() and exit(), it is important to ensure that the file paths are properly sanitized to prevent directory traversal attacks. Additionally, it is recommended to set appropriate headers for the file download, such as Content-Type and Content-Disposition. Finally, using exit() after readfile() ensures that no additional content is sent after the file download.
<?php
// Sanitize the file path to prevent directory traversal attacks
$filepath = '/path/to/file.txt';
// Set appropriate headers for the file download
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($filepath) . '"');
// Output the file content and exit
readfile($filepath);
exit();
?>