urlencode()

urlencode() — URL-encodes string.

Built-in function of PHP 8.5. The manual lists it as available in PHP 4, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.

What it does

This function is convenient when encoding a string to be used in a query part of a URL, as a convenient way to pass variables to the next page.

Signature

urlencode(string $string): string

Parameters

ParameterTypeWhat it takes
$stringstringThe string to be encoded.

Return value

Returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs. It is encoded the same way that the posted data from a WWW form is encoded, that is the same way as in application/x-www-form-urlencoded media type. This differs from the RFC 3986 encoding (see rawurlencode()) in that for historical reasons, spaces are encoded as plus (+) signs.

Example

A runnable snippet:

$userinput = 'Data123!@-_ +'; echo "UserInput: $userinput\n"; echo '<a href="mycgi?foo=', urlencode($userinput), '">';

Output:

UserInput: Data123!@-_ + <a href="mycgi?foo=Data123%21%40-_+%2B">

See also

urldecode(), htmlentities(), rawurlencode(), rawurldecode()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page urlencode() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.