PHP文件下载函数

180it 2020-02-24 AM 1746℃ 0条
<?php

/**
 * [download_file 下载文件的函数(大文件)]
 * @param  [type] $path_name [下载文件的路径]
 * @param  [type] $save_name [保存文件的名字]
 * @return [type]            [直接输出]
 */
function download_file($path_name, $save_name){
     ob_end_clean();//清除缓冲区
     $file = fopen($path_name, "rb") or die("Can not find file: $path_name\n");//只读的方式将文件打开,b表示强制二进制形式
     Header("Content-type: application/octet-stream");//通过这句代码客户端浏览器就能知道服务端返回的文件形式。
     Header("Content-Transfer-Encoding: binary");//Content-Transfer-Encoding: binary
     Header("Accept-Ranges: bytes");//告诉客户端浏览器返回的文件大小是按照字节进行计算的
     Header("Content-Length: ".filesize($path_name));//告诉浏览器返回的文件大小
     Header("Content-Disposition: attachment; filename=\"$save_name\"");//告诉浏览器返回的文件的名称。
     while (!feof($file)) {//判断文件是否达到末尾
        echo fread($file, 32768);//每次读取32768字节的长度并输出
     }
     fclose($file);//关闭文件句柄
}



/**
 * [download_file2 下载文件函数二(小文件)]
 * @param  [type] $file_path [下载文件的路径]
 * @return [type]            [直接输出]
 */
function download_file2($file_path){
    if(!file_exists($file_path)){
        die('file does not exists!');    
    }
    $fileName = basename($file_path);//获取路径中的文件名
    header('Content-Disposition:attachment;filename='.$fileName);//告诉浏览器返回的文件名
    header('Content-Length:'.filesize($file_path));//告诉浏览器返回文件的大小
    readfile($file_path);
}

来源:https://gitee.com/miraclehw/fileDownload/blob/master/download_func.php

支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

PHP文件下载函数