首頁 > 後端開發 > php教程 > php利用header函數下載各種文件

php利用header函數下載各種文件

高洛峰
發布: 2023-03-04 07:34:01
原創
1173 人瀏覽過

本文實例為大家分享了php header函數下載檔案實作程式碼,供大家參考,具體內容如下

http://www.php.net/manual/en/function.readfile.php

<?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利用header函數下載各種檔案相關文章請關注PHP中文網!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板