本节内容:
php实现大文件的下载,且支持断点续传。
例子:
<?php
//下载文件,调用示例
download($url,$file_name);
function download($url, $filename) {
// 获得文件大小, 防止超过2G的文件, 用sprintf来读
//print "文件地址:".$url."<br>";
//print "文件大小:".filesize ($url)."<br>";
$filesize = sprintf ( "%u", getFileSize ( $url ) );
//print $filesize;
if (! $filesize) {
//print "找不到文件!";
//return;
}
header ( "Content-type:application/octet-streamn" ); //application/octet-stream
header ( "Content-type:unknown/unknown;" );
header ( "Content-disposition: attachment; filename="" . $filename . """ );
header ( 'Content-transfer-encoding: binary' );
if ($range = getenv ( 'HTTP_RANGE' )) { // 当有偏移量的时候,采用206的断点续传头
$range = explode ( '=', $range );
$range = $range [1];
header ( "HTTP/1.1 206 Partial Content" );
header ( "Date: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s", filemtime ( $url ) ) . " GMT" );
header ( "Accept-Ranges: bytes" );
header ( "Content-Length:" . ($filesize - $range) );
header ( "Content-Range: bytes " . $range . ($filesize - 1) . "/" . $filesize );
header ( "Connection: close" . "nn" );
} else {
header ( "Content-Length:" . $filesize . "nn" );
$range = 0;
}
loadFile ( $url );
}
function loadFile($filename, $retbytes = true) {
$buffer = '';
$cnt = 0;
$handle = fopen ( $filename, 'rb' );
if ($handle === false) {
return false;
}
while ( ! feof ( $handle ) ) {
$buffer = fread ( $handle, 1024 * 1024 );
echo $buffer;
ob_flush ();
flush ();
if ($retbytes) {
$cnt += strlen ( $buffer );
}
}
$status = fclose ( $handle );
if ($retbytes && $status) {
return $cnt; // return num. bytes delivered like readfile() does.
}
return $status;
}
//读取文件大小
function getFileSize($url){
$url = parse_url($url);
if($fp = fsockopen($url['host'],empty($url['port'])?80:$url['port'],$error)){
fputs($fp,"GET ".(empty($url['path'])?'/':$url['path'])." HTTP/1.1rn");
fputs($fp,"Host:$url[host]rnrn");
while(!feof($fp)){
$tmp = fgets($fp);
if(trim($tmp) == ''){
break;
}elseif(preg_match('/Content-Length:(.*)/si',$tmp,$arr)){
return trim($arr[1]);
}
}
return null;
}else{
return null;
}
}
>>> 延伸阅读:
解决PHP上传大文件出现错误的问题
php安全下载大文件的实现代码
php超大文件下载及断点续传下载的实现代码
php读取操作大文件的方法详解
php 上传大文件时需要做的设置
解决PHP上传大文件的问题
php设置允许大文件上传的方法
nginx php(php-fpm)上传大文件的设置