Skip to content

Instantly share code, notes, and snippets.

@Hiweus
Last active March 15, 2021 11:38
Show Gist options
  • Save Hiweus/c21c0d566bdb6d9e72f0b15f458b9ca4 to your computer and use it in GitHub Desktop.
Save Hiweus/c21c0d566bdb6d9e72f0b15f458b9ca4 to your computer and use it in GitHub Desktop.

This script below get a path to one video and stream using php, this is possible because the Range header field. If the browser doesn't allow this header the script only drop all video on response.

<?php
  function streamVideo($path) {
      $fileInfo = pathinfo($path);
      header("Content-Disposition: inline; filename=\"{$fileInfo['basename']}\"");
      if(!isset(getallheaders()['Range'])) {
          echo file_get_contents($path);
          exit(0);
      }

      $chunkMaxValue = 10*1024*1024; // 10MB
      $fileSize = filesize($path);
      $range = explode("=", getallheaders()['Range'])[1];

      list($start, $end) = array_map(function($item) {
          return intval($item);
      }, explode("-", $range));


      if($end === 0) {
          $end = $start+$chunkMaxValue;
          if($end > $fileSize) {
              $end = $fileSize-1;
          }
      }
      $chunkSize = ($end - $start) + 1;

      $file = fopen($path, "rb");
      fseek($file, $start);
      $chunk = fread($file, $chunkSize);
      fclose($file);


      $headers = [
          'Content-Range' => "bytes $start-$end/$fileSize",
          'Accept-Ranges' => 'bytes',
          'Content-Length' => $chunkSize,
          'Content-Type' => 'video/mp4',
      ];

      foreach($headers as $key => $value) {
          header($key.": ".$value);
      }

      http_response_code(206);
      echo $chunk;
  }
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment