Detect base64 encoding in PHP?

后端 未结 12 1909
鱼传尺愫
鱼传尺愫 2020-12-05 02:10

Is there some way to detect if a string has been base64_encoded() in PHP?

We\'re converting some storage from plain text to base64 and part of it lives in a cookie

12条回答
  •  情话喂你
    2020-12-05 02:49

    Better late than never: You could maybe use mb_detect_encoding() to find out whether the encoded string appears to have been some kind of text:

    function is_base64_string($s) {
      // first check if we're dealing with an actual valid base64 encoded string
      if (($b = base64_decode($s, TRUE)) === FALSE) {
        return FALSE;
      }
    
      // now check whether the decoded data could be actual text
      $e = mb_detect_encoding($b);
      if (in_array($e, array('UTF-8', 'ASCII'))) { // YMMV
        return TRUE;
      } else {
        return FALSE;
      }
    }
    

提交回复
热议问题