What is the purpose of using flock() in PHP and how can it be applied to prevent multiple instances of a script from running simultaneously?

Using flock() in PHP allows you to lock a file, preventing other scripts from accessing it simultaneously. This can be useful when you want to ensure that only one instance of a particular script is running at a time.

$lockFile = fopen("lock.txt", "w");
if (flock($lockFile, LOCK_EX | LOCK_NB)) {
    // Run your script here
    flock($lockFile, LOCK_UN);
} else {
    echo "Script is already running.";
}
fclose($lockFile);