Detect base64 encoding in PHP?

2019-01-14 06:12发布

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 that needs to be updated. I'd like to reset their cookie if the text has not yet been encoded, otherwise leave it alone.

11条回答
干净又极端
2楼-- · 2019-01-14 06:54

Here's my solution:

if(empty(htmlspecialchars(base64_decode($string, true)))) { return false; }

It will return false if the decoded $string is invalid, for example: "node", "123", " ", etc.

查看更多
爷的心禁止访问
3楼-- · 2019-01-14 07:00

May be it's not exactly what you've asked for. But hope it'll be usefull for somebody.

In my case the solution was to encode all data with json_encode and then base64_encode.

$encoded=base64_encode(json_encode($data));

this value could be stored or used whatever you need. Then to check if this value isn't just a text string but your data encoded you simply use

function isData($test_string){
   if(base64_decode($test_string,true)&&json_decode(base64_decode($test_string))){
      return true;
   }else{
    return false;
   }

or alternatively

function isNotData($test_string){
   if(base64_decode($test_string,true)&&json_decode(base64_decode($test_string))){
      return false;
   }else{
    return true;
   }

Thanks to all previous answers authors in this thread:)

查看更多
相关推荐>>
4楼-- · 2019-01-14 07:01

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;
  }
}
查看更多
ゆ 、 Hurt°
5楼-- · 2019-01-14 07:02

We can combine three things into one function to check if given string is a valid base 64 encoded or not.

function validBase64($string)
{
    $decoded = base64_decode($string, true);

    // Check if there is no invalid character in string
    if (!preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $string)) return false;

    // Decode the string in strict mode and send the response
    if (!base64_decode($string, true)) return false;

    // Encode and compare it to original one
    if (base64_encode($decoded) != $string) return false;

    return true;
}
查看更多
我欲成王,谁敢阻挡
6楼-- · 2019-01-14 07:03

Your best option is:

$base64_test = mb_substr(trim($some_base64_data), 0, 76);
return (base64_decode($base64_test, true) === FALSE ? FALSE : TRUE);
查看更多
登录 后发表回答