What are common challenges faced when using Websockets in PHP for real-time user input to a file?

One common challenge when using Websockets in PHP for real-time user input to a file is handling concurrent connections and ensuring data consistency. One way to solve this is by using a locking mechanism to prevent multiple users from writing to the file simultaneously.

$fp = fopen('input.txt', 'a+');
if (flock($fp, LOCK_EX)) {
    fwrite($fp, $user_input . PHP_EOL);
    flock($fp, LOCK_UN);
} else {
    echo 'Unable to acquire lock for file';
}
fclose($fp);