HTTP ETags allow conditional updates with If-Match so clients do not overwrite concurrent changes.
What It Does
HTTP ETags allow conditional updates with If-Match so clients do not overwrite concurrent changes. The following examples distinguish a normal use case, a boundary case and a practical application.
Requirements and Compatibility
PHP 8.x and a local test environment. Apply input validation, correct error handling and the requirements of any optional libraries.
The code focuses on the core concept. Production implementation may also need routes, validation, persistence, authorization or deployment tooling.
Example 1: Basic Behavior
Generate an ETag from a stable canonical representation of the resource.
<?php
$body = json_encode(["id" => 8, "version" => 3], JSON_THROW_ON_ERROR);
$etag = chr(34) . hash("sha256", $body) . chr(34);
header("ETag: " . $etag);
echo $body;
Example 2: Another Case
Require If-Match on updates and return 412 when the client's revision is stale.
<?php
$ifMatch = chr(34) . "old" . chr(34); $current = chr(34) . "new" . chr(34);
if (!hash_equals($current, $ifMatch)) { http_response_code(412); echo "Precondition Failed"; }
Practical Example: Putting It to Use
A matching ETag is not enough if another writer can update between check and write.
<?php
$etag = chr(34) . "version-8" . chr(34); $received = chr(34) . "version-8" . chr(34);
var_dump(hash_equals($etag, $received));
// The conditional check and database update must be atomic.
Important Behavior and Edge Cases
Check the supplied validator against the current resource version before mutation and return 412 on mismatch.
Comparison with Related Functions or Approaches
| Option | What it means in practice |
|---|---|
| Implementing Optimistic Concurrency with ETags | HTTP ETags allow conditional updates with If-Match so clients do not overwrite concurrent changes. |
| Related approach | Database optimistic locking enforces the same principle through version columns. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring the important boundary for Implementing Optimistic Concurrency with ETags | Check the supplied validator against the current resource version before mutation and return 412 on mismatch. |
| Assuming a related mechanism has the same behavior | Database optimistic locking enforces the same principle through version columns. |
Key Takeaways
- HTTP ETags allow conditional updates with If-Match so clients do not overwrite concurrent changes.
- Check the supplied validator against the current resource version before mutation and return 412 on mismatch.
- Database optimistic locking enforces the same principle through version columns.
Before adapting these examples, verify the return values, test the failure paths and confirm that your application meets its security and environment requirements.