What are the best practices for handling file operations in PHP, specifically when creating or modifying CSS files?

When creating or modifying CSS files in PHP, it is important to handle file operations carefully to avoid any errors or data loss. One best practice is to use file locking to prevent concurrent writes to the same file. Additionally, always sanitize user input to prevent any malicious code injection.

// Example of creating or modifying a CSS file in PHP
$filename = 'styles.css';
$content = 'body { background-color: #f0f0f0; }';

// Open the file for writing
$handle = fopen($filename, 'w');

// Lock the file before writing
if (flock($handle, LOCK_EX)) {
    fwrite($handle, $content);
    flock($handle, LOCK_UN); // Unlock the file
} else {
    echo 'Could not lock the file.';
}

// Close the file handle
fclose($handle);