How can PHP be used to enable seeking functionality in streamed videos for better user experience?
To enable seeking functionality in streamed videos for a better user experience, PHP can be used to handle the logic of fetching the video segments based on the user's seek request. By dynamically generating the video source URLs with the appropriate byte range headers, PHP can allow users to seek to specific points in the video without having to wait for the entire video to load again.
<?php
$videoPath = 'path/to/video.mp4';
$range = isset($_SERVER['HTTP_RANGE']) ? $_SERVER['HTTP_RANGE'] : '';
$fp = fopen($videoPath, 'rb');
$size = filesize($videoPath);
list($start, $end) = explode('-', str_replace('bytes=', '', $range));
if (empty($end)) {
$end = $size - 1;
}
header('Content-Type: video/mp4');
header('Content-Length: ' . ($end - $start + 1));
header('Content-Range: bytes ' . $start . '-' . $end . '/' . $size);
header('Accept-Ranges: bytes');
fseek($fp, $start);
while (!feof($fp) && ($p = ftell($fp)) <= $end) {
if ($p + 8192 > $end) {
$length = $end - $p + 1;
} else {
$length = 8192;
}
echo fread($fp, $length);
ob_flush();
flush();
}
fclose($fp);
?>
Related Questions
- What are the potential benefits and drawbacks of dynamically unpacking zip files in PHP for displaying images?
- What best practices can be followed to ensure seamless access to variables in included PHP files?
- How can PHP scripts securely store and authenticate user passwords, especially when integrating with systems like phpBB3?