两个PHP 断点续传 HTTP[未测试]

 1   /**
 2   * PHP-HTTP断点续传实现
 3   * @param string $path: 文件所在路径
 4   * @param string $file: 文件名
 5   * @return void
 6   */
 7   function download($path,$file) {
 8       $real = $path.'/'.$file;
 9       if(!file_exists($real)) {
10               return false;
11       }
12       $size = filesize($real);
13       $size2 = $size-1;
14       $range = 0;
15       if(isset($_SERVER['HTTP_RANGE'])) {
16           header('HTTP /1.1 206 Partial Content');
17           $range = str_replace('=','-',$_SERVER['HTTP_RANGE']);
18           $range = explode('-',$range);
19           $range = trim($range[1]);
20           header('Content-Length:'.$size);
21           header('Content-Range: bytes '.$range.'-'.$size2.'/'.$size);
22         } else {
23           header('Content-Length:'.$size);
24           header('Content-Range: bytes 0-'.$size2.'/'.$size);
25         }
26       header('Accenpt-Ranges: bytes');
27       header('application/octet-stream');
28       header("Cache-control: public");
29       header("Pragma: public");
30       //解决在IE中下载时中文乱码问题
31       $ua = $_SERVER['HTTP_USER_AGENT'];
32       if(preg_match('/MSIE/',$ua)) {
33           $ie_filename = str_replace('+','%20',urlencode($file));
34           header('Content-Dispositon:attachment; filename='.$ie_filename);
35       } else {
36               header('Content-Dispositon:attachment; filename='.$file);
37       }
38       $fp = fopen($real,'rb+');
39       fseek($fp,$range);
40         while(!feof($fp)) {
41           set_time_limit(0);
42           print(fread($fp,1024));
43           flush();
44           ob_flush();
45       }
46       fclose($fp);
47   }
48   /*End of PHP*/
 1 $fname = './MMLDZG.mp3';  
 2 $fp = fopen($fname,'rb');  
 3 $fsize = filesize($fname);  
 4 if (isset($_SERVER['HTTP_RANGE']) && ($_SERVER['HTTP_RANGE'] != "") && preg_match("/^bytes=([0-9]+)-$/i", $_SERVER['HTTP_RANGE'], $match) && ($match[1] < $fsize)) {
 5     $start = $match[1]; 
 6 } else {
 7     $start = 0; 
 8 } 
 9 @header("Cache-control: public"); @header("Pragma: public"); 
10 if ($star--> 0) {  
11     fseek($fp, $start);  
12     Header("HTTP/1.1 206 Partial Content");  
13     Header("Content-Length: " . ($fsize - $start));  
14     Header("Content-Ranges: bytes" . $start . "-" . ($fsize - 1) . "/" . $fsize);  
15 } else {  
16     header("Content-Length: $fsize");  
17     Header("Accept-Ranges: bytes");  
18 }  
19 @header("Content-Type: application/octet-stream");  
20 @header("Content-Disposition: attachment;filename=mmdld.mp3");  
21 fpassthru($fp);  

fpassthru() 函数输出文件指针处的所有剩余数据。

该函数将给定的文件指针从当前的位置读取到 EOF,并把结果写到输出缓冲区。

posted @ 2012-05-11 15:00  [九狐科技]keheng  阅读(428)  评论(0编辑  收藏  举报