How to check if a string is base64 valid in PHP

I have a string and want to test using PHP if it's a valid base64 encoded or not.


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';
}

You can use this function:

 function is_base64($s)
{
      return (bool) preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $s);
}

Just for strings, you could use this function, that checks several base64 properties before returning true:

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;
}

This code should work, as the decode function returns FALSE if the string is not valid:

if (base64_decode($mystring, true)) {
    // is valid
} else {
    // not valid
}

You can read more about the base64_decode function in the documentation.