Skip to content

15: Percent-Encode WHATWG URL Components

Encode a filename as a single path segment and a phrase as form query data. Each component has its own percent-encoding rules.

  • PHP 8.6 CLI. Confirm the version with php --version.
  • The uri extension.
  • Review the previous chapter if you’re following the series in order.

Allow about 10 minutes for the walkthrough and exercise.

A runnable url-percent-encoding.php example.

Run the following from the root of the Code with PHP repository.

Terminal window
php code/php-8-6/15-url-percent-encoding/url-percent-encoding.php
url-percent-encoding.php
<?php
declare(strict_types=1);
use Uri\WhatWg\UrlPercentEncodingMode;
use function Uri\WhatWg\url_percent_encode;
echo url_percent_encode('maps/Hobart north.svg', UrlPercentEncodingMode::PathSegment), PHP_EOL;
echo url_percent_encode('Hobart & coast', UrlPercentEncodingMode::FormQuery), PHP_EOL;
maps%2FHobart%20north.svg
Hobart+%26+coast

PathSegment encodes a slash contained within the segment. FormQuery follows form encoding, including a plus sign for spaces. Encode each raw component once and join the resulting URL structure separately.

Encode A+B C with FormQuery. Check that the literal plus becomes %2B while the space becomes +.

Continue with Establish a Shared Key with X-Wing and ML-KEM-768.