How can PHP scripts handle file writing when a file is already open?

When a file is already open in PHP, you can use the `flock()` function to lock the file before writing to it. This ensures that only one script can write to the file at a time, preventing conflicts and data corruption. Once the writing is done, you should release the lock using `flock()`.

$filename = 'example.txt';
$handle = fopen($filename, 'a');

if (flock($handle, LOCK_EX)) {
    fwrite($handle, 'This is a new line of text.');
    flock($handle, LOCK_UN);
} else {
    echo 'Could not lock the file.';
}

fclose($handle);