Skip to content

Core\Uri::decodeFormValue

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

Reads one value of a form back to the characters it was written from.

A form value, such as a value in a query string or in the body of a POST request, is written with escapes. A + is a space, and a % and two hex digits give one byte. Core\Uri::decodeFormValue("red+shoes+%26+bags") returns red shoes & bags. %2B gives a real +. 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::encodeFormValue writes the escapes that this function reads.

The examples below read a search text from a link, show how a + and %2B are read, and read a saved setting from a cookie.

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 search text from a link

<?nvs
// Shows how to read a search text back from the escaped form it has in a link.
string $inLink = 'red+shoes+%26+bags';
// `Core\Uri::decodeFormValue` replaces each `+` with a space and each escape with its
// character. It returns `bytes`, and `as string` converts the result to text.
string $search = Core\Uri::decodeFormValue($inLink) as string;
// `%26` is `&`. This prints red shoes & bags.
echo $search, "\n";
Output
red shoes & bags

A plus and an escaped plus

<?nvs
// Shows how `Core\Uri::decodeFormValue` reads a `+`, the escape `%2B` and a broken escape.
// A `+` is a space, and `%2B` is a real `+`. This prints 1+1 = 2.
echo (Core\Uri::decodeFormValue('1%2B1+%3D+2') as string), "\n";
// `%20` is also a space. This prints a b.
echo (Core\Uri::decodeFormValue('a%20b') as string), "\n";
// A `%` without two hex digits after it is kept. This prints 100%.
echo (Core\Uri::decodeFormValue('100%') as string), "\n";
Output
1+1 = 2
a b
100%

A saved setting in a cookie

<?nvs
// Shows how a server reads the last search of a user from a cookie, and checks that it is valid text.
// In a web request, these values come from the `Cookie` header. The second one was changed
// by the visitor, and its bytes are not valid text.
array<string> $cookies = ['S%C3%A3o+Paulo+hotels', '%FF%FE'];
foreach ($cookies as string $cookie) {
// `as ?string` gives `null` when the bytes are not valid text.
// The server then shows an empty search box.
?string $search = Core\Uri::decodeFormValue($cookie) as ?string;
if ($search == null) {
echo "search box: (empty)\n";
} else {
echo 'search box: ', $search, "\n";
}
}
Output
search box: São Paulo hotels
search box: (empty)