How can PHP be utilized to optimize the streaming process for large media files on a website?
Large media files can be slow to load and stream on a website, causing a poor user experience. One way to optimize the streaming process is to use PHP to implement chunked streaming. This involves breaking the media file into smaller chunks and sending them progressively to the client, allowing for faster initial load times and smoother playback.
<?php
$filename = "path/to/large/media/file.mp4";
$chunkSize = 1024 * 1024; // 1MB chunk size
header("Content-Type: video/mp4");
header("Content-Length: " . filesize($filename));
$handle = fopen($filename, "rb");
while (!feof($handle)) {
echo fread($handle, $chunkSize);
ob_flush();
flush();
sleep(1); // optional delay to control streaming speed
}
fclose($handle);
?>