欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php利用header函数下载各种文件

程序员文章站 2024-04-03 19:49:16
本文实例为大家分享了php header函数下载文件实现代码,供大家参考,具体内容如下

本文实例为大家分享了php header函数下载文件实现代码,供大家参考,具体内容如下


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


dl_file($_get ['filename']);

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'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 ();
}

?>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。