Search code examples
phpwebencode

Why is my PHP urlencode not functioning as examples on internet?


Why does my urlencode() produce something different than I expected?

This might be my expectations being wrong but then I would be even more puzzled.

example

urlencode("ä");

expectations = returns %C3%A4

reality = returns %E4

Where have I gone wrong in my expections? It seems to be linked to encoding. But I'm not very familiar in what I should do/use.

Should I change something on my server to that the function uses the right encoding?


Solution

  • urlencode encodes the raw bytes in your string into a percent-encoded representation. If you expect %C3%A4 that means you expect the UTF-8 byte representation of "ä". If you get %E4 that means your string is actually encoded in ISO-8859-1 instead.

    Encode your string in UTF-8 to get the expected result. How to do this depends on where this string comes from. If it's a string literal in your source code file, save the file as UTF-8 in your text editor. If it comes from a database, see UTF-8 all the way through.

    For more background information, see What Every Programmer Absolutely, Positively Needs To Know About Encodings And Character Sets To Work With Text.