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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Content negotiation ranks the client's stated preferences against what the server actually supports.
  2. 2The q parameter and header order together define preference, so both must feed the sort.
  3. 3Wildcard media types like */* and type/* need explicit matching rules beyond string equality.

Related explainers

Share this explainer

Here's the card — post it anywhere.

HTTP content negotiation in PHP — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code