How can PHP be integrated with CSS to dynamically update background images on a webpage without compromising caching efficiency?

When dynamically updating background images on a webpage using PHP, we can use a combination of PHP and CSS to achieve this without compromising caching efficiency. One way to do this is by setting a unique query parameter in the CSS file link that changes whenever the background image needs to be updated. This way, the browser recognizes the CSS file as a new resource and fetches it from the server, while still utilizing caching for other resources.

<?php
$bg_image = "path/to/background.jpg";
$cache_buster = time(); // Unique timestamp to force browser to fetch new CSS file

echo '<link rel="stylesheet" type="text/css" href="styles.css?cb=' . $cache_buster . '">';

// In styles.css file
echo 'body {
    background-image: url(' . $bg_image . ');
}';
?>