How can PHP be used to implement file locking mechanisms to prevent conflicts during simultaneous edits?

When multiple users are editing the same file simultaneously, conflicts can arise if one user saves changes while another is still editing. To prevent this, file locking mechanisms can be implemented using PHP. This involves using functions like `flock()` to lock the file while one user is editing it, preventing others from accessing it until the lock is released.

$filename = 'example.txt';

$fp = fopen($filename, 'r+');
if (flock($fp, LOCK_EX)) {
    // File is locked, perform editing operations here
    fwrite($fp, 'New content');
    
    flock($fp, LOCK_UN); // Release the lock
} else {
    echo 'Could not lock file';
}

fclose($fp);