网站推广.NET

网站推广.NET

php三种方式下载文件

来源:互联网

本文主要和大家分享php三种方式下载文件,希望能帮助到大家。

1、直接添加文件链接

<button>    <a href = "http://localhost/down.zip">    下载文件</button>

点击该按钮下载:

2、传递参数查找并跳转到下载链接

传递参数:

<button>    <a href = "http://localhost?f=&#39;down&#39;">    下载文件</button>

查找文件并挑战到下载链接:

<?php$down = $_GET[&#39;f&#39;];   //获取文件参数$filename = $down.&#39;.zip&#39;; //获取文件名称$dir ="down/";  //相对于网站根目录的下载目录路径$down_host = $_SERVER[&#39;HTTP_HOST&#39;].&#39;/&#39;; //当前域名//判断如果文件存在,则跳转到下载路径if(file_exists(__DIR__.&#39;/&#39;.$dir.$filename)){    header(&#39;location:http://&#39;.$down_host.$dir.$filename);}else{    header(&#39;HTTP/1.1 404 Not Found&#39;);}

结果:

  • 文件存在

    立即学习“PHP免费学习笔记(深入)”;

  • 文件不存在

3、head() 和 fread()函数把文件直接输出到浏览器

<?php  $file_name = "down";$file_name = "down.zip";     //下载文件名    $file_dir = "./down/";        //下载文件存放目录    //检查文件是否存在    if (! file_exists ( $file_dir . $file_name )) {        header(&#39;HTTP/1.1 404 NOT FOUND&#39;);  } else {        //以只读和二进制模式打开文件       $file = fopen ( $file_dir . $file_name, "rb" );     //告诉浏览器这是一个文件流格式的文件        Header ( "Content-type: application/octet-stream" );     //请求范围的度量单位      Header ( "Accept-Ranges: bytes" );      //Content-Length是指定包含于请求或响应中数据的字节长度        Header ( "Accept-Length: " . filesize ( $file_dir . $file_name ) );      //用来告诉浏览器,文件是可以当做附件被下载,下载后的文件名称为$file_name该变量的值。    Header ( "Content-Disposition: attachment; filename=" . $file_name );        //读取文件内容并直接输出到浏览器        echo fread ( $file, filesize ( $file_dir . $file_name ) );        fclose ( $file );        exit ();    }

结果:和第二个一样

总结:

第一个和第二个操作比较简单,但是容易暴露文件的真实地址,安全性不高,第三种能够较好的把文件的真实地址隐藏起来

标签: php下载