I want to stream a video file of any length. But I struggle with creating my php script for this purpose.
I created one but when i seek the video it just breaks and the video goes back from beginning. Sometimes i get net::ERR_CONTENT_LENGTH_MISMATCH error. And cant figure out how to get things done. There is my code.
<?php
$filename = "song.mp4";
$file = fopen($filename, 'rb');
$filesize = filesize($filename);
$buffer = 5 * 1024;
header("Content-Type: video/mp4");
header("Cache-Control: no-cache");
header("Accept-Ranges: bytes");
if(isset($_SERVER['HTTP_RANGE'])){
$matches = array();
preg_match("/(\d+)/i", $_SERVER['HTTP_RANGE'], $matches);
$start = (int)$matches[1];
if(isset($matches[2])){
$end = $matches[2];
}else{
$end = $filesize - 1;
}
$length = $filesize - $start + 1;
fseek($file, $start);
header("Content-Length: " . $length);
header("Content-Range: bytes $start-$end/$filesize");
}else{
header("Content-Length: " . $filesize);
}
while(!feof($file)){
$data = fread($file, $buffer);
echo $data;
flush();
}
fclose($file);
fclose($log);
exit;
?>
I expect to get the full video streamed without any problems when i seek through.