php如何从服务器下载文件

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼 原创
2023-02-25 09:46:02 3379浏览

PHP下载服务器上的文件,可以通过自定义函数方法downtemplateAction()来实现下载,在其方法体内有判断文件是否存在以及是否成功下载、关闭文件等功能。

相关推荐:《php教程

具体示例如下:

/**
 * @todo 下载文件
 */
public function downtemplateAction(){
    header("Content-type:text/html;charset=utf-8");
    $file_name = "template.xlsx";
    $file_name = iconv("utf-8","gb2312",$file_name);
    $file_sub_path = APP_PATH.'/data/obj/2018-03-21/';
    $file_path=$file_sub_path.$file_name;
    if(!file_exists($file_path))
    {
        echo "下载文件不存在!";
        exit;
    }
 
    $fp=fopen($file_path,"r");
    $file_size=filesize($file_path);
    //下载文件需要用到的头
    Header("Content-type: application/octet-stream");
    Header("Accept-Ranges: bytes");
    Header("Accept-Length:".$file_size);
    Header("Content-Disposition: attachment; filename=".$file_name);
    $buffer=1024;
    $file_count=0;
    while(!feof($fp) && $file_count<$file_size)
    {
        $file_con=fread($fp,$buffer);
        $file_count+=$buffer;
        echo $file_con;
    }
    fclose($fp);    //关闭这个打开的文件
}

以上就是php如何从服务器下载文件的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。