PHP: urlencode() vs. rawurlencode()
The difference between these two function is in their return values.
urlencode():
string urlencode ( string $str
)
Parameters: str[The strings to be encoded]
urlencode 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.
[ http://php.net/manual/en/function.urlencode.php]
rawurlencode():
string rawurlencode ( string $str
)
Parameters : str [The url to be encoded]
rawurlencode Returns a string in which all non-alphanumeric characters except -_.~ have been replaced with a percent (%) sign followed by two hex digits. This is the encoding described in » RFC 3986 for protecting literal characters from being interpreted as special URL delimiters, and for protecting URLs from being mangled by transmission media with character conversions (like some email systems).
[http://php.net/manual/en/function.rawurlencode.php]
So the main difference is that urlencode()
encodes space as + signs
and rawurlencode()
encodes space as %20
When we use urlencode() and rawurlencode():
Every HTTP URL conforms to the following URI syntax:
url:[//[host[:port]][/path][?query][#fragment]
- If you encode path segment, use
rawurlencode()
. - If you encode query component, use
urlencode()
.
The Example of ` urlencode
` function
<?php$segment = 'today is hot day';
$path = urlencode($segment);?><a href= "http://example.com/<?php echo $path ?>">Click here</a>
The above example will output :
<a href="http://example.com/today+is+hot+day">Click Me</a>
The Example of ` rawurlencode
` function
<?php$segment = 'today is hot day';
$path = rawurlencode ($segment);?><a href= "http://example.com/<?php echo $path ?>">Click here</a>
The above example will output :
<a href="http://example.com/today%20is%20hot%20day">Click Me</a>
[encodes space as %20]
[NB:http://php.net/manual/en/function.urlencode.php, http://php.net/manual/en/function.rawurlencode.php]