Skip to content

Core\Uri::encodeFormValue

Core\Uri::encodeFormValue(string $s): stringCore\Uri::encodeFormValue(
    string $s,
): string

Escapes a text so that you can put it into a form value, such as a value in a query string or in the body of a form a browser sends.

A form is written as pairs like name=value, joined with &. Core\Uri::encodeFormValue writes a space as +. It writes every other character as a % and two hex digits, except letters, digits and -_.. Core\Uri::encodeFormValue("salt & pepper") returns salt+%26+pepper. The & and = in a value are escaped, so a value cannot start a new pair.

Core\Uri::decodeFormValue reads the text back. Core\Uri::buildQuery builds a whole query string from an array. For a path segment, use Core\Uri::encodeComponent, which writes a space as %20.

The examples below escape a value with spaces, show which characters are escaped, and build a sign-in link that sends the user back to the page they came from.

Parameters

  • $sstringThe text to encode.

Return value

Returns string. The escaped text, with upper-case hex digits. A tainted argument (text from outside the program, such as a request) gives a plain result. No byte of the result can start a new pair of the form.

Examples

A value with spaces

<?nvs
// Shows how to put a value with spaces into the query string of a link.
string $city = 'New York';
// `Core\Uri::encodeFormValue` writes each space as `+`.
// This prints /weather?city=New+York.
echo '/weather?city=', Core\Uri::encodeFormValue($city), "\n";
Output
/weather?city=New+York

Characters that are escaped

<?nvs
// Shows which characters `Core\Uri::encodeFormValue` escapes, so a value cannot change the form.
// A `&` would start a new pair, and `=` would end a name. They become `%26` and `%3D`.
// This prints salt+%26+pepper%3D1.
echo Core\Uri::encodeFormValue('salt & pepper=1'), "\n";
// A `+` means a space in a form, so a real `+` becomes `%2B`.
// This prints 1%2B1.
echo Core\Uri::encodeFormValue('1+1'), "\n";
// Letters, digits and `-_.` are not changed. A `~` becomes `%7E`.
// This prints version-2_final.txt%7E.
echo Core\Uri::encodeFormValue('version-2_final.txt~'), "\n";
Output
salt+%26+pepper%3D1
1%2B1
version-2_final.txt%7E

A sign in link that returns to the page

<?nvs
// Shows how a server builds a sign-in link that sends the user back to the page they came from.
// In a real program, this is the address of the page the user opened.
string $page = '/cart?item=42&size=L';
// `/`, `?`, `&` and `=` are escaped, so the whole address is the value of `next`.
// This prints /login?next=%2Fcart%3Fitem%3D42%26size%3DL.
echo '/login?next=', Core\Uri::encodeFormValue($page), "\n";
Output
/login?next=%2Fcart%3Fitem%3D42%26size%3DL