当前位置:Gxlcms > PHP教程 > PHP实现HTTP断点续传的方法_php技巧

PHP实现HTTP断点续传的方法_php技巧

时间:2021-07-01 10:21:17 帮助过:16人阅读

本文实例讲述了PHP实现HTTP断点续传的方法。分享给大家供大家参考。具体实现方法如下:

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

希望本文所述对大家的php程序设计有所帮助。

人气教程排行