0

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.

Tseko
  • 1
  • 2
  • 1
    header("Content-Range: bytes " . (($start-$end)/$filesize)); I think You should write this like that for proper size calc, or make new variable and check also if it is no 0. Check also $filesize is it correct value. – Grzegorz Miśkiewicz Dec 21 '18 at 14:18
  • 1
    Check also this post: https://stackoverflow.com/questions/23521839/failed-to-load-resource-neterr-content-length-mismatch – Grzegorz Miśkiewicz Dec 21 '18 at 14:19
  • Unfortunately it's not working i get the same error again and the video also breaks to load. And I'm sure there is no misconfiguration in the server. – Tseko Dec 21 '18 at 15:21
  • Check this ready to use class for what u want to do :-) https://codesamplez.com/programming/php-html5-video-streaming-tutorial – Grzegorz Miśkiewicz Dec 21 '18 at 15:26
  • be also sure to give song.mp4 relative path - ex. __DIR__ . '/song.mp4 if it in same directory as Your php file. – Grzegorz Miśkiewicz Dec 21 '18 at 15:27
  • I have seen this class before but wanted to create something myself. Really don't know why streaming is so hard to be done. Furthermore wanted to fix my own script because i have made other scripts for streaming but with the same unwanted behavior. – Tseko Dec 21 '18 at 17:24
  • I understand, but if it works on this class, write it as a lesson again and find what u do wrong. – Grzegorz Miśkiewicz Dec 21 '18 at 17:36

0 Answers0