简体   繁体   中英

base64 encoding/decoding in php

I have implemented a cookie mechanism in my site. All cookies that i wanted to store are in a array with their TTL, value, name ...

When i want to set the cookie, i serialize the tab, then i gzcompress and finally i base64_encode

base64_encode(gzcompress(serialize($array)))

My problem is sometime, when i get the cookie with

$_COOKIE[name]

the base64_encoded string is all in lowercase characters.

So my question is : - is that possible that all characters are in lowercase format (base64_encoded)

Or maybe i'am doing something wrong but the problem does not appear all the time and i can't reproduce the bug.

Yes, a Base64-encoded string can be all lowercase. The probability of this happening (for random input data, which compressed data pretty well approximates) is about (36 / 64) 4 N / 3 , where N is the length of the input in bytes, and 4 N / 3 is thus the approximate length of the output (excluding padding).

As it happens, (36 / 64) 4 ≈ 0.100113 is very close to 1 / 10, and so, to a very good approximation, the probability that a random Base64 string contains no uppercase letters goes down by a factor of 10 for every four characters in length.

Thus, for example, a random 8-character Base64 string (corresponding to a random 6-byte input) has about a 1% chance of containing no uppercase letters, while the corresponding probability for a random 12-character Base64 string (corresponding to a random 9-byte input) is about 0.1%, and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM