PHP

Atomic File Write

admin by @admin ADMIN
5h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Write a file in a way that other processes never see a half-written state. Write to a temp file in the same directory, then rename — rename is atomic on POSIX filesystems.
PHP
Raw
<?php
function atomicWrite(string $path, string $contents, int $mode = 0644): bool {
    $dir  = dirname($path);
    $tmp  = tempnam($dir, '.atomic-');
    if ($tmp === false) return false;
    try {
        if (file_put_contents($tmp, $contents, LOCK_EX) === false) return false;
        chmod($tmp, $mode);
        return rename($tmp, $path);  // atomic on the same filesystem
    } finally {
        if (file_exists($tmp)) @unlink($tmp);
    }
}

atomicWrite('/var/lib/myapp/state.json', json_encode(['ok' => true]));
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.