How can locking be implemented for secure writing operations in PHP?

To implement locking for secure writing operations in PHP, you can use file locking mechanisms to prevent multiple processes from writing to the same file simultaneously. This ensures data integrity and prevents race conditions.

$fp = fopen("data.txt", "a");
if (flock($fp, LOCK_EX)) {
    fwrite($fp, "Data to be written");
    flock($fp, LOCK_UN);
} else {
    echo "Couldn't lock the file!";
}
fclose($fp);