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);
?>