This is a simple toy script, but I’m having issues with it. I’m trying to have the user download a file using readfile() but also have the script write to the page. Upon executig this script in the browser the file IS downloaded, but it appears that the file is being printed to the screen as well. Additionally I’m getting the following errors:
Warning: Cannot modify header information – headers already sent by (output started at /Applications/XAMPP/xamppfiles/htdocs/test.php:8) in /Applications/XAMPP/xamppfiles/htdocs/test.php on line 11
Warning: Cannot modify header information – headers already sent by (output started at /Applications/XAMPP/xamppfiles/htdocs/test.php:8) in /Applications/XAMPP/xamppfiles/htdocs/test.php on line 12
Warning: Cannot modify header information – headers already sent by (output started at /Applications/XAMPP/xamppfiles/htdocs/test.php:8) in /Applications/XAMPP/xamppfiles/htdocs/test.php on line 13
Warning: Cannot modify header information – headers already sent by (output started at /Applications/XAMPP/xamppfiles/htdocs/test.php:8) in /Applications/XAMPP/xamppfiles/htdocs/test.php on line 14
Code is as follows:
<?php
$file = './1966.xlsx';
echo "thanks";
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
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();
?>
Do I need to declare headers for the entire script? I got the header and readfile() parts from the php manual online.
You’re getting those errors because you’re sending content to the browser before sending the headers.
To fix this, you need to remove
echo "thanks";.