Home  >  Article  >  Backend Development  >  How to implement download breakpoint resume in PHP

How to implement download breakpoint resume in PHP

藏色散人
藏色散人Original
2022-11-06 09:39:581814browse

php实现下载断点续传的方法:1、创建一个php示例文件;2、定义一个download方法;3、通过“if (empty($file) or !is_file($file)) {...}”方法检查文件是否存在;4、通过“if (!empty($_SERVER['HTTP_RANGE'])) {...}”实现文件下载,并支持断点续传即可。

How to implement download breakpoint resume in PHP

本教程操作环境:windows7系统、PHP8.1版、Dell G3电脑。

php怎么实现下载断点续传?

PHP实现文件下载,支持断点续传

我一般废话比较少,直接甩代码,不懂扣我,再不懂就只能扣脚丫了,OK?

PHP实现文件下载接口,支持断点续传,下载器可以查看文件大小。文件分片传输,内存消耗低。注意:使用时建议增加安全路径限制及可下载文件类型限制

/**
 * 文件下载
 * @param string $file 文件绝对路径
 */
function download($file)
{
    str_replace(['/','\\'], DIRECTORY_SEPARATOR, $file);
    //检查文件是否存在
    if (empty($file) or !is_file($file)) {
        die('文件不存在');
    }
    $fileName = basename($file);
    //以只读和二进制模式打开文件
    $fp = @fopen($file, 'rb');
    if ($fp) {
        // 获取文件大小
        $file_size = filesize($file);
        //告诉浏览器这是一个文件流格式的文件
        header('content-type:application/octet-stream');
        header('Content-Disposition: attachment; filename=' . $fileName);
        // 断点续传
        $range = null;
        if (!empty($_SERVER['HTTP_RANGE'])) {
            $range = $_SERVER['HTTP_RANGE'];
            $range = preg_replace('/[\s|,].*/', '', $range);
            $range = explode('-', substr($range, 6));
            if (count($range) < 2) {
                $range[1] = $file_size;
            }
            $range = array_combine(array('start', 'end'), $range);
            if (empty($range['start'])) {
                $range['start'] = 0;
            }
            if (empty($range['end'])) {
                $range['end'] = $file_size;
            }
        }
        // 使用续传
        if ($range != null) {
            header('HTTP/1.1 206 Partial Content');
            header('Accept-Ranges:bytes');
            // 计算剩余长度
            header(sprintf('content-length:%u', $range['end'] - $range['start']));
            header(sprintf('content-range:bytes %s-%s/%s', $range['start'], $range['end'], $file_size));
            // fp指针跳到断点位置
            fseek($fp, sprintf('%u', $range['start']));
        } else {
            header('HTTP/1.1 200 OK');
            header('Accept-Ranges:bytes');
            header('content-length:' . $file_size);
        }
        while (!feof($fp)) {
            echo fread($fp, 4096);
            ob_flush();
        }
        fclose($fp);
    } else {
        die('File loading failed');
    }
}

推荐学习:《PHP视频教程

The above is the detailed content of How to implement download breakpoint resume in PHP. For more information, please follow other related articles on the PHP Chinese website!

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