使用 php 下载文件,而不是处理大文件?

2022-01-02 00:00:00 download large-files php

我使用 php 下载文件,而不是文件本身在新窗口中打开.它似乎适用于较小的文件,但不适用于大文件(我需要它来处理非常大的文件).这是我必须下载文件的代码:

I'm using php to download files, rather than the file itself opening in a new window. It seems to work ok for smaller files, but does not work for large files (I need this to work on very large files). Here's the code I have to download the file:

function downloadFile($file) {   
    if (file_exists($file)) {         
        //download file
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: '.filesize($file));
        ob_clean();
        flush();
        readfile($file);
        exit;   
    };    
};

但是当我尝试下载一个大文件(例如 265mb)时,浏览器告诉我它找不到该文件?这些文件肯定在服务器上,并且该脚本适用于较小的文件.有没有办法下载类似于我已有的大文件?

But when I try to download a large file (example 265mb) the browser tells me that it can't find the file? The files are definately on the server, and the script works fine for the smaller files. Is there any way of downloading large files similar to what I already have?

推荐答案

PHP 对脚本可以运行的时间和可以使用的内存量有限制.脚本可能在它完成之前就超时了,或者因为读入大文件而占用了太多内存.

PHP has limits on how long a script can run, and how much memory it can use. It's possible that the script is timing out before it has completed, or is using up too much memory by reading in the large file.

尝试调整 max_execution_timememory_limit php.ini 中的变量.如果您无权访问 php.ini,请尝试使用 set_time_limit 和/或 ini_set 函数.

Try tweaking the max_execution_time and memory_limit variables in php.ini. If you don't have access to php.ini, try the set_time_limit and/or ini_set functions.

相关文章