When should readfile() be used instead of include for outputting text content in PHP?
readfile() should be used instead of include for outputting text content in PHP when you want to directly output the contents of a file to the browser without executing any PHP code within the file. This is useful when you simply want to display the contents of a text file, such as a CSS file or an image, without any PHP processing.
<?php
$file = 'example.txt';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: text/plain');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
} else {
echo 'File not found.';
}
?>