How to check if a string is base64 valid in PHP

I realise that this is an old topic, but using the strict parameter isn’t necessarily going to help.

Running base64_decode on a string such as “I am not base 64 encoded” will not return false.

If however you try decoding the string with strict and re-encode it with base64_encode, you can compare the result with the original data to determine if it’s a valid bas64 encoded value:

if ( base64_encode(base64_decode($data, true)) === $data){
    echo '$data is valid';
} else {
    echo '$data is NOT valid';
}

Leave a Comment