Detect base64 encoding in PHP?

后端 未结 12 1913
鱼传尺愫
鱼传尺愫 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:51

    We can combine three things into one function to check if given string is a valid base 64 encoded or not.

    function validBase64($string)
    {
        $decoded = base64_decode($string, true);
    
        // Check if there is no invalid character in string
        if (!preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $string)) return false;
    
        // Decode the string in strict mode and send the response
        if (!$decoded) return false;
    
        // Encode and compare it to original one
        if (base64_encode($decoded) != $string) return false;
    
        return true;
    }
    

提交回复
热议问题