phpbase64chr

different results when I encode a character to base64


When I encode a character to base64, I get different results depending on the the way I pass the character: For example, I want to encode chr(128) => €

1.passing the result of chr(): base64_encode(chr(128)) => 'gA=='
2.passing the character directly: base64_encode('€') => '4oKs'

Why are the results different?


Solution

  • chr(128) returns a 1 byte character which represents the €-sign, therefore the base64 encoded string encodes ony 1 byte (80 hexacdecimal = 128 decimal):

    echo bin2hex(base64_decode('gA=='));
    

    80

    On the other hand, in base64_encode('€') the '€' is a unicode string, and the encoded result contains 3 bytes, the unicode representation of the Euro-sign:

    echo bin2hex(base64_decode('4oKs'));
    

    E282AC