What are the best practices for using PHP to handle file downloads and renaming?
When handling file downloads in PHP, it is important to set the appropriate headers to ensure the file is downloaded correctly by the browser. To rename a file before downloading it, you can use the `rename()` function in PHP. Additionally, make sure to sanitize the file name to prevent any security vulnerabilities.
// Set headers for file download
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="new_filename.txt"');
// Rename the file before downloading
$old_filename = 'original_filename.txt';
$new_filename = 'new_filename.txt';
rename($old_filename, $new_filename);
// Output the file for download
readfile($new_filename);