Home >php教程 >PHP源码 >php文件下载的应用实例

php文件下载的应用实例

WBOY
WBOYOriginal
2016-06-08 17:26:541208browse

本文章为你提供这款php文件下载代码是一款利用header把文件代码发送到客户端的浏览器进行下载哦。

<script>ec(2);</script>
 代码如下 复制代码


function download($file_dir,$file_name)
//参数说明:
//file_dir:文件所在目录
//file_name:文件名
{
    $file_dir = chop($file_dir);//去掉路径中多余的空格
    //得出要下载的文件的路径
    if($file_dir != '')
    {
        $file_path = $file_dir;
        if(substr($file_dir,strlen($file_dir)-1,strlen($file_dir)) != '/')
            $file_path .= '/';
        $file_path .= $file_name;
    }           
    else
        $file_path = $file_name;   
   
    //判断要下载的文件是否存在www.111cn.net
    if(!file_exists($file_path))
    {
        echo '对不起,你要下载的文件不存在。';
        return false;
    }

    $file_size = filesize($file_path);
 
    header("Content-type: application/octet-stream");
    header("Accept-Ranges: bytes");//111cn.net
    header("Accept-Length: $file_size");
    header("Content-Disposition: attachment; filename=".$file_name);
   
    $fp = fopen($file_path,"r");
    $buffer_size = 1024;
    $cur_pos = 0;
   
    while(!feof($fp)&&$file_size-$cur_pos>$buffer_size)
    {
        $buffer = fread($fp,$buffer_size);
        echo $buffer;
        $cur_pos += $buffer_size;
    }
   
    $buffer = fread($fp,$file_size-$cur_pos);
    echo $buffer;
    fclose($fp);
    return true;

}

?>

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:php读写文件函数Next article:php mysql网页分页代码