PHP code example of fab2s / filelock

1. Go to this page and download the library: Download fab2s/filelock library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

fab2s / filelock example snippets


$filePath = "/some/dir/some.file.ext";
$lock = new FileLock($filePath, Filelock::LOCK_EXTERNAL); // will create /some/dir/some/file.ext.lock or /tmp/sha1(/some/dir/some)_file.ext.lock

$filePath = "/some/dir/some.file.ext";
$lock = new FileLock($filePath, Filelock::LOCK_SELF); // will directtly flock() /some/dir/some/file.ext

    $lock->doLock(true);
    // we either own the lock or php timed out
    

    if ($lock->doLock()) {
        // we got the lock
    }
    

    $isLocked = $lock->setLockTry(5) // default is 3
        ->setLockWait(0.01) // default is 0.1 second
        ->obtainLock(); // will try 5 times and wait 0.01 second in between
    if ($isLocked) { // could call $lock->isLocked()
        // we got the lock
    }
    

$lockHandle = $lock->getHandle();

$lock->unLock(); // doing so also fclose() underlying handle

    /**
     * @param string     $file
     * @param string     $mode fopen() mode
     * @param int|null   $maxTries 0|null for single non blocking attempt
     *                             1 for a single blocking attempt
     *                             1-N Number of non blocking attempts
     * @param float|null $lockWait Time to wait between attempts in second
     *
     * @return null|static
     */
    public static function open($file, $mode, $maxTries = null, $lockWait = null)

$filePath = "/some/dir/some.file.ext";
$mode = 'wb'; // any fopen() mode
$fileLock = Filelock::open($filePath, $mode); // returns null or FileLock instance

if ($fileLock) {
	// we got it opened and locked
	$handle = $fileLock->getHandle();
}