[ACCEPTED]-PHP URL Encoding / Decoding-url-encoding

Accepted answer
Score: 21

The weird characters in the values passed in the URL should 8 be escaped, using urlencode().


For example, the following 7 portion of code :

echo urlencode('dsf13f3343f23/23=');

would give you :

dsf13f3343f23%2F23%3D

Which works 6 fine, as an URL parameter.


And if you want 5 to build aquery string with several parameters, take 4 a look at the http_build_query() function.

For example :

echo http_build_query(array(
    'id' => 'dsf13f3343f23/23=',
    'a' => 'plop',
    'b' => '$^@test', 
));

will 3 give you :

id=dsf13f3343f23%2F23%3D&a=plop&b=%24%5E%40test

This function deals with escaping 2 and concatenating the parameters itself 1 ;-)

Score: 4

Use PHP's urlencode() function to encode the value 8 before you put it into a URL.

string urlencode ( string $str )
This 7 function is convenient when encoding a 6 string to be used in a query part of a 5 URL, as a convenient way to pass variables 4 to the next page.

This function converts 3 "weird" characters, such as =, into 2 a format safe to put into a URL. You can 1 use it like this:

Header('Location: /index.php?id=' . urlencode($id))
Score: 4

If you use Base64 to encode the binary value 4 for the URL, there is also a variant with URL and filename safe alphabet.

You can use 3 the strtr function to translate one from alphabet to the 2 other:

$base64url = strtr($base64, '+/', '-_');
$base64 = strtr($base64url, '-_', '+/');

So you can use these functions to 1 encode and decode base64url:

function base64url_encode($str) {
    return strtr(base64_encode($str), '+/', '-_'));
}
function base64url_decode($base64url) {
    return base64_decode(strtr($base64url, '-_', '+/'));
}

See also my answer on What is a good way to produce an short alphanumeric string from a long md5 hash?

Score: 1

There is no use in encrypting parameters.
Send 1 it as is:

/index.php?id=3 

nothing wrong with it.

More Related questions