我目前在用户下载存储在我的服务器上的文件时遇到一些问题。我设置了代码,以便在用户点击下载按钮后自动下载文件。它适用于所有文件,但当大小超过 30 MB 时,就会出现问题。用户下载有限制吗?另外,我已经提供了示例代码,并且想知道是否有比使用 PHP 函数“file_get_contents”更好的做法。
谢谢大家的帮助!
$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);
file_get_contents() http://fr.php.net/file_get_contents会将整个文件加载到内存中——使用它的日志。
而且,在 PHP 中,脚本可以使用的内存量是有限的(see memory_limit https://www.php.net/manual/en/ini.core.php#ini.memory-limit)-- 这可能解释您的下载脚本不适用于大文件。
Using [**`readfile()`**][3], instead, might be a better choice : it will read the file, and directly send its content to the output buffer.
这意味着 :
- 不将整个文件加载到内存中
- 不必回显您已加载到内存中的内容。
只需使用这样的东西就可以了:
$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`][4], [`log_errors`][5], and [`error_log`][6])*
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)