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);
Related Questions
- How can PDO::quote be used for escaping in PHP when generating dynamic SQL for inserts?
- What are some best practices for handling form submissions in PHP to ensure successful delivery and error handling?
- Why is it important to include the charset=utf8 parameter in a PDO connection string for PHP applications?