How can file access be restricted to prevent multiple users from accessing the same file simultaneously in PHP?

To prevent multiple users from accessing the same file simultaneously in PHP, you can use file locking. This involves acquiring an exclusive lock on the file before reading or writing to it, which prevents other users from accessing it at the same time.

$filename = 'example.txt';

$handle = fopen($filename, 'r');
if (flock($handle, LOCK_EX)) {
    // Perform operations on the file
    flock($handle, LOCK_UN); // Release the lock
} else {
    echo 'Could not lock the file.';
}

fclose($handle);