凌的博客

您现在的位置是: 首页 > 学无止境 > PHP > 

PHP

php 下载文件

2022-03-24 PHP 812
function download($file)
{
    //判断如果文件存在,则跳转到下载路径
    $file_path = ROOT_PATH . $file;
    if (file_exists(ROOT_PATH . $file)) {
        //以只读和二进制模式打开文件
        $file = fopen($file_path, "rb");
        $size = filesize($file_path);
        //告诉浏览器这是一个文件流格式的文件
        header("Content-type: application/octet-stream");
        //请求范围的度量单位
        header("Accept-Ranges: bytes");
        //Content-Length是指定包含于请求或响应中数据的字节长度
        header("Accept-Length: " . $size);
        //用来告诉浏览器,文件是可以当做附件被下载,下载后的文件名称为$file_name该变量的值。
        header("Content-Disposition: attachment; filename=" . basename($file_path));
        //读取文件内容并直接输出到浏览器
        echo fread($file, $size);
        fclose($file);
    } else {
        header('HTTP/1.1 404 Not Found');
    }

}


文章评论

0条评论