How to create a video stream from a single dynamic image in PHP



PHP Snippet 1:

$identifier = "an_identifier";

//set headers
header('Accept-Range: bytes');
header('Connection: close');
header('Content-Type: multipart/x-mixed-replace;boundary=' . $identifier);
header('Cache-Control: no-cache');

// loop to continuously serve an image
while(true) {

    $image = load_image_contents();

    echo "--" . $identifier . "\r\nContent-Type: image/jpeg\r\nContent-Length: ".strlen($image)."\r\n\r\n".$image;
    flush();
    usleep(50000);

}

PHP Snippet 2:

<img src="image.php">

PHP Snippet 3:

<html>
    <header>
    
        <script>
        
            function ReloadImage()
            {
                var image_element = document.getElementById('image_id');
                
                image_element.src = 'image.php?rand=' + Math.random();
            }

            setInterval(ReloadImage,200);
        
        </script>
        
    </header>

    <body>

        <img src="image.php" id="image_id">
        
    </body>

</html>