How can the PHP script be modified to lock the file before reading, incrementing, and writing the counter to prevent data corruption?
To prevent data corruption when reading, incrementing, and writing the counter in a file, the PHP script can be modified to use file locking. By locking the file before performing these operations, we ensure that only one process can access the file at a time, preventing potential race conditions and data corruption.
$counter_file = 'counter.txt';
$fp = fopen($counter_file, 'r+');
if (flock($fp, LOCK_EX)) {
$counter = intval(fread($fp, filesize($counter_file)));
$counter++;
fseek($fp, 0);
fwrite($fp, $counter);
flock($fp, LOCK_UN);
} else {
echo "Could not lock file!";
}
fclose($fp);