首页  编辑  

PHP中,解决html5 video mp4文件无法在Safari中播放的问题

Tags: /PHP/   Date Created:
参考资料: https://www.jianshu.com/p/fecdec504ab0?from=singlemessage
默认情况下, ThinkPHP downloa助手函数不支持Range header,而Safari会对video中的文件首先请求一次range:0-1,如果服务器端不支持,那么就无法播放了。
解决方法如下:
public function file($url) {
	if (!session('user')) {
		$this->ajaxReturn(["auth" => "timeout"]);
	}
	$file = \think\facade\Filesystem::path($url);
	if(!isset($_SERVER['HTTP_RANGE'])) return download($file);

	$ext = pathinfo($file, PATHINFO_EXTENSION);
	$total = filesize($file);
	$range = str_replace('=','-',$_SERVER['HTTP_RANGE']);
	$range = explode('-',$range);
	if (isset($range[2]) && intval($range[2]) >0){
		$end = trim($range[2]);
	}else{
		$end = $total-1;
	}
	$start = trim($range[1]);
	$size = $end-$start+1;
	header('Content-Length:'.$size);
	header('Content-Range: bytes '.$start.'-'.$end.'/'.$total);
	header('Accenpt-Ranges: bytes');
	if (strtolower($ext) == "mp4") header('Content-Type: video/mp4');

	$fp = fopen($file,'rb+');
	fseek($fp,$start);
	while(!feof($fp)) {
		print(fread($fp,$size));
		flush();
		ob_flush();
	}
	fclose($fp);
}