首页 > 开发 > PHP > 正文

php实现文件下载功能的几个代码分享

2024-05-04 22:21:16
字体:
来源:转载
供稿:网友

一个简单的php文件下载源代码,虽不支持断点续传等,但是可以满足一些常用的需求了。php下载文件其实用一个a标签就能实现,比如 <a href="web/magento-1.8.1.0.zip">magento-1.8.1.0.zip</a> 。但是遇到一些浏览器能识别的格式,比如.txt,.html,.pdf等,再用<a href="web/abc.txt">abc.txt</a> 想必也知道会发生什么了。
代码如下:
<?php

/**
 * 文件下载
 *
**/

header("Content-type:text/html;charset=utf-8");
download('web/magento-1.8.1.0.zip', 'magento下载');

function download($file, $down_name){
 $suffix = substr($file,strrpos($file,'.')); //获取文件后缀
 $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);
}

?>


也可以看看这个注释比较详细的代码:

代码如下:
<?php
 //文件下载,下载一张图片
 //$file_name="Angel.mp3";

 $file_name="bjnihao.jpg";  //出现中文 程序无法完成下载 提示:文件不存在
 //对文件进行转码(PHP文件函数 比较古老 需对中文码转成 gb2312)
 //iconv — Convert string to requested character encoding
 //by www.Vevb.com
 $file_name=iconv("utf-8","gb2312",$file_name);

 //设置文件下载路径(相对路径)
 //$file_path="./dowm/".$file_name;

 //使用绝对路径
 $file_path=$_SERVER['DOCUMENT_ROOT']."/http/dowm/".$file_name;

 //打开文件---先判断再操作
 if(!file_exists($file_path)){

  echo "文件不存在";
  return ; //直接退出
 }

 //存在--打开文件

 $fp=fopen($file_path,"r");

 //获取文件大小
 $file_size=filesize($file_path);

 //http 下载需要的响应头
 header("Content-type: application/octet-stream"); //返回的文件
 header("Accept-Ranges: bytes");   //按照字节大小返回
 header("Accept-Length: $file_size"); //返回文件大小
 header("Content-Disposition: attachment; filename=".$file_name);//这里客户端的弹出对话框,对应的文件名

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表