Home > Backend Development > PHP Tutorial > php进行文件的强制下载

php进行文件的强制下载

WBOY
Release: 2016-06-23 13:35:57
Original
989 people have browsed it

浏览器下载文件,例如在浏览器中可以直接打开的文件(.gif  /.txt等)。在进行文件下载操作时,默认是通过浏览器直接打开,而不是下载保存文件。并且通过这种方法下载文件可以不暴漏下载文件所在的路径,可以在下载之前进行一系列的权限控制.如果强制浏览器下载,有二种方案,一是:把所有文件全部做成压缩文件等浏览器无法识别的格式,操作比较繁琐。二是:通过php操作header,进行强制下载。通过以下代码可以实现php强制文件下载,代码如下
Copy after login

 1 <?php 2  3 if(isset($_GET['key'])) 4 { 5     $filename = './test.png'; 6     if(file_exists($filename)) 7     { 8         header ("Content-Type: application/force-download"); 9         header ('Content-Disposition: attachment;filename="'.$filename.'"');10         readfile ($filename);11     }12 }13 14 ?>15 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"16     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">17 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">18 <head>19     <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">20     <title>Document</title>21 </head>22 <body>23     <a href="./force_download.php?key=564984w1f321fd5s6f98rf7w1re">下载png</a>24 </body>25 </html>
Copy after login

Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template