How can one optimize the provided PHP code for reading and writing data to a CSV file to prevent data corruption or loss?

To optimize the provided PHP code for reading and writing data to a CSV file and prevent data corruption or loss, it is essential to properly handle file locking. This ensures that only one process can write to the file at a time, preventing data corruption. By using the flock() function to acquire an exclusive lock on the file before writing and releasing the lock after writing, we can ensure data integrity.

<?php
$filename = 'data.csv';

// Open the file in append mode and acquire an exclusive lock
$file = fopen($filename, 'a+');
if (flock($file, LOCK_EX)) {
    // Write data to the file
    fputcsv($file, $data);
    
    // Release the lock and close the file
    flock($file, LOCK_UN);
    fclose($file);
} else {
    echo 'Could not acquire lock on file.';
}
?>