Url encoding


URL(s) can only be sent over the Internet using the ASCII character-set. Often especial when we generate when automatically generating url(s) we need to make sure that contains only ASCII character-set

To ensure that our url(s) contain all the time only allowed characters we can encode url(s). For this PHP has few handy functions (like urlencode, rawurlencode) that make all work for us.

Basically this functions convert all non-ASCII characters to a valid ASCII format. Also url must not contain spaces, space character will be converted to "+" or "%20" text, depends what functions we use to encode url(s). Let(s) take few example, for URL: "http://magic-software.ro/search/word/design pattern"

    echo 'http://magic-software.ro/search/word/'.urlencode('design pattern');
    //will output: 'http://magic-software.ro/search/word/design+pattern'
    //function with can decode url is urldecode 

Now if we use function rawurlencode for this url we will se that rawurlencode encode space character with "%20" and urlencode with "+"

    echo 'http://magic-software.ro/search/word/'.urlencode('design pattern');
    //will output: 'http://magic-software.ro/search/word/design+pattern'
    echo 'http://magic-software.ro/search/word/'.rawurlencode('design pattern');
    //will output: 'http://magic-software.ro/search/word/design%20pattern'

Reverse function for "rawurlencode" is "rawurldecode" and for "urlencode" is "urldecode". Also depending on your PHP version some Superglobals variables like $_GET or $_REQUEST are url decoded as default by PHP, so when attempting to decode an url allready decoded unexpected results could appear.

Add comment