PHP

Atomic Counter with flock

admin by @admin ADMIN
Jun 16, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
A single-file counter that survives concurrent increments correctly using flock + read-modify-write inside the locked region. Useful for crude visitor or job-id counters when you don't want a DB.
PHP
Raw
<?php
function increment(string $file, int $by = 1): int {
    $fh = fopen($file, 'c+');
    flock($fh, LOCK_EX);
    $current = (int)stream_get_contents($fh);
    $next    = $current + $by;
    rewind($fh);
    ftruncate($fh, 0);
    fwrite($fh, (string)$next);
    fflush($fh);
    flock($fh, LOCK_UN);
    fclose($fh);
    return $next;
}

$jobId = increment('/var/lib/myapp/jobs.counter');
echo "Assigned job #$jobId\n";
Tags

Save your own code snippets

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