Home  >  Article  >  Backend Development  >  PHP下载大文件失败怎么办

PHP下载大文件失败怎么办

PHPz
PHPzOriginal
2016-06-06 20:39:271920browse

PHP下载大文件失败是因为readfile读取文件的时候会把文件放入缓存,导致内存溢出;解决办法:实现分段下载,并限制下载速度即可。

PHP下载大文件失败怎么办

PHP下载大文件失败怎么办?

解决PHP下载大文件失败,并限制下载速度

1.问题: PHP在使用readfile函数定义下载文件时候,文件不可以过大,否则会下载失败,文件损坏且不报错;

2.原因: 这个是因为readfile读取文件的时候会把文件放入缓存,导致内存溢出;

3.解决:分段下载,并限制下载速度;

<?php
//设置文件最长执行时间
set_time_limit(0);
 
if (isset($_GET[&#39;filename&#39;]) && !empty($_GET[&#39;filename&#39;])) {
    $file_name = $_GET[&#39;filename&#39;];
    $file = __DIR__ . &#39;/assets/&#39; . $file_name;
} else {
    echo &#39;what are your searching for?&#39;;
    exit();
}
 
if (file_exists($file) && is_file($file)) {
    $filesize = filesize($file);
    header(&#39;Content-Description: File Transfer&#39;);
    header(&#39;Content-Type: application/octet-stream&#39;);
    header(&#39;Content-Transfer-Encoding: binary&#39;);
    header(&#39;Accept-Ranges: bytes&#39;);
    header(&#39;Expires: 0&#39;);
    header(&#39;Cache-Control: must-revalidate&#39;);
    header(&#39;Pragma: public&#39;);
    header(&#39;Content-Length: &#39; . $filesize);
    header(&#39;Content-Disposition: attachment; filename=&#39; . $file_name);
 
    // 打开文件
    $fp = fopen($file, &#39;rb&#39;);
    // 设置指针位置
    fseek($fp, 0);
 
    // 开启缓冲区
    ob_start();
    // 分段读取文件
    while (!feof($fp)) {
        $chunk_size = 1024 * 1024 * 2; // 2MB
        echo fread($fp, $chunk_size);
        ob_flush(); // 刷新PHP缓冲区到Web服务器
        flush(); // 刷新Web服务器缓冲区到浏览器
        sleep(1); // 每1秒 下载 2 MB
    }
    // 关闭缓冲区
    ob_end_clean();
    fclose($fp);
} else {
    echo &#39;file not exists or has been removed!&#39;;
}
 
exit();

更多相关技术知识,请访问PHP中文网

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn