How can PHP be used to create a download script that allows for custom file names during download?
To create a download script in PHP that allows for custom file names during download, you can use the `header()` function to set the `Content-Disposition` header with the desired file name. This will prompt the browser to download the file with the specified name.
<?php
$file = 'path/to/your/file.txt';
$customFileName = 'custom_filename.txt';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $customFileName . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
} else {
echo 'File not found.';
}
?>
Related Questions
- What are the best practices for handling multiple forms on a single webpage in PHP to prevent data loss?
- How can PHP beginners effectively handle complex PHP functions for generating select boxes in forms?
- How can PHP be used to retrieve and display multiple data fields for a selected item in a dropdown menu?