Oihana PHP

writeFileAtomic.php

Table of Contents

Functions

writeFileAtomic()  : string
Writes content to a file **atomically**.

Functions

writeFileAtomic()

Writes content to a file **atomically**.

writeFileAtomic(string $file, string $content[, int $permissions = 0644 ]) : string

The content is first written to a temporary file located in the same directory as the target (so the final rename() stays on the same filesystem and is therefore atomic), then renamed over the destination. A concurrent reader always sees either the previous file or the fully-written new one — never a half-written file. This addresses the non-atomicity caveat of plain copy/write helpers (see the copying guide).

The destination's parent directory is created on demand. On failure, the temporary file is removed and a typed exception is thrown.

Parameters
$file : string

Destination file path.

$content : string

The content to write.

$permissions : int = 0644

File permissions to set (octal, default: 0644).

Tags
throws
FileException

If the temporary file cannot be written, permissions cannot be set, or the atomic rename fails.

DirectoryException

If the destination directory cannot be created.

author

Marc Alcaraz (ekameleon)

since
1.2.0
example
use function oihana\files\writeFileAtomic;

writeFileAtomic( '/etc/myapp/config.json' , $json ) ;
// readers never observe a truncated config.json
Return values
string

The destination file path.

On this page

Search results