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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1An exclusive lock turns a read-modify-write sequence into an atomic operation across concurrent processes.
- 2A finally block guarantees the lock is released and the handle closed even when a write fails midway.
- 3Truncating and rewinding before writing prevents stale trailing bytes from a shorter new value.
Related explainers
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 steps
php
<?php final class RotatingFileLogger {
How a rotating file logger works in PHP
logging
file-rotation
io
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-race-free-file-counter-in-php-explained-php-dd06/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.