使用PHP读取mp4文件 [英] Reading mp4 files with PHP
问题描述
我正在尝试使用PHP读取mp4文件,而我现在正在做的是:
I'm trying to read mp4 file with PHP and what I'm doing now is this:
<?php
header("Content-Length: filesize");
readfile('file.mp4');
?>
但是通过这种方式,我无法跳过甚至返回,直到未100%加载视频.当然,当我直接从文件(video.mp4)中读取内容时,一切都会顺利进行.
but this way I can't skip or even go back until the video is not loaded 100%. Of course when I read directly from the file (video.mp4) everything goes well.
谢谢.
推荐答案
您需要自己在PHP中实现跳过功能.这是一个代码段.
You need to implement the skipping functionality yourself in PHP. This is a code snippet that will do that.
<?php
$path = 'file.mp4';
$size=filesize($path);
$fm=@fopen($path,'rb');
if(!$fm) {
// You can also redirect here
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();
更多性能
请注意,这不是最有效的方法,因为整个文件都需要通过PHP进行处理,因此您只需要尝试如何使用即可.
Note that this is not the most efficient way to do it, because the whole file needs to go through PHP, so you will just need to try how it goes for you.
假设您要执行此操作的原因是限制访问,并且以后需要提高效率,则可以为Web服务器使用标志.
Assuming the reason you want to do this is to restrict access, and you need more efficiency later, you can use a flag for the web server.
具有X-Sendfile模块或轻巧的Apache(此处的nginx信息)
Apache with X-Sendfile module or lightty (nginx info here)
$path = 'file.mp4';
header("X-Sendfile: $path");
die();
这有点高级,您只应在需要时使用它,但是当您开始使用一些简单但性能中等的产品时,很高兴得知您具有升级选项.
This is a bit more advanced and you should only use it if you need it, but it is relaxing to know you have an upgrade option when you start out with something that is rather easy but has mediocre performance.
这篇关于使用PHP读取mp4文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!