PHP 弹出文件下载 原理 代码

  1. /** 
  2.  * @author      default7<default7@zbphp.com> 
  3.  * @description 演示PHP弹出下载的原理 
  4.  * 
  5.  * @param $file_name 
  6.  */  
  7. function downFile($file_name)  
  8. {  
  9.     $file_path = "/tmp/" . $file_name;  
  10.     $buffer = 102400; //一次返回102400个字节  
  11.     if (!file_exists($file_path)) {  
  12.         echo "<script type='text/javascript'> alert('对不起!该文件不存在或已被删除!'); </script>";  
  13.   
  14.         return;  
  15.     }  
  16.     $fp = fopen($file_path, "r");  
  17.     $file_size = filesize($file_path);  
  18.     $file_data = '';  
  19.     while (!feof($fp)) {  
  20.         $file_data .= fread($fp, $buffer);  
  21.     }  
  22.     fclose($fp);  
  23.   
  24.     //Begin writing headers  
  25.     header("Pragma: public");  
  26.     header("Expires: 0");  
  27.     header("Cache-Control: must-revalidate, post-check=0, pre-check=0");  
  28.     header("Cache-Control: public");  
  29.     header("Content-Description: File Transfer");  
  30.     header("Content-type:application/octet-stream;");  
  31.     header("Accept-Ranges:bytes");  
  32.     header("Accept-Length:{$file_size}");  
  33.     header("Content-Disposition:attachment; filename={$file_name}");  
  34.     header("Content-Transfer-Encoding: binary");  
  35.     echo $file_data;  
原文地址:https://www.cnblogs.com/caicaizi/p/4997152.html