How to check if a string is base64 valid in PHP How to check if a string is base64 valid in PHP php php

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


You can use this function:

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


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.