php
70 lines · 9 steps
HTTP content negotiation in PHP
Parse an Accept header, rank its media types by quality, and pick the best match your server can offer.
Explained by
highlit
1<?php
2
3namespace App\Http;
4
5final class ContentNegotiator
6{
7 public function __construct(private array $supported = ['application/json', 'application/xml', 'text/html'])
8 {
9 }
10
11 public function best(?string $acceptHeader): ?string
12 {
13 $candidates = $this->parse($acceptHeader ?? '*/*');
14
15 foreach ($candidates as $candidate) {
16 foreach ($this->supported as $offered) {
17 if ($this->matches($candidate['type'], $offered)) {
18 return $offered;
19 }
20 }
21 }
22
23 return null;
24 }
25
26 private function parse(string $header): array
27 {
28 $accepted = [];
29
30 foreach (explode(',', $header) as $index => $part) {
31 $segments = array_map('trim', explode(';', $part));
32 $type = strtolower(array_shift($segments));
33
34 if ($type === '') {
35 continue;
36 }
37
38 $quality = 1.0;
39 foreach ($segments as $segment) {
40 if (str_starts_with($segment, 'q=')) {
41 $quality = (float) substr($segment, 2);
42 }
43 }
44
45 $accepted[] = ['type' => $type, 'q' => $quality, 'order' => $index];
46 }
47
48 usort($accepted, static function (array $a, array $b): int {
49 return $b['q'] <=> $a['q'] ?: $a['order'] <=> $b['order'];
50 });
51
52 return array_values(array_filter($accepted, static fn (array $a): bool => $a['q'] > 0.0));
53 }
54
55 private function matches(string $accepted, string $offered): bool
56 {
57 if ($accepted === '*/*') {
58 return true;
59 }
60
61 [$acceptedType, $acceptedSub] = explode('/', $accepted) + [1 => '*'];
62 [$offeredType] = explode('/', $offered);
63
64 if ($acceptedSub === '*') {
65 return $acceptedType === $offeredType;
66 }
67
68 return $accepted === $offered;
69 }
70}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Content negotiation ranks the client's stated preferences against what the server actually supports.
- 2The q parameter and header order together define preference, so both must feed the sort.
- 3Wildcard media types like */* and type/* need explicit matching rules beyond string equality.
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
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
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/http-content-negotiation-in-php-explained-php-fedc/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.