Home > php教程 > php手册 > 用PHP实现分段下载

用PHP实现分段下载

WBOY
Release: 2016-06-21 08:58:03
Original
1846 people have browsed it

如果只是普通的文件下载,完全没有必要用到php,用个就可以,但是有的时候为让文件保密,只能给一部分人下载,显然不能够把链节告诉别人,如果是这样哪就起不到保密的效果。下面这个函数就是一个用php写的文件下载的函数,它是把文件一段一段地读出来,再传送给客户端.

以下为引用的内容:
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;   
   
    //判断要下载的文件是否存在
    if(!file_exists($file_path))
    {
        echo '对不起,你要下载的文件不存在。';
        return false;
    }

    $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);
   
    $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;

}

本文收集整理自互联网,若您是原文作者,请来信更改作者及出处 Post@chinaz.com(把#改为@)



Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template