What factors should be considered when serving large video files from a web server in PHP?
When serving large video files from a web server in PHP, factors to consider include server bandwidth, file size, server load, and user experience. To optimize performance, it is recommended to use streaming techniques, such as byte-range requests, to allow users to start playing the video before it is fully downloaded.
<?php
$videoFilePath = '/path/to/video.mp4';
if (file_exists($videoFilePath)) {
$fileSize = filesize($videoFilePath);
$handle = fopen($videoFilePath, 'rb');
header('Content-Type: video/mp4');
header('Content-Length: ' . $fileSize);
header('Accept-Ranges: bytes');
if (isset($_SERVER['HTTP_RANGE'])) {
$range = $_SERVER['HTTP_RANGE'];
$range = str_replace('bytes=', '', $range);
$range = explode('-', $range);
$start = intval($range[0]);
$end = $fileSize - 1;
header('HTTP/1.1 206 Partial Content');
header('Content-Range: bytes ' . $start . '-' . $end . '/' . $fileSize);
fseek($handle, $start);
} else {
$start = 0;
$end = $fileSize - 1;
}
header('Content-Length: ' . ($end - $start + 1));
while (!feof($handle) && connection_status() == 0) {
echo fread($handle, 8192);
ob_flush();
flush();
}
fclose($handle);
} else {
http_response_code(404);
echo 'File not found.';
}
?>
Keywords
Related Questions
- How can one safely disable the Safe Mode in PHP.ini on a root server without causing other issues?
- How can the issue of recognizing different result orders (e.g., 1:4 and 4:1) as the same result be addressed in a PHP query?
- What are some best practices for optimizing PHP code to handle large datasets, such as 10,000 records?