What role does PHP play in optimizing video loading speed on different devices?

PHP can play a crucial role in optimizing video loading speed on different devices by dynamically serving the appropriate video format based on the user's device capabilities. By detecting the user agent and screen size, PHP can determine the optimal video format (such as MP4, WebM, or Ogg) and resolution to deliver the best viewing experience while minimizing loading times.

<?php
$userAgent = $_SERVER['HTTP_USER_AGENT'];
$screenSize = getScreenSize(); // Custom function to get screen size

if (strpos($userAgent, 'iPhone') !== false || strpos($userAgent, 'Android') !== false) {
    $videoFormat = 'mp4';
} else {
    $videoFormat = 'webm';
}

if ($screenSize > 1024) {
    $videoResolution = '1080p';
} elseif ($screenSize > 768) {
    $videoResolution = '720p';
} else {
    $videoResolution = '480p';
}

$videoPath = 'videos/video.' . $videoFormat;

echo '<video controls>';
echo '<source src="' . $videoPath . '" type="video/' . $videoFormat . '">';
echo 'Your browser does not support the video tag.';
echo '</video>';
?>