What best practices should be followed when writing PHP scripts that involve file locking mechanisms like flock?

When writing PHP scripts that involve file locking mechanisms like flock, it is important to always release the lock after using it to prevent deadlocks and ensure proper synchronization among multiple processes accessing the same file. Additionally, it is crucial to handle potential errors that may occur during the locking process to prevent unexpected behavior in your script.

$fp = fopen("example.txt", "r+");

if (flock($fp, LOCK_EX)) {
    // Perform operations on the file while it is locked
    fwrite($fp, "Hello, World!");

    flock($fp, LOCK_UN); // Release the lock
} else {
    // Handle error when locking the file
    echo "Unable to lock file.";
}

fclose($fp);