bonsaicode / filelock
Used to prevent a script from being run more than once at the same time by providing mutex functionality via locking a file on the local machine.
Requires
- php: >=7.1
Requires (Dev)
- phpunit/phpunit: ^9.6 || ^10.5 || ^11.5
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-14 17:22:49 UTC
README
Used to prevent a script from being run more than once at the same time by providing mutex functionality via locking a file on the local machine.
Scenario:
- You run php script A and it acquires the lock having a given name, e.g. "lockA"
- You try to run script A again while it is still running. It tries to acquire the same "lockA", but cannot because the first script has the lock.
- After the first script A ends, the "lockA" is released, and then you could run the script again.
The lock is held by the operating system (flock), so it is released automatically if the script dies unexpectedly.
The lock file is left in place on release (deleting it would let two processes hold the same lock at once). The leftover files are empty and harmless.
This class is intended for single server environments or when you know the process will only run on one server.
DO NOT use this if you are running in a multi-server environment where duplicate VMs could be dynamically created, e.g. auto scaling environment.
Otherwise the same process could run at the same time on multiple servers.
Therefore we do not use sys_get_temp_dir() for the lockfile directory because the server could change between requests.
If you are running in a multi-server environment with dynamically created VMs, please use the BonsaiCode\Redis::lockAcquire and BonsaiCode\Redis::lockRelease methods (with a redis service)
Note: This does not work on Windows localhost w/NGINX:
- the script will wait until any lockfile is released instead of the intended named lockfile.
- two scripts won't run at same time, but one will wait for the other instead of exiting
Dependencies:
Pass the lock directory to the constructor, or define a LOCK_DIR constant with the directory in which to create the lock file, e.g.:
const LOCK_DIR = '/var/www/mysite.com/locks';
The lock directory should be located outside of any web/code directories so that the code can be updated without affecting any existing lock files.
The lock directory MUST BE WRITABLE BY THE WEB SERVER / CRON USER.
Requirements
- PHP 7.1 or higher
Installation
To install the package, run the following command in the console:
$ composer require "bonsaicode/filelock"
Usage
<?php
$lock = new BonsaiCode\FileLock( 'MyLock' ); # or: new BonsaiCode\FileLock( 'MyLock', '/var/www/mysite.com/locks' )
$lockStatus = $lock->acquire();
if( $lockStatus === -1 ) {
echo "Script already running\n";
exit();
} else if( $lockStatus === -2 ) {
echo "Cannot open lock, permission problem?\n";
exit();
}
# Your process code here...
$lock->release();
?>