In PHP, what methods can be employed to ensure the integrity and consistency of file modifications, particularly when adding or editing content within a file that contains structured data or code blocks?

When adding or editing content within a file that contains structured data or code blocks, it is important to ensure the integrity and consistency of the file. One way to achieve this is by using file locking mechanisms, such as flock(), to prevent concurrent writes to the file. Additionally, you can read the file contents, make modifications in memory, and then write the modified content back to the file in a single operation to avoid data corruption.

$file = 'data.txt';

// Open the file for reading and writing
$handle = fopen($file, 'r+');

// Acquire an exclusive lock on the file
if (flock($handle, LOCK_EX)) {
    // Read the file contents
    $contents = fread($handle, filesize($file));

    // Make modifications to the content

    // Rewind the file pointer to the beginning
    fseek($handle, 0);

    // Write the modified content back to the file
    fwrite($handle, $modifiedContent);

    // Release the lock
    flock($handle, LOCK_UN);
} else {
    echo 'Could not acquire lock on file';
}

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