PHP File Downloading Questions

社会主义新天地 提交于 2019-12-12 10:08:14

问题


I am currently running into some problems with user's downloading a file stored on my server. I have code set up to auto download a file once the user hits the download button. It is working for all files, but when the size get's larger than 30 MB it is having issues. Is there a limit on user download? Also, I have supplied my example code and am wondering if there is a better practice than using the PHP function 'file_get_contents'.

Thank You all for the help!

$path = $_SERVER['DOCUMENT_ROOT'] . '../path/to/file/';
$filename = 'filename.zip';
$filesize = filesize($path . $filename);
@header("Content-type: application/zip");
@header("Content-Disposition: attachment; filename=$filename");
@header("Content-Length: $filesize")
echo file_get_contents($path . $filename);

回答1:


file_get_contents() will load the whole file into memory -- using a log of it.

And, in PHP, the amount of memory a script can used is limited (see memory_limit) -- which might explain that your download script doesn't work for big files.


Using readfile(), instead, might be a better choice : it will read the file, and directly send its content to the output buffer.

This means :

  • Not loading the whole file into memory
  • Not having to echo the content you've loaded in memory.

Just using something like this should be OK :

$path = $_SERVER['DOCUMENT_ROOT'] . '../path/to/file/';
$filename = 'filename.zip';
$filesize = filesize($path . $filename);
@header("Content-type: application/zip");
@header("Content-Disposition: attachment; filename=$filename");
@header("Content-Length: $filesize")
readfile($path . $filename);


(BTW : do you really want to silence errors this way, with the @ operator ? Another solution could be to not display them, but log them to a file -- see display_errors, log_errors, and error_log)




回答2:


file_get_contents() pulls the file contents into the PHP VM. Use readfile() to stream the file without reading it.



来源:https://stackoverflow.com/questions/2624039/php-file-downloading-questions

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