PHP URL Encode example
2 minsPHP contains two inbuilt functions called urlencode()
and rawurlencode()
to encode a string so that it can be placed inside the query part or the path segment of a URL.
The urlencode() function
# Syntax
urlencode (string $str) : string
The urlencode()
function converts a string to URL encoded format by replacing all non-alphanumeric characters except -
and _
with a percent (%
) sign followed by two hex digits.
It converts the space character to plus sign (+
) according to application/x-www-form-urlencoded MIME format. It follows RFC 1738.
Example
<?php
echo urlencode("Hellö Wörld") . "\n";
?>
# Output
Hell%C3%B6+W%C3%B6rld
The rawurlencode() function
The rawurlencode()
function encodes URLs according to the latest RFC 3986. Unlike urlencode()
function, it encodes space character to %20
instead of plus sign (+
)
# Syntax
rawurlencode (string $str) : string
As per RFC 3986, It returns a string in which all non-alphanumeric characters except -
, _
, .
, ~
are replaced with a percent (%) sign followed by two hex digits.
If you’re confused which function you should use for encoding URLs, just go ahead with rawurlencode()
.
Example
<?php
echo rawurlencode("Hellö Wörld") . "\n";
?>
# Output
Hell%C3%B6%20W%C3%B6rld
Also Read: URL Decode PHP Example