What are the best practices for handling image caching and serving in PHP to optimize performance for a dynamic image source like an IP camera?

To optimize performance for a dynamic image source like an IP camera in PHP, it is essential to implement image caching and serving. This involves storing the image locally after the initial request and serving it from the cache for subsequent requests. By caching the image, you can reduce the load on the camera and improve the overall performance of your application.

<?php
// Set the URL of the IP camera
$camera_url = "http://example.com/ip_camera";

// Set the path to store cached images
$cache_path = "cache/";

// Check if the cached image exists
$cached_image = $cache_path . basename($camera_url);
if (!file_exists($cached_image)) {
    // If the cached image doesn't exist, fetch it from the camera and save it
    $image_data = file_get_contents($camera_url);
    file_put_contents($cached_image, $image_data);
}

// Serve the cached image
header('Content-Type: image/jpeg');
readfile($cached_image);
?>