Detect base64 encoding in PHP?

后端 未结 12 1912
鱼传尺愫
鱼传尺愫 2020-12-05 02:10

Is there some way to detect if a string has been base64_encoded() in PHP?

We\'re converting some storage from plain text to base64 and part of it lives in a cookie

12条回答
  •  难免孤独
    2020-12-05 02:47

    I was about to build a base64 toggle in php, this is what I did:

    function base64Toggle($str) {
        if (!preg_match('~[^0-9a-zA-Z+/=]~', $str)) {
            $check = str_split(base64_decode($str));
            $x = 0;
            foreach ($check as $char) if (ord($char) > 126) $x++;
            if ($x/count($check)*100 < 30) return base64_decode($str);
        }
        return base64_encode($str);
    }
    

    It works perfectly for me. Here are my complete thoughts on it: http://www.albertmartin.de/blog/code.php/19/base64-detection

    And here you can try it: http://www.albertmartin.de/tools

提交回复
热议问题