php 45 lines · 7 steps

A race-free file counter in PHP

Using an exclusive file lock to safely read-modify-write a persistent integer counter.

Explained by highlit
1<?php
2 
3namespace App\Storage;
4 
5use RuntimeException;
6 
7final class CounterFile
8{
9 public function __construct(private readonly string $path)
10 {
11 }
12 
13 public function increment(int $by = 1): int
14 {
15 $handle = fopen($this->path, 'c+');
16 
17 if ($handle === false) {
18 throw new RuntimeException("Unable to open {$this->path}");
19 }
20 
21 try {
22 if (!flock($handle, LOCK_EX)) {
23 throw new RuntimeException("Could not acquire lock on {$this->path}");
24 }
25 
26 $contents = stream_get_contents($handle);
27 $current = (int) trim($contents);
28 $next = $current + $by;
29 
30 rewind($handle);
31 ftruncate($handle, 0);
32 
33 if (fwrite($handle, (string) $next) === false) {
34 throw new RuntimeException("Failed to write to {$this->path}");
35 }
36 
37 fflush($handle);
38 
39 return $next;
40 } finally {
41 flock($handle, LOCK_UN);
42 fclose($handle);
43 }
44 }
45}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1An exclusive lock turns a read-modify-write sequence into an atomic operation across concurrent processes.
  2. 2A finally block guarantees the lock is released and the handle closed even when a write fails midway.
  3. 3Truncating and rewinding before writing prevents stale trailing bytes from a shorter new value.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A race-free file counter in PHP — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code