How can PHP be used to offer a text file for download instead of displaying it in the browser?
When a text file is accessed through a web browser, it may be displayed directly instead of being offered for download. To force the browser to download the file instead, you can use PHP to set the appropriate headers. By sending the correct Content-Type and Content-Disposition headers, you can prompt the browser to download the file instead of displaying it.
<?php
$file = 'example.txt';
header('Content-Type: text/plain');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
readfile($file);
?>
Keywords
Related Questions
- What potential security risks can arise from not using htmlentities() in PHP form fields?
- Are there any pitfalls to be aware of when using LIKE statements to compare date values in MySQL queries with PHP?
- What are some alternative methods to achieve the same functionality as shell_exec in PHP without using shell commands?