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 fread()使用技巧
Jan 22 PHP
PHP之COOKIE支持详解
Sep 20 PHP
php数组函数序列之array_slice() - 在数组中根据条件取出一段值,并返回
Nov 07 PHP
Php中文件下载功能实现超详细流程分析
Jun 13 PHP
php stream_get_meta_data返回值
Sep 29 PHP
PHP变量赋值、代入给JavaScript中的变量
Jun 29 PHP
浅谈PHP中JSON数据操作
Jul 01 PHP
PHP的运行机制与原理(底层)
Nov 16 PHP
php多线程并发实现方法
Sep 30 PHP
php将print_r处理后的数据还原为原始数组的解决方法
Nov 02 PHP
Zend Framework入门教程之Zend_Session会话操作详解
Dec 08 PHP
微信公众平台开发教程⑤ 微信扫码支付模式介绍
Apr 10 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
一个显示天气预报的程序
2006/10/09 PHP
CI框架Session.php源码分析
2014/11/03 PHP
Laravel的throttle中间件失效问题解决方法
2016/10/09 PHP
浅谈PHP中new self()和new static()的区别
2017/08/11 PHP
PHP 对象接口简单实现方法示例
2020/04/13 PHP
JQuery入门—JQuery程序的代码风格详细介绍
2013/01/03 Javascript
jQuery之ajax技术的详细介绍
2013/06/19 Javascript
jquery模拟SELECT下拉框取值效果
2013/10/23 Javascript
javascript限制用户只能输汉字中文的方法
2014/11/20 Javascript
jquery使用animate方法实现控制元素移动
2015/03/27 Javascript
javascript与Python快速排序实例对比
2015/08/10 Javascript
基于jQuery实现响应式圆形图片轮播特效
2015/11/25 Javascript
JavaScript中数据类型转换总结
2016/12/25 Javascript
JavaScript表单即时验证 验证不成功不能提交
2017/08/31 Javascript
JavaScript实现HTML5游戏断线自动重连的方法
2017/09/18 Javascript
使用vue与jquery实时监听用户输入状态的操作代码
2017/09/19 jQuery
Three.js开发实现3D地图的实践过程总结
2017/11/20 Javascript
深入理解JavaScript和TypeScript中的class
2018/04/22 Javascript
vue-cli点击实现全屏功能
2020/03/07 Javascript
JavaScript中如何调用Java方法
2020/09/16 Javascript
解决iview table组件里的 固定列 表格不自适应的问题
2020/11/13 Javascript
[23:18]Spirit vs Liquid Supermajor小组赛A组 BO3 第二场 6.2
2018/06/03 DOTA
python中的代码编码格式转换问题
2015/06/10 Python
Python for Informatics 第11章之正则表达式(四)
2016/04/21 Python
Python第三方库的安装方法总结
2016/06/06 Python
Python贪心算法实例小结
2018/04/22 Python
Python数据结构之图的应用示例
2018/05/11 Python
python 对key为时间的dict排序方法
2018/10/17 Python
python+flask编写一个简单的登录接口
2020/11/13 Python
Django url 路由匹配过程详解
2021/01/22 Python
惠普墨西哥官方商店:HP墨西哥
2016/12/01 全球购物
最新会计专业求职信范文
2014/01/28 职场文书
小班重阳节活动方案
2014/02/08 职场文书
2015年助残日活动总结
2015/03/27 职场文书
教师节祝酒词
2015/08/11 职场文书
mysql 如何获取两个集合的交集/差集/并集
2021/06/08 MySQL