php基于header函数下载各种文件的方法

墨辰丷
发布: 2023-03-29 08:24:02
原创
1393 人浏览过

这篇文章主要为大家详细介绍了php利用header函数下载各种文件的代码,感兴趣的小伙伴们可以参考一下

具体内容如下

<?php
/**
* 下载文件
* header函数
*
*/


dl_file($_GET [&#39;filename&#39;]);

function dl_file($file)
{
 $file = ".//images//" . $file;
 //First, see if the file exists
 
 if (! is_file ( $file ))
 {
  die ( "<b>404 File not found!</b>" );
 }
 
 // Gather relevent info about file
 $len = filesize ( $file );
 $filename = basename ( $file );
 $file_extension = strtolower ( substr ( strrchr ( $filename, "." ), 1 ) );
 
 // This will set the Content-Type to the appropriate setting for the file
 switch ($file_extension)
 {
  case "pdf" :
   $ctype = "application/pdf";
   break;
  case "exe" :
   $ctype = "application/octet-stream";
   break;
  case "zip" :
   $ctype = "application/zip";
   break;
  case "doc" :
   $ctype = "application/msword";
   break;
  case "xls" :
   $ctype = "application/vnd.ms-excel";
   break;
  case "ppt" :
   $ctype = "application/vnd.ms-powerpoint";
   break;
  case "gif" :
   $ctype = "image/gif";
   break;
  case "png" :
   $ctype = "image/png";
   break;
  case "jpeg" :
  case "jpg" :
   $ctype = "image/jpg";
   break;
  case "mp3" :
   $ctype = "audio/mpeg";
   break;
  case "wav" :
   $ctype = "audio/x-wav";
   break;
  case "mpeg" :
  case "mpg" :
  case "mpe" :
   $ctype = "video/mpeg";
   break;
  case "mov" :
   $ctype = "video/quicktime";
   break;
  case "avi" :
   $ctype = "video/x-msvideo";
   break;
  
  // The following are for extensions that shouldn&#39;t be downloaded
  // (sensitive stuff, like php files)
  case "php" :
  case "htm" :
  case "html" :
  case "txt" :
   die ( "<b>Cannot be used for " . $file_extension . " files!</b>" );
   break;
  
  default :
   $ctype = "application/force-download";
 }
 
 
 $file_temp = fopen ( $file, "r" );
 
 
 // Begin writing headers
 header ( "Pragma: public" );
 header ( "Expires: 0" );
 header ( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
 header ( "Cache-Control: public" );
 header ( "Content-Description: File Transfer" );
 // Use the switch-generated Content-Type
 header ( "Content-Type: $ctype" );
 // Force the download
 $header = "Content-Disposition: attachment; filename=" . $filename . ";";
 header ( $header );
 header ( "Content-Transfer-Encoding: binary" );
 header ( "Content-Length: " . $len );
 
 
 //@readfile ( $file );
 echo fread ( $file_temp, filesize ( $file ) );
 fclose ( $file_temp );
 
 exit ();
}

?>
登录后复制

总结:以上就是本篇文的全部内容,希望能对大家的学习有所帮助。

相关推荐:

php实现文件上传详解

php 实现Hash表功能

php Session无效分析资料整理图文详解

以上是php基于header函数下载各种文件的方法的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!