php支持断点续传、分块下载的类


Posted in PHP onMay 02, 2016

本文是为大家分享php支持断点续传、分块下载的类,供大家参考,具体内容如下

<?php
 
/**
 * User: djunny
 * Date: 2016-04-29
 * Time: 17:18
 * Mail: 199962760@qq.com
 * 支持断点下载的类
 */
class downloader {
 
  /**
   * download file to local path
   *
   * @param    $url
   * @param    $save_file
   * @param int  $speed
   * @param array $headers
   * @param int  $timeout
   * @return bool
   * @throws Exception
   */
  static function get($url, $save_file, $speed = 10240, $headers = array(), $timeout = 10) {
    $url_info = self::parse_url($url);
    if (!$url_info['host']) {
      throw new Exception('Url is Invalid');
    }
 
    // default header
    $def_headers = array(
      'Accept'     => '*/*',
      'User-Agent'   => 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)',
      'Accept-Encoding' => 'gzip, deflate',
      'Host'      => $url_info['host'],
      'Connection'   => 'Close',
      'Accept-Language' => 'zh-cn',
    );
 
    // merge heade
    $headers = array_merge($def_headers, $headers);
    // get content length
    $content_length = self::get_content_size($url_info['host'], $url_info['port'], $url_info['request'], $headers, $timeout);
 
    // content length not exist
    if (!$content_length) {
      throw new Exception('Content-Length is Not Exists');
    }
    // get exists length
    $exists_length = is_file($save_file) ? filesize($save_file) : 0;
    // get tmp data file
    $data_file = $save_file . '.data';
    // get tmp data
    $exists_data = is_file($data_file) ? json_decode(file_get_contents($data_file), 1) : array();
    // check file is valid
    if ($exists_length == $content_length) {
      $exists_data && @unlink($data_file);
      return true;
    }
    // check file is expire
    if ($exists_data['length'] != $content_length || $exists_length > $content_length) {
      $exists_data = array(
        'length' => $content_length,
      );
    }
    // write exists data
    file_put_contents($data_file, json_encode($exists_data));
 
    try {
      $download_status = self::download_content($url_info['host'], $url_info['port'], $url_info['request'], $save_file, $content_length, $exists_length, $speed, $headers, $timeout);
      if ($download_status) {
        @unlink($data_file);
      }
    } catch (Exception $e) {
      throw new Exception($e->getMessage());
    }
    return true;
  }
 
  /**
   * parse url
   *
   * @param $url
   * @return bool|mixed
   */
  static function parse_url($url) {
    $url_info = parse_url($url);
    if (!$url_info['host']) {
      return false;
    }
    $url_info['port']  = $url_info['port'] ? $url_info['host'] : 80;
    $url_info['request'] = $url_info['path'] . ($url_info['query'] ? '?' . $url_info['query'] : '');
    return $url_info;
  }
 
  /**
   * download content by chunk
   *
   * @param $host
   * @param $port
   * @param $url_path
   * @param $headers
   * @param $timeout
   */
  static function download_content($host, $port, $url_path, $save_file, $content_length, $range_start, $speed, &$headers, $timeout) {
    $request = self::build_header('GET', $url_path, $headers, $range_start);
    $fsocket = @fsockopen($host, $port, $errno, $errstr, $timeout);
    stream_set_blocking($fsocket, TRUE);
    stream_set_timeout($fsocket, $timeout);
    fwrite($fsocket, $request);
    $status = stream_get_meta_data($fsocket);
    if ($status['timed_out']) {
      throw new Exception('Socket Connect Timeout');
    }
    $is_header_end = 0;
    $total_size  = $range_start;
    $file_fp    = fopen($save_file, 'a+');
    while (!feof($fsocket)) {
      if (!$is_header_end) {
        $line = @fgets($fsocket);
        if (in_array($line, array("\n", "\r\n"))) {
          $is_header_end = 1;
        }
        continue;
      }
      $resp    = fread($fsocket, $speed);
      $read_length = strlen($resp);
      if ($resp === false || $content_length < $total_size + $read_length) {
        fclose($fsocket);
        fclose($file_fp);
        throw new Exception('Socket I/O Error Or File Was Changed');
      }
      $total_size += $read_length;
      fputs($file_fp, $resp);
      // check file end
      if ($content_length == $total_size) {
        break;
      }
      sleep(1);
      // for test
      //break;
    }
    fclose($fsocket);
    fclose($file_fp);
    return true;
 
  }
 
  /**
   * get content length
   *
   * @param $host
   * @param $port
   * @param $url_path
   * @param $headers
   * @param $timeout
   * @return int
   */
  static function get_content_size($host, $port, $url_path, &$headers, $timeout) {
    $request = self::build_header('HEAD', $url_path, $headers);
    $fsocket = @fsockopen($host, $port, $errno, $errstr, $timeout);
    stream_set_blocking($fsocket, TRUE);
    stream_set_timeout($fsocket, $timeout);
    fwrite($fsocket, $request);
    $status = stream_get_meta_data($fsocket);
    $length = 0;
    if ($status['timed_out']) {
      return 0;
    }
    while (!feof($fsocket)) {
      $line = @fgets($fsocket);
      if (in_array($line, array("\n", "\r\n"))) {
        break;
      }
      $line = strtolower($line);
      // get location
      if (substr($line, 0, 9) == 'location:') {
        $location = trim(substr($line, 9));
        $url_info = self::parse_url($location);
        if (!$url_info['host']) {
          return 0;
        }
        fclose($fsocket);
        return self::get_content_size($url_info['host'], $url_info['port'], $url_info['request'], $headers, $timeout);
      }
      // get content length
      if (strpos($line, 'content-length:') !== false) {
        list(, $length) = explode('content-length:', $line);
        $length = (int)trim($length);
      }
    }
    fclose($fsocket);
    return $length;
 
  }
 
  /**
   * build header for socket
   *
   * @param   $action
   * @param   $url_path
   * @param   $headers
   * @param int $range_start
   * @return string
   */
  static function build_header($action, $url_path, &$headers, $range_start = -1) {
    $out = $action . " {$url_path} HTTP/1.0\r\n";
    foreach ($headers as $hkey => $hval) {
      $out .= $hkey . ': ' . $hval . "\r\n";
    }
    if ($range_start > -1) {
      $out .= "Accept-Ranges: bytes\r\n";
      $out .= "Range: bytes={$range_start}-\r\n";
    }
    $out .= "\r\n";
 
    return $out;
  }
}
 
 
#use age
/*
try {
  if (downloader::get('http://dzs.aqtxt.com/files/11/23636/201604230358308081.rar', 'test.rar')) {
    //todo
    echo 'Download Succ';
  }
} catch (Exception $e) {
  echo 'Download Failed';
}
*/
?>

