Skip to content

Core\Uri::decodeComponent

Core\Uri::decodeComponent(string $s): bytesCore\Uri::decodeComponent(
    string $s,
): bytes

Reads one escaped part of a link back to the characters it was written from.

A link can only contain some characters, so the others are written as escapes: a % and two hex digits for each byte. Core\Uri::decodeComponent("caf%C3%A9%20menu") returns café menu. A + stays a +. A % that is not followed by two hex digits is kept as it is.

The result is bytes, because an escape can give any byte, and some bytes are not valid text. as string converts the result to text and throws an error when it is not valid. as ?string gives null instead. Core\Uri::encodeComponent writes the escapes that this function reads.

The examples below read a file name from a link, show that a + is kept, and check a file name from a request before a server uses it.

Parameters

  • $sstringThe text to decode.

Return value

Returns bytes. The decoded bytes, as bytes, because an escape can give any byte. as string converts them to text and throws an error when they are not valid UTF-8. A % that is not followed by two hex digits is kept, so 100% returns 100%.

Examples

A file name in a link

<?nvs
// Shows how to read a file name back from the escaped form it has in a link.
string $inLink = 'report%202026%20%28final%29.pdf';
// `Core\Uri::decodeComponent` replaces each escape with its character, and returns `bytes`.
// `as string` converts the result to text.
string $name = Core\Uri::decodeComponent($inLink) as string;
// `%20` is a space, `%28` is `(` and `%29` is `)`.
// This prints report 2026 (final).pdf.
echo $name, "\n";
Output
report 2026 (final).pdf

A plus stays a plus

<?nvs
// Shows that `Core\Uri::decodeComponent` keeps a `+` as a `+`.
// A path segment can contain a `+`. Here it is part of the name of a page.
string $segment = 'C++%20tips';
// This prints C++ tips.
echo (Core\Uri::decodeComponent($segment) as string), "\n";
// A form value uses `+` for a space. `Core\Uri::decodeFormValue` reads it that way.
// This prints C tips.
echo (Core\Uri::decodeFormValue($segment) as string), "\n";
Output
C++ tips
C tips

Check a path segment before using it

<?nvs
// Shows how a server reads a file name from a request path and checks that it is valid text.
// In a web request, these names come from the address the visitor opened,
// such as /files/caf%C3%A9.txt.
array<string> $segments = ['caf%C3%A9.txt', '%FF%FE.txt'];
foreach ($segments as string $segment) {
bytes $name = Core\Uri::decodeComponent($segment);
// An escape can give any byte, and some bytes are not valid text.
// `as ?string` gives `null` for them, so the server can reply with an error.
?string $text = $name as ?string;
if ($text == null) {
echo "400 Bad Request: the file name is not valid text\n";
} else {
echo '200 OK: ', $text, "\n";
}
}
Output
200 OK: café.txt
400 Bad Request: the file name is not valid text