PHP URL Encoding
A URL is made of components with different roles. Build a query from validated values rather than joining raw request text into a destination.
How it works
rawurlencode is useful for an individual path or query value under its encoding contract. http_build_query assembles a query from a structured array, and PHP_QUERY_RFC3986 chooses percent-encoding for spaces. Neither operation approves the destination host or turns arbitrary input into a safe redirect. After constructing a URL for an HTML attribute, HTML-encode that complete attribute value as well.
Run it locally
Run this complete source locally with PHP 8.2 or newer. Save it using the filename shown and run the command below. PHP is not currently available in Bhylu’s browser playground. Apache and MySQL are not needed for an ordinary CLI example.
php -l url-encoding.php
php url-encoding.phpDownload this source as a local PHP lab file. Keep lab files separate from the Bhylu project and production data.
Example
<?php
declare(strict_types=1);
$query = http_build_query(["item"=>"Hand drill","page"=>2], "", "&", PHP_QUERY_RFC3986);
echo "/catalogue?", $query, "\n";
echo rawurlencode("Hand drill"), "\n";
Expected result
/catalogue?item=Hand%20drill&page=2
Hand%20drillThe space belongs to the value rather than separating URL structure, so it is encoded. The ampersand between fields is actual query syntax supplied by the builder. Encoding the whole URL with rawurlencode would also encode its separators and answer a different question.
Check the official PHP manual for detailed version and API contracts.