What are some best practices for efficiently managing and serving dynamic CSS files generated by PHP based on user preferences?

When managing and serving dynamic CSS files generated by PHP based on user preferences, it is important to efficiently cache the generated CSS files to reduce server load and improve performance. One way to achieve this is by using a combination of PHP output buffering, file caching, and conditional checks to determine when to regenerate the CSS files based on user preferences.

<?php
// Check if the cached CSS file exists and is up to date
$cached_css_file = 'cached_styles.css';
$should_regenerate = false;

if (!file_exists($cached_css_file)) {
    $should_regenerate = true;
} else {
    $last_modified = filemtime($cached_css_file);
    $expiry_time = time() - 3600; // Example: Regenerate CSS file every hour
    if ($last_modified < $expiry_time) {
        $should_regenerate = true;
    }
}

if ($should_regenerate) {
    ob_start();
    // Generate dynamic CSS based on user preferences
    // Replace this with your actual CSS generation code
    header('Content-Type: text/css');
    echo 'body { background-color: #fff; color: #333; }';
    $css_content = ob_get_clean();
    
    // Save generated CSS to cached file
    file_put_contents($cached_css_file, $css_content);
} else {
    // Serve cached CSS file
    header('Content-Type: text/css');
    readfile($cached_css_file);
}