What are the best practices for handling concurrent access to files in PHP to prevent data corruption or loss?

Concurrent access to files in PHP can lead to data corruption or loss if not handled properly. To prevent this, use file locking mechanisms such as flock() to ensure that only one process can write to a file at a time. This will help prevent conflicts and maintain data integrity.

$fp = fopen('data.txt', 'r+');
if (flock($fp, LOCK_EX)) {
    // Perform file operations here
    flock($fp, LOCK_UN);
} else {
    echo "Could not lock file.";
}
fclose($fp);