Home > php教程 > php手册 > php实现文件下载简单示例(代码实现文件下载)

php实现文件下载简单示例(代码实现文件下载)

WBOY
Release: 2016-06-06 20:24:21
Original
922 people have browsed it

这篇文章主要介绍了php实现文件下载简单示例,需要的朋友可以参考下

复制代码 代码如下:


public function downloads($name){
$name_tmp = explode("_",$name);
$type = $name_tmp[0];
$file_time = explode(".",$name_tmp[3]);
$file_time = $file_time[0];
$file_date = date("Y/md",$file_time);
$file_dir = SITE_PATH."/data/uploads/$type/$file_date/"; 

if (!file_exists($file_dir.$name)){
 header("Content-type: text/html; charset=utf-8");
 echo "File not found!";
 exit;
} else {
 $file = fopen($file_dir.$name,"r");
 Header("Content-type: application/octet-stream");
 Header("Accept-Ranges: bytes");
 Header("Accept-Length: ".filesize($file_dir . $name));
 Header("Content-Disposition: attachment; filename=".$name);
 echo fread($file, filesize($file_dir.$name));
 fclose($file);
}
}


示例2:代码实现文件下载

一般实现下载都是调用url来下载,,但是遇到ie能识别打开的文件就不能用这种方式了,比如下载一个图片、html网页等,这时就需要编程来实现,以下php代码可以解决:

复制代码 代码如下:



if( empty($_GET['FileName'])|| empty($_GET['FileDir'])|| empty($_GET['FileId'])){
    echo'<script> alert("非法连接 !"); location.replace ("index.php") </script>'; exit();
}
$file_name=$_GET['FileName'];
$file_dir=$_GET['FileDir'];
$FileId=$_GET['FileId'];
$file_dir = $file_dir."/";
if   (!file_exists($file_dir.$file_name))   {   //检查文件是否存在 
  echo   "文件找不到"; 
  exit;   
  }   else   { 
$file = fopen($file_dir . $file_name,"r"); // 打开文件
// 输入文件标签
Header("Content-type: application/octet-stream");
Header("Accept-Ranges: bytes");
Header("Accept-Length: ".filesize($file_dir . $file_name));
Header("Content-Disposition: attachment; filename=" . $file_name);
// 输出文件内容
echo fread($file,filesize($file_dir . $file_name));
fclose($file);
exit();
}
?>

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