当前位置: 亚洲城ca88 > ca88 > 正文

PHP实现HTTP断点续传的章程ca88,php辅助断点续传

时间:2019-07-04 23:03来源:ca88
废话没有多少说,直接上代码 正文实例汇报了PHP完毕HTTP断点续传的办法。共享给我们供我们参谋。具体落到实处方式如下: 正文是为大家分享php帮忙断点续传、分块下载的类,供大家

废话没有多少说,直接上代码

正文实例汇报了PHP完毕HTTP断点续传的办法。共享给我们供我们参谋。具体落到实处方式如下:

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

<?php
  // 暂不支持断点续传
  // $url = 'http://www.mytest.com/debian.iso'; 不知道为何获取本地文件大小为0
  $url = 'http://192.168.8.93/download/vm-672/18/0.vmdk';
  $file = basename($url);
  $header = get_headers($url, 1);
  $size = $header['Content-Length'];

  $fp = fopen($url, 'rb');
  if ($fp === false) exit('文件不存在或打开失败');

  header('Content-Description: File Transfer');
  header('Content-Type: application/octet-stream');
  header('Content-Disposition: attachment; filename="'.$file.'"');
  header('Content-Transfer-Encoding: binary');
  header('Expires: 0');
  header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  header('Pragma: public');
  header('Content-Length: ' . $size);

  ob_clean();
  ob_end_flush();
  set_time_limit(0);

  $chunkSize = 1024 * 1024;
  while (!feof($fp)) {
    $buffer = fread($fp, $chunkSize);
    echo $buffer;
    ob_flush();
    flush();
  }
  fclose($fp);
  exit;
<?php
/**
 * PHP-HTTP断点续传实现
 * @param string $path: 文件所在路径
 * @param string $file: 文件名
 * @return void
 */
function download($path,$file) {
  $real = $path.'/'.$file;
  if(!file_exists($real)) {
    return false;
  }
  $size = filesize($real);
  $size2 = $size-1;
  $range = 0;
  if(isset($_SERVER['HTTP_RANGE'])) {
    header('HTTP /1.1 206 Partial Content');
    $range = str_replace('=','-',$_SERVER['HTTP_RANGE']);
    $range = explode('-',$range);
    $range = trim($range[1]);
    header('Content-Length:'.$size);
    header('Content-Range: bytes '.$range.'-'.$size2.'/'.$size);
  } else {
    header('Content-Length:'.$size);
    header('Content-Range: bytes 0-'.$size2.'/'.$size);
  }
  header('Accenpt-Ranges: bytes');
  header('application/octet-stream');
  header("Cache-control: public");
  header("Pragma: public");
  //解决在IE中下载时中文乱码问题
  $ua = $_SERVER['HTTP_USER_AGENT'];
  if(preg_match('/MSIE/',$ua)) {
    $ie_filename = str_replace(' ',' ',urlencode($file));
    header('Content-Dispositon:attachment; filename='.$ie_filename);
  } else {
    header('Content-Dispositon:attachment; filename='.$file);
  }
  $fp = fopen($real,'rb ');
  fseek($fp,$range);
  while(!feof($fp)) {
    set_time_limit(0);
    print(fread($fp,1024));
    flush();
    ob_flush();
  }
  fclose($fp);
}
<?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", "rn"))) {
          $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", "rn"))) {
        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.0rn";
    foreach ($headers as $hkey => $hval) {
      $out .= $hkey . ': ' . $hval . "rn";
    }
    if ($range_start > -1) {
      $out .= "Accept-Ranges: bytesrn";
      $out .= "Range: bytes={$range_start}-rn";
    }
    $out .= "rn";

    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程序设计有着支持。

如上就是本文的全体内容,希望对大家的读书抱有帮衬。

您只怕感兴趣的稿子:

  • 浅谈php fopen下载远程文件的函数
  • 从品质方面思索PHP下载远程文件的3种方法
  • PHP下载远程文件到地方存款和储蓄的章程
  • php带密码效率并下载远程文件保留本地钦点目录 修改抓牢版
  • php下载远程文件类(援助断点续传)
  • PHP完毕的文件操作类及文件下载功效示例
  • php达成的支持断点续传的文件下载类
  • PHP文件下载类
  • 化解PHP超大文件下载,断点续传下载的办法详解
  • PHP达成的下载远程文件类定义与用法示例

你或者感兴趣的篇章:

  • php断点续传之怎样分割合併文件
  • 缓和PHP超大文件下载,断点续传下载的办法详解
  • php达成的扶助断点续传的文本下载类
  • php下载远程文件类(帮忙断点续传)
  • php断点续传之文件分割合併详解
  • 至于php援助分块与断点续传文件下载作用代码
  • php resumablejs完成的分块上传 断点续传作用示例
  • php扶助断点续传、分块下载的类
  • PHP轻松实现断点续传下载的不二等秘书技
  • PHP达成断点续传乱序合併文件的方法

你或者感兴趣的文章:

  • php断点续传之如何分割合併文件
  • 缓和PHP超大文件下载,断点续传下载的艺术详解
  • ca88,php落成的支撑断点续传的公文下载类
  • php下载远程文件类(匡助断点续传)
  • PHP实现HTTP断点续传的秘籍
  • php断点续传之文件分割合併详解
  • 至于php帮忙分块与断点续传文件下载功用代码
  • php resumablejs完结的分块上传 断点续传作用示例
  • PHP简单达成断点续传下载的主意
  • PHP完成断点续传乱序合併文件的措施

编辑:ca88 本文来源:PHP实现HTTP断点续传的章程ca88,php辅助断点续传

关键词: 亚洲城ca88