php header下载

<?php
//设置文件最长执行时间
set_time_limit(0);
ini_set('memory_limit', '512M');
if(isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'POST')){
    $tmp_arr = $_POST;
}
if($_SERVER['REQUEST_METHOD'] == 'GET'){
    $tmp_arr = $_GET;
}
if(isset($tmp_arr['file_path']) && trim($tmp_arr['file_path'])!='') {
    $file = $tmp_arr['file_path'];
    if (file_exists($file) && is_file($file)) {
        $filesize = filesize($file);
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Transfer-Encoding: binary');
        header('Accept-Ranges: bytes');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . $filesize);
        header('Content-Disposition: attachment; filename=' . basename($file));

        // 打开文件
        $fp = fopen($file, 'rb');
        // 设置指针位置
        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 'file not exists or has been removed!';
    }
    exit();
}else{
    die(json_encode(array('return_code'=>10008, 'return_message'=>'PARAM_ERROR', 'error'=>'参数错误')));
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值