18910140161

php实现文件下载的方法

顺晟科技

2022-09-22 09:24:57

129

如果我们不想让浏览器直接打开服务器上PDF,txt文件,则直接将它们下载到本地,可以通过修改header头协议的方法进行实现。下面顺晟科技博客就来详细的说一说。

php实现文件下载的方法

下面提供一个自定义的php下载文件的函数,我们下载文件时直接调用此函数即可。

php文件下载函数

/**
 * php 实现文件下载
 * 顺晟科技博客
 * http://feiniaomy.com
 * 
 * @param $filename 服务器上被下载文件的路径
 * @return string
 */
function download($filename)
{ 
    if ((isset($filename))&&(file_exists($filename))){ 
        header("Content-length: ".filesize($filename)); 
        header('Content-Type: application/octet-stream'); 
        header("Accept-Ranges: bytes"); 
        header('Content-Disposition: attachment; filename="' . $filename . '"'); 
        readfile("$filename"); 
    } else { 
        // return false;
        echo "没有找到要下载的文件!"; 
    } 
}

函数调用:

#下载图片文件
download('bb.png');
#下载txt文件
download('em.txt');
#下载压缩包
download('feiniaomy.zip');
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航