What are the best practices for handling file locks in PHP to prevent conflicts and ensure data integrity?

When multiple processes or threads access the same file concurrently, file locks can prevent conflicts and ensure data integrity. In PHP, you can use the flock() function to acquire an exclusive lock on a file before reading or writing to it. It's important to release the lock when you're done to allow other processes to access the file.

$fp = fopen('example.txt', 'r+');
if (flock($fp, LOCK_EX)) {
    // Perform read or write operations on the file
    flock($fp, LOCK_UN); // Release the lock
} else {
    echo "Could not acquire lock on file.";
}
fclose($fp);