以上就是本文的全部内容,希望对大家的学习有所帮助。

PHP 相关文章推荐
php下清空字符串中的HTML标签的代码
Sep 06 PHP
PHP人民币金额数字转中文大写的函数代码
Feb 27 PHP
PHP数据过滤的方法
Oct 30 PHP
PHP调用VC编写的COM组件实例
Mar 29 PHP
php中HTTP_REFERER函数用法实例
Nov 21 PHP
php中file_exists函数使用详解
May 08 PHP
从刷票了解获得客户端IP的方法
Sep 21 PHP
Yii隐藏URL中index.php的方法
Jul 12 PHP
[原创]php token使用与验证示例【测试可用】
Aug 30 PHP
php如何利用pecl安装mongodb扩展详解
Jan 09 PHP
PHP实现微信小程序用户授权的工具类示例
Mar 05 PHP
laravel 框架结合关联查询 when()用法分析
Nov 22 PHP
php数组分页实现方法
Apr 30 #PHP
thinkPHP使用pclzip打包备份mysql数据库的方法
Apr 30 #PHP
php打包压缩文件之ZipArchive方法用法分析
Apr 30 #PHP
php使用pclzip类实现文件压缩的方法(附pclzip类下载地址)
Apr 30 #PHP
php简单实现数组分页的方法
Apr 30 #PHP
php简单创建zip压缩文件的方法
Apr 30 #PHP
Yii2 rbac权限控制操作步骤实例教程
Apr 29 #PHP
You might like
二招解决php乱码问题
2012/03/25 PHP
PHP使用CURL获取302跳转后的地址实例
2014/05/04 PHP
php中error与exception的区别及应用
2014/07/28 PHP
PHP+FastCGI+Nginx配置PHP运行环境
2014/08/07 PHP
php的GD库imagettftext函数解决中文乱码问题
2015/01/24 PHP
PHP实现APP微信支付的实例讲解
2018/02/10 PHP
Laravel框架使用Seeder实现自动填充数据功能
2018/06/13 PHP
javascript 新浪背投广告实现代码
2009/07/07 Javascript
jQuery与其它库冲突的解决方法
2010/06/25 Javascript
javascript学习笔记(五)正则表达式
2011/04/08 Javascript
Jquery Change与bind事件代码
2011/09/29 Javascript
通过jQuery源码学习javascript(一)
2012/12/27 Javascript
jQuery中before()方法用法实例
2014/12/25 Javascript
javascript中的Function.prototye.bind
2015/06/25 Javascript
jQuery hover事件简单实现同时绑定2个方法
2016/06/07 Javascript
vue+vux实现移动端文件上传样式
2017/07/28 Javascript
如何编写一个d.ts文件的步骤详解
2018/04/13 Javascript
脚手架vue-cli工程webpack的作用和特点
2018/09/29 Javascript
JS实现点餐自动选择框(案例分析)
2019/12/10 Javascript
jquery实现弹窗(系统提示框)效果
2019/12/10 jQuery
JS替换字符串中指定位置的字符(多种方法)
2020/05/28 Javascript
js+canvas实现刮刮奖功能
2020/09/13 Javascript
python中set常用操作汇总
2016/06/30 Python
对pandas的dataframe绘图并保存的实现方法
2017/08/05 Python
Python图形绘制操作之正弦曲线实现方法分析
2017/12/25 Python
pandas数据预处理之dataframe的groupby操作方法
2018/04/13 Python
python批量修改文件编码格式的方法
2018/05/31 Python
python多线程分块读取文件
2019/08/29 Python
在Django中预防CSRF攻击的操作
2020/03/13 Python
茵宝(Umbro)英国官方商店:英国足球服装生产商
2016/12/29 全球购物
6PM官网:折扣鞋、服装及配饰
2018/08/03 全球购物
离婚协议书标准格式
2014/10/04 职场文书
贷款收入证明格式
2015/06/24 职场文书
教师节晚会主持词
2015/06/30 职场文书
golang操作rocketmq的示例代码
2022/04/06 Golang
win11电脑关机鼠标灯还亮怎么解决? win11关机后鼠标灯还亮解决方法
2023/01/09 数码科技