php下载
/** * 下载 * @date: 2021-12-09 */ public function downloads() { set_time_limit(0); $res = $_REQUEST; $root = $this->root; $root = rtrim(rtrim($root, '\\'), '/'); $path = array_key_exists('path', $res) ? $res['path'] : ''; $path = trim(trim($path, '\\'), '/'); $file = $root . $path; //检测文件是否存在 if (file_exists($file)) { $name = basename($file); $file_size = filesize($file); $ranges = $this->getRange($file_size); header("Content-type:application/octet-stream"); header("Accept-Ranges:bytes"); header('Content-Disposition: attachment; filename=' . $name); if ($ranges) { $range_start = $ranges['start']; $range_end = $ranges['end']; header('HTTP/1.1 206 Partial Content'); header(sprintf('Content-Length: %u', $range_end - $range_start)); header(sprintf('Content-Range: bytes %s-%s/%s', $range_start, $range_end, $file_size - 1)); } else { header("HTTP/1.1 200 OK"); header(sprintf('Content-Length: %s', $file_size - 1)); } $fp = fopen($file, 'rb'); // fp指针跳到断点位置 $n = empty($ranges['start']) ? 0 : $ranges['start']; fseek($fp, $n); while (!feof($fp)) { echo fread($fp, 1024); ob_flush(); flush(); } fclose($fp); } else { return '文件不存在或系统错误'; } } /** 获取header range信息 * @param int $file_size 文件大小 * @return Array */ private function getRange($file_size) { if (isset($_SERVER['HTTP_RANGE']) && !empty($_SERVER['HTTP_RANGE'])) { $range = $_SERVER['HTTP_RANGE']; $range = preg_replace('/[\s|,].*/', '', $range); $range = explode('-', substr($range, 6)); $arr = [ 'start' => (isset($range[0]) && !empty($range[0])) ? $range[0] : 0, 'end' => (isset($range[1]) && !empty($range[1]) && $range[1] != 0) ? $range[1] : $file_size - 1, ]; return $arr; } return null; }