views:

267

answers:

3

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?

+1  A: 

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.

Michał Chaniewski
+1  A: 

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.

merkuro
You can replace everything from '$fp = ...' to 'fclose()' with a call to readfile().
too much php
This looks like a very neat alternative to my bloated code. Will use this one in the future! THX!
merkuro
+1  A: 

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.

GApple