1 <?php
2 /*php官网用户笔记上有例子
3 网址:us1.php.net/manual/zh/function.header.php
4 I just made a function to allow a file to
5 force-download (for a script to disallow file links from untrusted sites
6 -- preventing mp3/video leeching on forums), and I realized that a
7 script like that could potentially be very dangerous.
8
9 Someone could possibly exploit the script to download sensitive files
10 from your server, like your index.php or passwords.txt -- so I made this
11 switch statement to both allow for many file types for a download
12 script, and to prevent certain types from being accessed.
13 */
14 function dl_file($file){
15
16 //First, see if the file exists
17 if (!is_file($file)) { die("<b>404 File not found!</b>"); }
18
19 //Gather relevent info about file
20 $len = filesize($file);
21 $filename = basename($file);
22 $file_extension = strtolower(substr(strrchr($filename,"."),1));
23
24 //This will set the Content-Type to the appropriate setting for the file
25 switch( $file_extension ) {
26 case "pdf": $ctype="application/pdf"; break;
27 case "exe": $ctype="application/octet-stream"; break;
28 case "zip": $ctype="application/zip"; break;
29 case "doc": $ctype="application/msword"; break;
30 case "xls": $ctype="application/vnd.ms-excel"; break;
31 case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
32 case "gif": $ctype="image/gif"; break;
33 case "png": $ctype="image/png"; break;
34 case "jpeg":
35 case "jpg": $ctype="image/jpg"; break;
36 case "mp3": $ctype="audio/mpeg"; break;
37 case "wav": $ctype="audio/x-wav"; break;
38 case "mpeg":
39 case "mpg":
40 case "mpe": $ctype="video/mpeg"; break;
41 case "mov": $ctype="video/quicktime"; break;
42 case "avi": $ctype="video/x-msvideo"; break;
43
44 //The following are for extensions that shouldn't be downloaded (sensitive stuff, like php files)
45 case "php":
46 case "htm":
47 case "html":
48 case "txt": die("<b>Cannot be used for ". $file_extension ." files!</b>"); break;
49
50 default: $ctype="application/force-download";
51 }
52
53 //Begin writing headers
54 header("Pragma: public");
55 header("Expires: 0");
56 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
57 header("Cache-Control: public");
58 header("Content-Description: File Transfer");
59
60 //Use the switch-generated Content-Type
61 header("Content-Type: $ctype");
62
63 //Force the download
64 $header="Content-Disposition: attachment; filename=".$filename.";";
65 header($header );
66 header("Content-Transfer-Encoding: binary");
67 header("Content-Length: ".$len);
68 @readfile($file);
69 exit;
70 }
71 //This works in both IE and Firefox.
72 ?>