How to check if a string is base64 valid in PHP

后端 未结 18 1281
执笔经年
执笔经年 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:02

    i know that i resort a very old question, and i tried all of the methods proposed; i finally end up with this regex that cover almost all of my cases:

    $decoded = base64_decode($string, true);
    if (0 < preg_match('/((?![[:graph:]])(?!\s)(?!\p{L}))./', $decoded, $matched)) return false;
    

    basically i check for every character that is not printable (:graph:) is not a space or tab (\s) and is not a unicode letter (all accent ex: èéùìà etc.)

    i still get false positive with this chars: £§° but i never use them in a string and for me is perfectly fine to invalidate them. I aggregate this check with the function proposed by @merlucin

    so the result:

    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;
    
      // if string returned contains not printable chars
      if (0 < preg_match('/((?![[:graph:]])(?!\s)(?!\p{L}))./', $decoded, $matched)) return false;
    
      // Encode the string again
      if(base64_encode($decoded) != $s) return false;
    
      return true;
    }
    

提交回复
热议问题