I am trying to get a text file to download using a PHP script but when my script runs the file contents are displayed in the browser window. I tried this solution: Why downloaded file is not downloaded instead it is shown in browser? However the code I have already has a content length header. This is my PHP code (which I obtained from another post 1 and modified for a text file)
$file = 'file.txt';
header('Content-Description: File Transfer');
header('Content-Type: text/plain');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
Browser output of text file contents
I tried to copy an example from php.com for a pdf file and I get the same symbols as in the post I linked.
I am not sure why this is happening. I am running MAMP 3.5 with PHP version 5.6.10 on Chrome.
This has really baffled me since so far I have been able to find solutions online for everything I have done. As far as I can tell, what I am doing is correct so any advice would be much appreciated.
Many thanks,
Nehal Patel
RESOLVED (9/4/15) with guidance from Marcus: removed flush() an ob_clean().
$file = 'file.txt';
header('Content-Description: File Transfer');
header('Content-Type: text/plain');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;