php支持断点续传、分块下载的类,php支持断点续传
本文是为大家分享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把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\ \;||\xc2\xa0)/","其他字符",$str)”语句。

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

禅工作室 13.0.1
功能强大的PHP集成开发环境

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

Dreamweaver CS6
视觉化网页开发工具

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具