What are the best practices for implementing byte-range requests in PHP for streaming video?
When streaming video in PHP, implementing byte-range requests allows for the efficient delivery of video content by serving only the requested portions of the file. This can help reduce bandwidth usage and improve playback performance for users. To implement byte-range requests in PHP, you can check for the "Range" header in the incoming request, parse the requested byte range, and then use fseek() and fread() functions to read and output the requested portion of the video file.
$file = 'path/to/video.mp4';
$fp = fopen($file, 'rb');
$start = 0;
$end = filesize($file) - 1;
if (isset($_SERVER['HTTP_RANGE'])) {
$range = $_SERVER['HTTP_RANGE'];
$range = str_replace('bytes=', '', $range);
list($start, $end) = explode('-', $range);
$start = max(0, (int)$start);
$end = min(filesize($file) - 1, (int)$end);
header('HTTP/1.1 206 Partial Content');
header('Content-Range: bytes ' . $start . '-' . $end . '/' . filesize($file));
} else {
header('HTTP/1.1 200 OK');
}
header('Content-Length: ' . ($end - $start + 1));
header('Content-Type: video/mp4');
fseek($fp, $start);
while (!feof($fp) && ($p = ftell($fp)) <= $end) {
echo fread($fp, min(8192, $end - $p + 1));
}
fclose($fp);