我使用的代码从服务器(受保护的文件)获取文件并在用户上下载或查看。我在使Firefox和IE从该URL播放HTML5视频时遇到了问题。此代码仅适用于Chrome。我知道它有点乱,但没有时间让它看起来更好。
ob_clean();
@ini_set('error_reporting', E_ALL & ~ E_NOTICE);
@apache_setenv('no-gzip', 1);
@ini_set('zlib.output_compression', 'Off');
$file = $_GET["file"];
$finfo = new finfo(FILEINFO_MIME);
$mime = $finfo->file($file);
$size = filesize($file);
header('Content-Type: '.$mime);
if(isset($_SERVER['HTTP_RANGE'])){
$ranges = array_map('intval',explode('-', substr($_SERVER['HTTP_RANGE'], 6)));
if(!$ranges[1]){
$ranges[1] = $size - 1;
}
if($ranges[0]>0||$ranges[1]<$size)
header('HTTP/1.0 206 Partial Content');
else
header('HTTP/1.0 200 OK');
header('Accept-Ranges: bytes');
header('Content-Length: ' . ($ranges[1] - $ranges[0]));
header("Content-Disposition: inline;");
header(sprintf('Content-Range: bytes %d-%d/%d',$ranges[0],$ranges[1],$size));
header("Content-Transfer-Encoding: binary\n");
header('Connection: close');
$f = fopen($file, 'rb');
$chunkSize = 8192;
fseek($f, $ranges[0]);
while(true){
if(ftell($f) >= $ranges[1]){
break;
}
echo fread($f, $chunkSize);
@ob_flush();
flush();
}
}
else {
header('Content-Length: ' . $size);
@readfile($file);
@ob_flush();
flush();
}
这个不适用于Chrome,但适用于Firefox和IE。
$path = $_GET["file"];
$size=filesize($path);
$fm=@fopen($path,'rb');
if(!$fm) {
header ("HTTP/1.0 404 Not Found");
die();
}
$begin=0;
$end=$size;
if(isset($_SERVER['HTTP_RANGE'])) {
if(preg_match('/bytes=\h*(\d+)-(\d*)[\D.*]?/i', $_SERVER['HTTP_RANGE'], $matches)) {
$begin=intval($matches[0]);
if(!empty($matches[1])) {
$end=intval($matches[1]);
}
}
}
if($begin>0||$end<$size)
header('HTTP/1.0 206 Partial Content');
else
header('HTTP/1.0 200 OK');
header("Content-Type: video/mp4");
header('Accept-Ranges: bytes');
header('Content-Length:'.($end-$begin));
header("Content-Disposition: inline;");
header("Content-Range: bytes $begin-$end/$size");
header("Content-Transfer-Encoding: binary\n");
header('Connection: close');
$cur=$begin;
fseek($fm,$begin,0);
while(!feof($fm)&&$cur<$end&&(connection_status()==0))
{ print fread($fm,min(1024*16,$end-$cur));
$cur+=1024*16;
usleep(1000);
}
die();