使用PHP强制下载PDF文件(代码家园)

我们有时会遇到这样一种情况,当需要下载一个PDF文件时,如果不经处理会直接在浏览器里打开PDF文件,然后再需要通过另存为才能保存下载文件。本文将通过PHP来实现直接下载PDF文件。

实现原理:我们仅仅只需要修改页面HTTP头,把Content-Type设置为force-download,问题即可解决。(更多PHP教程请访问代码家园)请看代码:

  1. forceDownload("pdfdemo.pdf"); 
  2. function forceDownload($filename) { 
  3.  
  4.     if (false == file_exists($filename)) { 
  5.         return false; 
  6.     } 
  7.      
  8.     // http headers 
  9.     header('Content-Type: application-x/force-download'); 
  10.     header('Content-Disposition: attachment; filename="' . basename($filename) .'"'); 
  11.     header('Content-length: ' . filesize($filename)); 
  12.  
  13.     // for IE6 
  14.     if (false === strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6')) { 
  15.         header('Cache-Control: no-cache, must-revalidate'); 
  16.     } 
  17.     header('Pragma: no-cache'); 
  18.          
  19.     // read file content and output 
  20.     return readfile($filename);; 

为了方便,我写了一个函数forceDownload(),然后通过调用该函数即可。

转载请注明:代码家园 » 使用PHP强制下载PDF文件 
本文原地址:http://www.daimajiayuan.com/sitejs-17816-1.html

posted @ 2013-12-05 17:02  似水星辰  阅读(944)  评论(0编辑  收藏  举报