在网上无意中看到这样一个例子,就是用PHP来限制文件下载速度,其基本理念是一次发送一段数据,再sleep一段时间,通常是一秒,然后在发送. 例子挺全面,开加入了对文件名的检查,加强了安全方面的考量,值得收藏.
1. 404 File not found!");
7. }
8. //Gather relevent info about file
9. $filename = basename($file);
10. $file_extension = strtolower(substr(strrchr($filename,"."),1));
11. // This will set the Content-Type to the appropriate setting for the file
12. switch( $file_extension ) {
13. case "exe":
14. $ctype="application/octet-stream";
15. break;
16. case "zip":
17. $ctype="application/zip";
18. break;
19. case "mp3":
20. $ctype="audio/mpeg";
21. break;
22. case "mpg":
23. $ctype="video/mpeg";
24. break;
25. case "avi":
26. $ctype="video/x-msvideo";
27. break;
28.
29. // The following are for extensions that shouldn't be downloaded
30. // (sensitive stuff, like php files)
31. case "php":
32. case "htm":
33. case "html":
34. case "txt":
35. die("Cannot be used for ". $file_extension ." files!");
36. break;
37. default:
38. $ctype="application/force-download";
39. }
40.
41. // Begin writing headers
42. header("Cache-Control:");
43. header("Cache-Control: public");
44. header("Content-Type: $ctype");
45.
46. $filespaces = str_replace("_", " ", $filename);
47. // if your filename contains underscores, replace them with spaces
48.
49. $header='Content-Disposition: attachment; filename='.$filespaces;
50. header($header);
51. header("Accept-Ranges: bytes");
52.
53. $size = filesize($file);
54. // check if http_range is sent by browser (or download manager)
55. if(isset($_SERVER['HTTP_RANGE'])) {
56. // if yes, download missing part
57.
58. $seek_range = substr($_SERVER['HTTP_RANGE'] , 6);
59. $range = explode( '-', $seek_range);
60. if($range[0] > 0) { $seek_start = intval($range[0]); }
61. if($range[1] > 0) { $seek_end = intval($range[1]); }
62.
63. header("HTTP/1.1 206 Partial Content");
64. header("Content-Length: " . ($seek_end - $seek_start + 1));
65. header("Content-Range: bytes $seek_start-$seek_end/$size");
66. } else {
67. header("Content-Range: bytes 0-$seek_end/$size");
68. header("Content-Length: $size");
69. }
70. //open the file
71. $fp = fopen("$file","rb");
72.
73. //seek to start of missing part
74. fseek($fp,$seek_start);
75.
76. //start buffered download
77. while(!feof($fp)) {
78. //reset time limit for big files
79. set_time_limit(0);
80. print(fread($fp,1024*$speed));
81. flush();
82. sleep(1);
83. }
84. fclose($fp);
85. exit;
86. }
87. ?>