What is the best practice for implementing a data record lock in PHP?

When multiple users are accessing and modifying the same data record in a PHP application, it is important to implement a data record lock to prevent conflicts and ensure data integrity. One common approach is to use a file-based locking mechanism where a lock file is created when a user accesses the record and is removed once the user is done.

$recordId = 123; // ID of the data record
$lockFile = "record_$recordId.lock"; // Name of the lock file

// Attempt to acquire a lock on the data record
$lockHandle = fopen($lockFile, "w");
if (flock($lockHandle, LOCK_EX)) {
    // Lock acquired, perform operations on the data record
    // Once done, release the lock
    flock($lockHandle, LOCK_UN);
} else {
    // Unable to acquire lock, handle accordingly
}

// Close the lock file handle
fclose($lockHandle);