forcing a file download with php

半世苍凉 提交于 2019-11-28 01:45:50

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.

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!