osomanden
osomanden

Reputation: 643

string base64_encode/decode fails?

I have this script:

    function is_base64($s){
        // Check if there are valid base64 characters
        if (!preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $s)) return false;

        // Decode the string in strict mode and check the results
        $decoded = base64_decode($s, true);
        if(false === $decoded) return false;

        // Encode the string again
        if(base64_encode($decoded) != $s) return false;

        return true;
    }

called by is_base64($input)

where $input is two strings I try to test against the function.

This is reported ok : !!K0deord*test

This is reported not ok : Kilroy2P4All

What could be the difference that makes it return false?

Upvotes: 1

Views: 3515

Answers (1)

Sverri M. Olsen
Sverri M. Olsen

Reputation: 13283

You are decoding the value using the $strict argument, which means that the regular expression is not needed (the decoding will simply fail if there are invalid characters in the string).

Encoding the decoded string is also not needed. If the encoded string is successfully decoded then it is valid; encoding it again does not change the validity of anything.

Something like this should be sufficient to validate a base64-encoded string:

function is_base64($s) {
    return ! (base64_decode($s, true) === false);
}

It simply decodes the value and then returns whether or not it succeeded or failed.

Upvotes: 3

Related Questions