15: Percent-Encode WHATWG URL Components
Overview
Section titled “Overview”Encode a filename as a single path segment and a phrase as form query data. Each component has its own percent-encoding rules.
Prerequisites
Section titled “Prerequisites”- PHP 8.6 CLI. Confirm the version with
php --version. - The
uriextension. - Review the previous chapter if you’re following the series in order.
Allow about 10 minutes for the walkthrough and exercise.
What You’ll Build
Section titled “What You’ll Build”A runnable url-percent-encoding.php example.
Step 1: Run the example (~5 min)
Section titled “Step 1: Run the example (~5 min)”Run the following from the root of the Code with PHP repository.
php code/php-8-6/15-url-percent-encoding/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;Expected Result
Section titled “Expected Result”maps%2FHobart%20north.svgHobart+%26+coastWhy It Works
Section titled “Why It Works”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.
Exercise
Section titled “Exercise”Encode A+B C with FormQuery. Check that the literal plus becomes %2B while the space becomes +.
Wrap-up
Section titled “Wrap-up”Continue with Establish a Shared Key with X-Wing and ML-KEM-768.