{"id":17191658,"url":"https://github.com/fab2s/filelock","last_synced_at":"2025-04-13T19:53:14.709Z","repository":{"id":62503419,"uuid":"201736388","full_name":"fab2s/FileLock","owner":"fab2s","description":"A fluent Helper to properly handle file locking based on flock()","archived":false,"fork":false,"pushed_at":"2021-06-16T09:56:39.000Z","size":12,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2024-03-15T03:07:52.458Z","etag":null,"topics":["file-lock","flock","helper","php","simple"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/fab2s.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-08-11T08:09:36.000Z","updated_at":"2022-11-20T17:35:51.000Z","dependencies_parsed_at":"2022-11-02T12:03:05.400Z","dependency_job_id":null,"html_url":"https://github.com/fab2s/FileLock","commit_stats":null,"previous_names":[],"tags_count":2,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fab2s%2FFileLock","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fab2s%2FFileLock/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fab2s%2FFileLock/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fab2s%2FFileLock/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/fab2s","download_url":"https://codeload.github.com/fab2s/FileLock/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248774136,"owners_count":21159525,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["file-lock","flock","helper","php","simple"],"created_at":"2024-10-15T01:27:00.669Z","updated_at":"2025-04-13T19:53:14.685Z","avatar_url":"https://github.com/fab2s.png","language":"PHP","readme":"# FileLock\n\n[![Build Status](https://travis-ci.com/fab2s/FileLock.svg?branch=master)](https://travis-ci.com/fab2s/FileLock) [![Total Downloads](https://poser.pugx.org/fab2s/filelock/downloads)](//packagist.org/packages/fab2s/filelock) [![Monthly Downloads](https://poser.pugx.org/fab2s/filelock/d/monthly)](//packagist.org/packages/fab2s/filelock) [![Latest Stable Version](https://poser.pugx.org/fab2s/filelock/v/stable)](https://packagist.org/packages/fab2s/filelock) [![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/fab2s/FileLock/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/fab2s/FileLock/?branch=master) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat)](http://makeapullrequest.com) [![License](https://poser.pugx.org/fab2s/filelock/license)](https://packagist.org/packages/fab2s/filelock)\n\nA fluent _Helper_ to properly handle file locking based on [flock()](https://php.net/flock).\n\nFileLock offers two locking strategies and several options.\nJust 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)\n\n## Installation\n\nMath can be installed using composer :\n\n```\ncomposer require \"fab2s/filelock\"\n```\n\n`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\n\nShould you need to work with php bellow 7.1, you can still use [OpinHelper](https://github.com/fab2s/OpinHelpers) `0.x`\n\n## Prerequisites\n\n`FileLock` has no specific dependencies \n\n## External Locking\n\nThis 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\nThis 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\n\nBy 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\n\nBy 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. \nAltogether, 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\n\nExternal 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\n\n\u003e 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\n\nIf 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\n\n```php\n$filePath = \"/some/dir/some.file.ext\";\n$lock = new FileLock($filePath, Filelock::LOCK_EXTERNAL); // will create /some/dir/some/file.ext.lock or /tmp/sha1(/some/dir/some)_file.ext.lock\n```\n\n## Self Locking\n\nThis 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_\n\n```php\n$filePath = \"/some/dir/some.file.ext\";\n$lock = new FileLock($filePath, Filelock::LOCK_SELF); // will directtly flock() /some/dir/some/file.ext\n```\n\nIt _could_ make sense under specific circumstances to use a double lock, both External and Self, using two FileLock instances\n\n## In practice\n\nIn both External and Self locking, once you have an instance you can:\n\n- Acquire a Blocking lock:\n    \n    ```php\n    $lock-\u003edoLock(true);\n    // we either own the lock or php timed out\n    ```\n\n- Attempt to acquire a Non Blocking lock:\n    \n    ```php\n    if ($lock-\u003edoLock()) {\n        // we got the lock\n    }\n    ```\n\n- Attempt to acquire a Non Blocking lock several time before failing:\n    \n    ```php\n    $isLocked = $lock-\u003esetLockTry(5) // default is 3\n        -\u003esetLockWait(0.01) // default is 0.1 second\n        -\u003eobtainLock(); // will try 5 times and wait 0.01 second in between\n    if ($isLocked) { // could call $lock-\u003eisLocked()\n        // we got the lock\n    }\n    ```\n\nFrom there, you can get the underlying handle:\n\n```php\n$lockHandle = $lock-\u003egetHandle();\n```\n\nThis is mostly useful when Self locking as you probably need the handle to actually write something.\n\n### Release lock\n    \nIn all cases, locks are either released upon instance destruction or manually:\n\n```php\n$lock-\u003eunLock(); // doing so also fclose() underlying handle\n```\n\n\u003e 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.\n\n## Open Factory\n\nFileLock comes with an handy factory to ease exclusively and self locked file opening:\n\n```php\n    /**\n     * @param string     $file\n     * @param string     $mode fopen() mode\n     * @param int|null   $maxTries 0|null for single non blocking attempt\n     *                             1 for a single blocking attempt\n     *                             1-N Number of non blocking attempts\n     * @param float|null $lockWait Time to wait between attempts in second\n     *\n     * @return null|static\n     */\n    public static function open($file, $mode, $maxTries = null, $lockWait = null)\n```\n\nUsage 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.\n\n```php\n$filePath = \"/some/dir/some.file.ext\";\n$mode = 'wb'; // any fopen() mode\n$fileLock = Filelock::open($filePath, $mode); // returns null or FileLock instance\n\nif ($fileLock) {\n\t// we got it opened and locked\n\t$handle = $fileLock-\u003egetHandle();\n}\n```\n\n## Requirements\n\n`FileLock` is tested against php 7.1, 7.2, 7.3, 7.4 and 8.0\n\n## Contributing\n\nContributions are welcome, do not hesitate to open issues and submit pull requests.\n\n## License\n\n`FileLock` is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffab2s%2Ffilelock","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffab2s%2Ffilelock","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffab2s%2Ffilelock/lists"}