PHP urlencode() Function
The PHP urlencode() function is used to encode the url. The function 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.
Syntax
urlencode(string)
Parameters
string |
Required. Specify the URL 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() function) in that for historical reasons, spaces are encoded as plus (+) signs.
Example:
The example below shows the usage of urlencode() function.
<?php echo urlencode("https://www.alphacodingskills.com")."\n"; $userinput = "an online learning portal"; echo '<a href="www.alphacodingskills.com/', urlencode($userinput), '">'; ?>
The output of the above code will be:
https%3A%2F%2Fwww.alphacodingskills.com <a href="www.alphacodingskills.com/an+online+learning+portal">
Example:
Consider one more example which shows how a string is encoded and decoded.
<?php $str1 = "https://www.alphacodingskills.com"; $encoded_str1 = urlencode($str1); echo "The string is: $str1 \n"; echo "Encoded string: $encoded_str1 \n"; $str2 = "https%3A%2F%2Fwww.alphacodingskills.com"; $decoded_str2 = urldecode($str2); echo "\nThe string is: $str2 \n"; echo "Decoded string: $decoded_str2 \n"; ?>
The output of the above code will be:
The string is: https://www.alphacodingskills.com Encoded string: https%3A%2F%2Fwww.alphacodingskills.com The string is: https%3A%2F%2Fwww.alphacodingskills.com Decoded string: https://www.alphacodingskills.com
❮ PHP URLs Reference