PHPackages                             philiprehberger/safe-file-writer - 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. philiprehberger/safe-file-writer

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

philiprehberger/safe-file-writer
================================

Atomic file writes with temp-file swap and file locking

v1.1.0(2mo ago)138MITPHPPHP ^8.2CI passing

Since Mar 13Pushed 1mo agoCompare

[ Source](https://github.com/philiprehberger/safe-file-writer)[ Packagist](https://packagist.org/packages/philiprehberger/safe-file-writer)[ Docs](https://github.com/philiprehberger/safe-file-writer)[ GitHub Sponsors](https://github.com/philiprehberger)[ RSS](/packages/philiprehberger-safe-file-writer/feed)WikiDiscussions main Synced 3w ago

READMEChangelogDependencies (6)Versions (5)Used By (0)

PHP Safe File Writer
====================

[](#php-safe-file-writer)

[![Tests](https://github.com/philiprehberger/safe-file-writer/actions/workflows/tests.yml/badge.svg)](https://github.com/philiprehberger/safe-file-writer/actions/workflows/tests.yml)[![Latest Version on Packagist](https://camo.githubusercontent.com/3d3d2c0174d95af6f67e2cf53ab922468b9852c2cdf5ee2ae1d0fc330e22de65/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7068696c69707265686265726765722f736166652d66696c652d7772697465722e737667)](https://packagist.org/packages/philiprehberger/safe-file-writer)[![Last updated](https://camo.githubusercontent.com/898bfc99a1d8a1a20b5bfa58d5211c361b563470a9663347ba403f150ccc09cc/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6173742d636f6d6d69742f7068696c69707265686265726765722f736166652d66696c652d777269746572)](https://github.com/philiprehberger/safe-file-writer/commits/main)

Atomic file writes with temp-file swap and file locking.

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

[](#requirements)

- PHP 8.2+

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

[](#installation)

```
composer require philiprehberger/safe-file-writer
```

Usage
-----

[](#usage)

### Write a file atomically

[](#write-a-file-atomically)

```
use PhilipRehberger\SafeFileWriter\SafeFile;

// Writes to a temp file first, then renames — atomic on POSIX systems
SafeFile::write('/path/to/config.txt', 'key=value');

// Parent directories are created automatically
SafeFile::write('/path/to/deep/nested/file.txt', 'content');
```

### Write JSON

[](#write-json)

```
SafeFile::writeJson('/path/to/data.json', [
    'name' => 'Philip',
    'scores' => [10, 20, 30],
]);
// Writes pretty-printed JSON with a trailing newline

// Custom JSON flags
SafeFile::writeJson('/path/to/compact.json', $data, JSON_UNESCAPED_UNICODE);
```

### Append to a file

[](#append-to-a-file)

```
// Appends with exclusive lock; creates file if it doesn't exist
SafeFile::append('/var/log/app.log', "[2026-03-13] Info: started\n");
SafeFile::append('/var/log/app.log', "[2026-03-13] Info: finished\n");
```

### Read a file

[](#read-a-file)

```
// Reads with a shared lock
$content = SafeFile::read('/path/to/config.txt');
```

### Read JSON

[](#read-json)

```
$data = SafeFile::readJson('/path/to/data.json');
// Returns decoded array/object
```

### Check existence

[](#check-existence)

```
if (SafeFile::exists('/path/to/file.txt')) {
    // ...
}
```

### Delete a file

[](#delete-a-file)

```
$deleted = SafeFile::delete('/path/to/file.txt');
// Returns true if deleted, false if file didn't exist
```

### Backup Before Write

[](#backup-before-write)

```
use PhilipRehberger\SafeFileWriter\SafeFile;

// Backs up existing file with timestamp, then writes new content atomically
SafeFile::writeWithBackup('/path/to/config.txt', 'new config');
// Creates /path/to/config.txt.2026-03-31T120000.bak before overwriting

// Store backups in a custom directory
SafeFile::writeWithBackup('/path/to/config.txt', 'updated', '/var/backups');

// Same for JSON files
SafeFile::writeJsonWithBackup('/path/to/data.json', ['version' => 2]);
```

### File Checksums

[](#file-checksums)

```
use PhilipRehberger\SafeFileWriter\Checksum;
use PhilipRehberger\SafeFileWriter\SafeFile;

// Compute a SHA-256 checksum (default)
$hash = SafeFile::checksum('/path/to/file.txt');

// Use a different algorithm
$md5 = SafeFile::checksum('/path/to/file.txt', 'md5');

// Verify a file against a known checksum
$valid = SafeFile::verifyChecksum('/path/to/file.txt', $expectedHash);

// Compare two files
$same = Checksum::compareFiles('/path/to/a.txt', '/path/to/b.txt');
```

### Atomic Multi-File Writes

[](#atomic-multi-file-writes)

```
use PhilipRehberger\SafeFileWriter\SafeFile;

// Write multiple files atomically — all or nothing
SafeFile::writeMany([
    '/path/to/config.json' => '{"key": "value"}',
    '/path/to/settings.yaml' => 'debug: true',
    '/path/to/version.txt' => '1.1.0',
]);
// If any file fails to write, previously written files are rolled back
```

API
---

[](#api)

MethodDescriptionReturns`SafeFile::write(string $path, string $content)`Atomic write via temp-file + rename`void``SafeFile::writeJson(string $path, mixed $data, int $flags = ...)`Atomic JSON write`void``SafeFile::writeWithBackup(string $path, string $content, ?string $backupDir = null)`Backup existing file, then atomic write`void``SafeFile::writeJsonWithBackup(string $path, mixed $data, ?string $backupDir = null)`Backup existing file, then atomic JSON write`void``SafeFile::writeMany(array $files)`Atomic multi-file write with rollback`void``SafeFile::append(string $path, string $content)`Append with exclusive lock`void``SafeFile::read(string $path)`Read with shared lock`string``SafeFile::readJson(string $path)`Read and decode JSON`mixed``SafeFile::checksum(string $path, string $algo = 'sha256')`Compute file checksum`string``SafeFile::verifyChecksum(string $path, string $expected, string $algo = 'sha256')`Verify file against expected checksum`bool``SafeFile::exists(string $path)`Check if file exists`bool``SafeFile::delete(string $path)`Delete file if it exists`bool``BackupManager::backup(string $path, ?string $backupDir = null)`Create timestamped backup of a file`?string``Checksum::compute(string $path, string $algo = 'sha256')`Compute file hash`string``Checksum::verify(string $path, string $expected, string $algo = 'sha256')`Verify file hash matches expected`bool``Checksum::compareFiles(string $pathA, string $pathB, string $algo = 'sha256')`Compare checksums of two files`bool``FileWriteException`Directory creation, temp-file creation, write, or rename failure—`FileReadException`File not found, open failure, lock failure, or read failure—`\JsonException`Invalid JSON on `writeJson()` or `readJson()`—Development
-----------

[](#development)

```
composer install
vendor/bin/phpunit
vendor/bin/pint --test
vendor/bin/phpstan analyse
```

Support
-------

[](#support)

If you find this project useful:

⭐ [Star the repo](https://github.com/philiprehberger/safe-file-writer)

🐛 [Report issues](https://github.com/philiprehberger/safe-file-writer/issues?q=is%3Aissue+is%3Aopen+label%3Abug)

💡 [Suggest features](https://github.com/philiprehberger/safe-file-writer/issues?q=is%3Aissue+is%3Aopen+label%3Aenhancement)

❤️ [Sponsor development](https://github.com/sponsors/philiprehberger)

🌐 [All Open Source Projects](https://philiprehberger.com/open-source-packages)

💻 [GitHub Profile](https://github.com/philiprehberger)

🔗 [LinkedIn Profile](https://www.linkedin.com/in/philiprehberger)

License
-------

[](#license)

[MIT](LICENSE)

###  Health Score

41

—

FairBetter than 87% of packages

Maintenance88

Actively maintained with recent releases

Popularity9

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity50

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 87.5% 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 ~6 days

Total

4

Last Release

86d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/cfd7d24cbbf32400fa13ce0bbe7a31edd2d66a6d4488eafdb3d64c5337bf0435?d=identicon)[philiprehberger](/maintainers/philiprehberger)

---

Top Contributors

[![philiprehberger](https://avatars.githubusercontent.com/u/8218077?v=4)](https://github.com/philiprehberger "philiprehberger (14 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (2 commits)")

---

Tags

safefilewritelockatomic

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/philiprehberger-safe-file-writer/health.svg)

```
[![Health](https://phpackages.com/badges/philiprehberger-safe-file-writer/health.svg)](https://phpackages.com/packages/philiprehberger-safe-file-writer)
```

###  Alternatives

[league/flysystem

File storage abstraction for PHP

13.6k665.7M2.4k](/packages/league-flysystem)[league/flysystem-aws-s3-v3

AWS S3 filesystem adapter for Flysystem.

1.7k277.8M961](/packages/league-flysystem-aws-s3-v3)[knplabs/gaufrette

PHP library that provides a filesystem abstraction layer

2.5k40.9M129](/packages/knplabs-gaufrette)[knplabs/knp-gaufrette-bundle

Allows to easily use the Gaufrette library in a Symfony project

72429.6M99](/packages/knplabs-knp-gaufrette-bundle)[league/flysystem-local

Local filesystem adapter for Flysystem.

224254.9M71](/packages/league-flysystem-local)[nette/safe-stream

Nette SafeStream: provides isolation for thread safe manipulation with files via native PHP functions.

1185.0M141](/packages/nette-safe-stream)

PHPackages © 2026

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