Home  >  Article  >  php教程  >  php header()函数实现文件下载的例子

php header()函数实现文件下载的例子

WBOY
WBOYOriginal
2016-05-25 16:46:381113browse

虽然php 中的header()函数 下载文件不支持断点续传功能但有时我们还真需要此功能,如我们下载txt,图片文件时如果直接是个连接估计是直接打开了而不是下载了,那么我们可如何实现下载呢。

<?php
/**
 * 文件下载
 *
 *
 */
header("Content-type:text/html;charset=utf-8");
download(&#39;web/www.phprm.com .txt&#39;, &#39;txt文件下载&#39;);
function download($file, $down_name) {
    $suffix = substr($file, strrpos($file, &#39;.&#39;)); //获取文件后缀
    $down_name = $down_name . $suffix; //新文件名,就是下载后的名字
    //判断给定的文件存在与否
    if (!file_exists($file)) {
        die("您要下载的文件已不存在,可能是被删除");
    }
    $fp = fopen($file, "r");
    $file_size = filesize($file);
    //下载文件需要用到的头
    header("Content-type: application/octet-stream");
    header("Accept-Ranges: bytes");
    header("Accept-Length:" . $file_size);
    header("Content-Disposition: attachment; filename=" . $down_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);
}
?>


本文链接:

收藏随意^^请保留教程地址.

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