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 namespace App\Models;
Auto-pruning old records with Laravel's Prunable
pruning
eloquent
cleanup
Intermediate
5 steps
typescript
type RGB = { r: number; g: number; b: number }; function parseHex(hex: string): RGB { const normalized = hex.replace(/^#/, "").trim();
Lightening and darkening hex colors in TypeScript
bitwise
color-manipulation
parsing
Intermediate
9 steps
javascript
const legacyRedirects = [ { from: '/blog/:slug', to: '/articles/:slug' }, { from: '/shop/product/:id', to: '/store/items/:id' }, { from: '/about-us', to: '/about' },
How redirects work in Next.js config
redirects
routing
configuration
Intermediate
7 steps
php
<?php namespace App\Http\Controllers;
Building a multi-step onboarding wizard in Laravel
session-state
validation
multi-step-forms
Intermediate
9 steps
php
<?php namespace App\Listeners;
Generating responsive images in a Laravel listener
queued jobs
event listeners
image processing
Intermediate
7 steps
php
final class InvoiceCalculator { private const SCALE = 4;
Precise money math with PHP's BCMath
bcmath
arbitrary precision
money
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/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.