How to check if a string is base64 valid in PHP

后端 未结 18 1278
执笔经年
执笔经年 2020-12-13 03:41

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

18条回答
  •  抹茶落季
    2020-12-13 04:15

    MOST ANSWERS HERE ARE NOT RELIABLE

    In fact, there is no reliable answer, as many non-base64-encoded text will be readable as base64-encoded, so there's no default way to know for sure.

    Further, it's worth noting that base64_decode will decode many invalid strings For exmaple, and is not valid base64 encoding, but base64_decode WILL decode it. As jw specifically. (I learned this the hard way)

    That said, your most reliable method is, if you control the input, to add an identifier to the string after you encode it that is unique and not base64, and include it along with other checks. It's not bullet-proof, but it's a lot more bullet resistant than any other solution I've seen. For example:

    function my_base64_encode($string){
      $prefix = 'z64ENCODEDz_';
      $suffix = '_z64ENCODEDz';
      return $prefix . base64_encode($string) . $suffix;
    }
    
    function my_base64_decode($string){
      $prefix = 'z64ENCODEDz_';
      $suffix = '_z64ENCODEDz';
      if (substr($string, 0, strlen($prefix)) == $prefix) {
        $string = substr($string, strlen($prefix));
      }
      if (substr($string, (0-(strlen($suffix)))) == $suffix) {
        $string = substr($string, 0, (0-(strlen($suffix))));
      }
          return base64_decode($string);
    }
    
    function is_my_base64_encoded($string){
      $prefix = 'z64ENCODEDz_';
      $suffix = '_z64ENCODEDz';
      if (strpos($string, 0, 12) == $prefix && strpos($string, -1, 12) == $suffix && my_base64_encode(my_base64_decode($string)) == $string && strlen($string)%4 == 0){
        return true;
      } else {
        return false;
      }
    }
    

提交回复
热议问题