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
rust
use axum::{extract::{Path, State}, http::StatusCode, Json}; use dashmap::DashMap; use serde::Serialize; use std::sync::Arc;
Request coalescing in an Axum handler
caching
concurrency
request-coalescing
Advanced
8 steps
php
<?php namespace App\Console\Commands;
Releasing stale document locks in Laravel
artisan-command
transactions
row-locking
Intermediate
6 steps
php
<?php namespace App\Providers;
Subdomain multi-tenancy routing in Laravel
multi-tenancy
service-container
route-binding
Advanced
7 steps
php
<?php namespace App\Broadcasting;
Authorizing presence channels in Laravel
broadcasting
authorization
presence-channels
Intermediate
3 steps
go
package config import ( "fmt"
A thread-safe config singleton in Go
singleton
concurrency
environment-variables
Intermediate
7 steps
php
<?php namespace App\Http\Middleware;
Resolving the current team in Laravel middleware
middleware
multi-tenancy
cookies
Intermediate
8 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.