Are there any best practices for executing PHP scripts to prevent them from running multiple times unintentionally?

To prevent PHP scripts from running multiple times unintentionally, one common approach is to use a lock file. The script checks for the existence of a lock file before proceeding, and if the file exists, the script exits to prevent multiple instances from running simultaneously. If the lock file does not exist, the script creates the lock file before executing its main functionality.

$lockFile = '/path/to/lockfile.lock';

if (file_exists($lockFile)) {
    // Lock file exists, exit to prevent multiple instances
    exit;
}

// Create lock file
file_put_contents($lockFile, '');

// Main script functionality goes here

// Remove lock file after script execution
unlink($lockFile);