PHP强制下载文件

header() 函数向客户端发送原始的 HTTP 报头。进入指定页面后就弹出文件下载对话框,如图

PHP强制下载文件

代码如下:

  1. function download_file($archivo$downloadfilename = null) {  
  2.    
  3.     if (file_exists($archivo)) {  
  4.         $downloadfilename = $downloadfilename !== null ? $downloadfilename : basename($archivo);  
  5.         header('Content-Description: File Transfer');  
  6.         header('Content-Type: application/octet-stream');  
  7.         header('Content-Disposition: attachment; filename=' . $downloadfilename);  
  8.         header('Content-Transfer-Encoding: binary');  
  9.         header('Expires: 0');  
  10.         header('Cache-Control: must-revalidate, post-check=0, pre-check=0');  
  11.         header('Pragma: public');  
  12.         header('Content-Length: ' . filesize($archivo));  
  13.    
  14.         ob_clean();  
  15.         flush();  
  16.         readfile($archivo);  
  17.         exit;  
  18.     }  
  19.