Skip to content
PHP Logo

How can PHP developers ensure data integrity when multiple users access the same file simultaneously?

When multiple users access the same file simultaneously in PHP, developers can ensure data integrity by implementing file locking mechanisms. This prevents multiple users from writing to the file at the same time, avoiding data corruption or inconsistencies.

php
$filename = "data.txt";

$handle = fopen($filename, "a+");

if (flock($handle, LOCK_EX)) {
    // Perform operations on the file here
    fwrite($handle, "New data to write\n");

    flock($handle, LOCK_UN);
} else {
    echo "Could not lock the file!";
}

fclose($handle);