I have a string and want to test using PHP if it's a valid base64 encoded or not.
In base64 encoding, the character set is [A-Z, a-z, 0-9, and + /] . If the rest length is less than 4, the string is padded with '=' characters. ^([A-Za-z0-9+/]{4})* means the string starts with 0 or more base64 groups.
PHP | base64_encode() Function. The base64_encode() function is an inbuilt function in PHP which is used to Encodes data with MIME base64. MIME (Multipurpose Internet Mail Extensions) base64 is used to encode the string in base64. The base64_encoded data takes 33% more space then original data.
The equals sign "=" represents a padding, usually seen at the end of a Base64 encoded sequence. Each group of six bits is encoded using the above conversion.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With