I have a website which is a few years old now, it basically offers downloads.
Anyway since moving server people can not download files because its now giving a error 500 error and in the log files it is bringing this error:
malformed header from script. Bad header=1: index.php
The only code which is related to this which I can see anyway is this:
// Echo $productOptionDetails->file;
$file = DOWNLOAD_FOLDER. '/'. $productOptionDetailEntity->file;
if (file_exists($file)) {
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, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file) + 1);
ob_clean();
flush();
readfile($file);
exit;
}
Now if I just output:
// Echo $productOptionDetails->file;
$file = DOWNLOAD_FOLDER. '/'. $productOptionDetailEntity->file;
if (file_exists($file)) {
readfile($file);
exit;
}
It outputs lots of encrypted text so its obviously reading something.
What I have read is that the headers are incorrect but after reading loads of content in php.net as well as other websites this looks fine.
Can anyone give a shout on why I am getting these errors?
Thanks
This problem is related to some output which appears before you send headers.
It is a common problem that some characters like spaces, new lines or even UTF-8 malformed BOM (Byte order mark) are placed before starting php tag.
You need to be sure that absolute nothing is echo-ed before sending headers and need to check that for all included files in your script.
In addition, ob_clean(); and flush(); functions are not needed in you code.
The problem is in
Dot is evaluated before plus so your code is string + 1, result is 1 and this causes that 1 is sent as header. Correct code should be
because according to this page http://www.php.net/manual/en/function.readfile.php no +1 is used. Other solution is
which will work as you want.
As far as I can understand from the code
flush()
is not needed. Also instead of usingjust use
ob_end_clean()
to clear any buffered code.And you said you were moving servers and now it is not working, does it means you have modified PHP settings or version too?
If yes than do post the PHP configuration for
output_buffering
.Based on what you said, the problem is because there is something you said to
echo
before you wrote the code to download. To overcome this problem you should write the code so as theecho
should be written after the download code at the time the download should be get performed.It may not always an
echo
, it may be someHTML tags
instead of it.Download should be the first thing to be run in any page if you want to download something from that page to clients' system.