PHPackages                             fab2s/filelock - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [File &amp; Storage](/categories/file-storage)
4. /
5. fab2s/filelock

ActiveLibrary[File &amp; Storage](/categories/file-storage)

fab2s/filelock
==============

A fluent Helper to properly handle file locking with flock

1.0.1(4y ago)2298.4k↓23.2%1MITPHPPHP ^7.1|^8.0CI failing

Since Sep 20Pushed 4y ago1 watchersCompare

[ Source](https://github.com/fab2s/FileLock)[ Packagist](https://packagist.org/packages/fab2s/filelock)[ RSS](/packages/fab2s-filelock/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (2)Dependencies (1)Versions (3)Used By (1)

FileLock
========

[](#filelock)

[![Build Status](https://camo.githubusercontent.com/c6b00934d163147dbd96cf8929b692dc0755452f74b2f6510552317e452634b0/68747470733a2f2f7472617669732d63692e636f6d2f66616232732f46696c654c6f636b2e7376673f6272616e63683d6d6173746572)](https://travis-ci.com/fab2s/FileLock) [![Total Downloads](https://camo.githubusercontent.com/ef51cbda336e66afd018f0fab3c3721f6bcb5c859c69a299b192da57aa78591c/68747470733a2f2f706f7365722e707567782e6f72672f66616232732f66696c656c6f636b2f646f776e6c6f616473)](//packagist.org/packages/fab2s/filelock) [![Monthly Downloads](https://camo.githubusercontent.com/cc6cf295bae6422f8d9a6aa9c78e54883e69d52a840ca3d478619ac54ab9dc83/68747470733a2f2f706f7365722e707567782e6f72672f66616232732f66696c656c6f636b2f642f6d6f6e74686c79)](//packagist.org/packages/fab2s/filelock) [![Latest Stable Version](https://camo.githubusercontent.com/6bc28c72bd814610b62689973967f22ee60f725d586c6b0b0bcbb47f3adb0ccd/68747470733a2f2f706f7365722e707567782e6f72672f66616232732f66696c656c6f636b2f762f737461626c65)](https://packagist.org/packages/fab2s/filelock) [![Scrutinizer Code Quality](https://camo.githubusercontent.com/aed45ea26dd3441f34641db2a28175173215158c144effd67bb04c76254ec475/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f66616232732f46696c654c6f636b2f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/fab2s/FileLock/?branch=master) [![PRs Welcome](https://camo.githubusercontent.com/7d9ed3c8f22eceb1711573169b1390cc0b1194467340dc815205060c162b5309/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5052732d77656c636f6d652d627269676874677265656e2e7376673f7374796c653d666c6174)](http://makeapullrequest.com) [![License](https://camo.githubusercontent.com/64142385e999120c9852836f6cc7ac70188365beaef2282d82296670be2ecc85/68747470733a2f2f706f7365722e707567782e6f72672f66616232732f66696c656c6f636b2f6c6963656e7365)](https://packagist.org/packages/fab2s/filelock)

A fluent *Helper* to properly handle file locking based on [flock()](https://php.net/flock).

FileLock offers two locking strategies and several options. Just like `flock()`, FileLock can either wait until an exclusive lock is acquired (Blocking), or fail immediately (Non Blocking), but it can also try a configurable amount of time to acquire a Non Blocking exclusive lock, and wait a configurable amount of time between each attempts. FileLock can either lock a file (Self Locking) or create a file.lock and lock it instead (External Locking)

Installation
------------

[](#installation)

Math can be installed using composer :

```
composer require "fab2s/filelock"

```

`FileLock` is also included in [OpinHelper](https://github.com/fab2s/OpinHelpers) which packages several bellow "Swiss Army Knife" level Helpers covering some of the most annoying aspects of php programing, such as UTF8 string manipulation, high precision Mathematics or properly locking a file

Should you need to work with php bellow 7.1, you can still use [OpinHelper](https://github.com/fab2s/OpinHelpers) `0.x`

Prerequisites
-------------

[](#prerequisites)

`FileLock` has no specific dependencies

External Locking
----------------

[](#external-locking)

This locking strategy does not lock the input filePath itself but rather creates a new file `$lockFilePath = "$inputFilePath.lock";` and attempts to [flock()](https://php.net/flock) it instead This method is preferred in highly concurrent usages, where many processes will try to write the same file at once, such as file caching. Because this allows us to first try to open the `.lock` file in *write* mode and fail back to *read* mode before a `flock()` is eventually attempted

By using a separate file for locking, we make sure that every write waiting for the lock (this should be done in Blocking mode) does not hold any handle on the cache file itself while it is most likely already being intensively read

By failing back to *read* mode when *write* failed, we again lower the *write* handles to a single one, only when the external `.lock` file needs to be created. Altogether, this means that after warm up, each process waiting to write on the same file will be holding a *read* handle on the `.lock` file, while a single *write* one is at most used to actually write the cache file. As *write* handles are costly to open, approximately ten times slower than *read* handles, doing this can end up making some difference

External locking can also be useful when you do not want to actually `flock()` a file (could be already locked or used by some other program/process), or because you just need exclusivity for something as the lock file is then created for you and every PHP process will be able to check its existence

> Please note that the external and empty `.lock` file is never deleted by FileLock and that its presence does not necessarily means that the lock is active

If the `$lockFilePath = "$inputFilePath.lock";` version of the `.lock` file (that is where the $inputFilePath directory) is not writable, it is created in `sys_get_temp_dir()` instead, with a hashed `basedir($inputFilePath)` prefix in filename

```
$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
```

Self Locking
------------

[](#self-locking)

This locking strategy does acquire a lock on the input filePath itself. It provide with more guarantees than the External Locking strategy as the file will be locked for any process, not just the ones checking the lock through FileLock and it is preferred when write sessions are not *instant*

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

It *could* make sense under specific circumstances to use a double lock, both External and Self, using two FileLock instances

In practice
-----------

[](#in-practice)

In both External and Self locking, once you have an instance you can:

- Acquire a Blocking lock:

    ```
    $lock->doLock(true);
    // we either own the lock or php timed out
    ```
- Attempt to acquire a Non Blocking lock:

    ```
    if ($lock->doLock()) {
        // we got the lock
    }
    ```
- Attempt to acquire a Non Blocking lock several time before failing:

    ```
    $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
    }
    ```

From there, you can get the underlying handle:

```
$lockHandle = $lock->getHandle();
```

This is mostly useful when Self locking as you probably need the handle to actually write something.

### Release lock

[](#release-lock)

In all cases, locks are either released upon instance destruction or manually:

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

> It is **IMPORTANT** to notice that when you acquire an Self lock, you need to keep the $lock instance alive until you are done with manipulating the file. Because FileLock is set to release its locks and handles when destroyed. This could happen if you where to acquire a lock in some function without storing the resulting instance outside of its scope.

Open Factory
------------

[](#open-factory)

FileLock comes with an handy factory to ease exclusively and self locked file opening:

```
    /**
     * @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)
```

Usage is pretty similar to [fopen()](https://php.net/fopen) except it returns a FileLock instance upon success (open + lock) instead of a resource and null when it failed.

```
$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();
}
```

Requirements
------------

[](#requirements)

`FileLock` is tested against php 7.1, 7.2, 7.3, 7.4 and 8.0

Contributing
------------

[](#contributing)

Contributions are welcome, do not hesitate to open issues and submit pull requests.

License
-------

[](#license)

`FileLock` is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity36

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity64

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~635 days

Total

2

Last Release

1798d ago

PHP version history (2 changes)1.0.0PHP &gt;=7.1

1.0.1PHP ^7.1|^8.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/7323989?v=4)[fab2s](/maintainers/fab2s)[@fab2s](https://github.com/fab2s)

---

Top Contributors

[![fab2s](https://avatars.githubusercontent.com/u/7323989?v=4)](https://github.com/fab2s "fab2s (11 commits)")

---

Tags

file-lockflockhelperphpsimplephphelperfileSimpleflocklockfilelock

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/fab2s-filelock/health.svg)

```
[![Health](https://phpackages.com/badges/fab2s-filelock/health.svg)](https://phpackages.com/packages/fab2s-filelock)
```

###  Alternatives

[jstewmc/php-helpers

Static classes to help with numbers, strings, arrays, files, and bools in PHP

3111.6k2](/packages/jstewmc-php-helpers)[blueimp/jquery-file-upload

File Upload widget for jQuery.

141.5M18](/packages/blueimp-jquery-file-upload)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
