I know how to make the download occur, when the download happens it appends the html from the web page that causes the download. How do I filter out the HTML?
-
Can you clarify, ideally with some sample code? It's not clear what you mean by "causes the download" – Matthew Flaschen Jun 15 '09 at 23:08
3 Answers
If I understand you correctly it's a common problem. I solved it by using ob_start at the beginning of my index.php (start/root/entry file) before ANY output occures and for the download I do the following:
ob_end_clean();
header("Content-Type: application/octet-stream; ");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ". filesize("thefileinquestion").";");
header("Content-disposition: attachment; filename=thefileinquestion");
$fp = fopen(thefileinquestion, "r");
while(!feof($fp)){
$buffer = fread($fp, 1024);
echo $buffer;
flush();
}
fclose($fp);
die();
Update
The ob_start
command buffers any output (eg via echo, printf) and prevents anything being send to the user BEFORE your actual download. The ob_end_clean
than stops this behavior and allows direct output again. HTH.

- 6,161
- 2
- 27
- 29
-
3You can replace everything from '$fp = ...' to 'fclose()' with a call to readfile(). – too much php Jun 15 '09 at 23:19
-
This looks like a very neat alternative to my bloated code. Will use this one in the future! THX! – merkuro Jun 15 '09 at 23:27
-
11) Send the actual media type, not "application/octet-stream". 2) There is no "Content-Transfer-Encoding" header field in HTTP. Really. – Julian Reschke Mar 20 '12 at 07:54
I understand that you're trying to output some stream for download from PHP page?
If so, then don't output that content from the page that contains HTML, but redirect to separate php page that outputs only the download stream, with headers if necessary.

- 4,646
- 1
- 18
- 15
-
This is like a half answer. It is just above "If you want it to download, force it to download." – Jake Jun 12 '13 at 13:48
Make sure you're not outputting additional data after the file stream is completed. Use a call to exit() to end page execution after the file stream is finished. Any characters after a closing '?>' tag (such as a newline) can cause download problems as well.
Moving the download script to its own file should make finding any problems easier, because it does only one thing. To avoid outputing any final newlines, you can omit the closing '?>' tag in this case as well at the end of your script.

- 3,463
- 22
- 27