如何检查字符串在 PHP 中是否为 base64 有效

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4278106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:30:42  来源:igfitidea点击:

How to check if a string is base64 valid in PHP

phpvalidationbase64

提问by Alias

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

我有一个字符串,想使用 PHP 测试它是否是有效的 base64 编码。

回答by PottyBert

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.

在诸如“我不是 base 64 编码的”这样的字符串上运行 base64_decode 不会返回 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:

但是,如果您尝试使用严格解码字符串并使用 base64_encode 对其重新编码,则可以将结果与原始数据进行比较以确定它是否为有效的 bas64 编码值:

if ( base64_encode(base64_decode($data, true)) === $data){
    echo '$data is valid';
} else {
    echo '$data is NOT valid';
}

回答by Dennais

You can use this function:

您可以使用此功能:

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

回答by EdoDodo

This code should work, as the decode function returns FALSE if the string is not valid:

此代码应该可以工作,因为如果字符串无效,解码函数将返回 FALSE:

if (base64_decode($mystring, true)) {
    // is valid
} else {
    // not valid
}

You can read more about the base64_decode function in the documentation.

您可以在文档中阅读有关 base64_decode 函数的更多信息。

回答by Pekka

I think the only way to do that is to do a base64_decode()with the $strictparameter set to true, and see whether it returns false.

我认为唯一的方法是base64_decode()$strict参数设置为true,然后查看它是否返回false

回答by merlucin

Just for strings, you could use this function, that checks several base64 properties before returning true:

仅对于字符串,您可以使用此函数,在返回 true 之前检查几个 base64 属性:

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;

    // Encode the string again
    if(base64_encode($decoded) != $s) return false;

    return true;
}

回答by Lucio Mollinedo

This is a really old question, but I found the following approach to be practically bullet proof. It also takes into account those weird strings with invalid characters that would cause an exception when validating.

这是一个非常古老的问题,但我发现以下方法实际上是防弹的。它还考虑了那些在验证时会导致异常的带有无效字符的奇怪字符串。

    public static function isBase64Encoded($str) 
{
    try
    {
        $decoded = base64_decode($str, true);

        if ( base64_encode($decoded) === $str ) {
            return true;
        }
        else {
            return false;
        }
    }
    catch(Exception $e)
    {
        // If exception is caught, then it is not a base64 encoded string
        return false;
    }

}

I got the idea from this pageand adapted it to PHP.

我从这个页面得到了这个想法并将其改编为 PHP。

回答by Nadir Latif

I tried the following:

我尝试了以下方法:

  • base64 decode the string with strict parameter set to true.
  • base64 encode the result of previous step. if the result is not same as the original string, then original string is not base64 encoded
  • if the result is same as previous string, then check if the decoded string contains printable characters. I used the php function ctype_printto check for non printable characters. The function returns false if the input string contains one or more non printable characters.
  • base64 解码字符串,严格参数设置为 true。
  • base64 编码上一步的结果。如果结果与原始字符串不同,则原始字符串不是 base64 编码的
  • 如果结果与之前的字符串相同,则检查解码后的字符串是否包含可打印的字符。我使用 php 函数ctype_print来检查不可打印的字符。如果输入字符串包含一个或多个不可打印的字符,则该函数返回 false。

The following code implements the above steps:

以下代码实现了上述步骤:

public function IsBase64($data) {
    $decoded_data = base64_decode($data, true);
    $encoded_data = base64_encode($decoded_data);
    if ($encoded_data != $data) return false;
    else if (!ctype_print($decoded_data)) return false;

    return true;
}

The above code will may return unexpected results. For e.g for the string "json" it will return false. "json" may be a valid base64 encoded string since the number of characters it has is a multiple of 4 and all characters are in the allowed range for base64 encoded strings. It seems we must know the range of allowed characters of the original string and then check if the decoded data has those characters.

上面的代码可能会返回意想不到的结果。例如,对于字符串“json”,它将返回 false。“json”可能是有效的 base64 编码字符串,因为它的字符数是 4 的倍数,并且所有字符都在 base64 编码字符串的允许范围内。看来我们必须知道原始字符串允许的字符范围,然后检查解码后的数据是否有这些字符。

回答by Niroshan

I write this method is working perfectly on my projects. When you pass the base64 Image to this method, If it valid return true else return false. Let's try and let me know any wrong. I will edit and learn in the feature.

我写的这个方法在我的项目上运行得很好。当您将 base64 Image 传递给此方法时,如果有效则返回 true 否则返回 false。让我们试着让我知道任何错误。我将在该功能中进行编辑和学习。

/**
 * @param $str
 * @return bool
 */
private function isValid64base($str){
    if (base64_decode($str, true) !== false){
        return true;
    } else {
        return false;
    }
}

回答by liljoshu

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.

事实上,没有可靠的答案,因为许多非 base64 编码的文本都可以像 base64 编码一样可读,因此没有确定的默认方法。

Further, it's worth noting that base64_decode will decode many invalid stringsFor exmaple, andis not valid base64 encoding, but base64_decode WILL decode it. As jwspecifically. (I learned this the hard way)

此外,值得注意的是,base64_decode将解码许多无效字符串,例如,andbase64 编码无效,但 base64_decode 将对其进行解码。至于jw具体。(我经过惨痛的教训才学到这个)

That said, your most reliable method is, if you control the input, to add an identifierto 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:

也就是说,您最可靠的方法是,如果您控制输入,则在对字符串进行编码后向字符串添加一个标识符,该标识符是唯一的而非 base64,并将其与其他检查一起包含在内。它不是防弹的,但它比我见过的任何其他解决方案都更能防弹。例如:

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

回答by bilal

Alright guys... finally I have found a bullet proof solution for this problem. Use this below function to check if the string is base64 encoded or not -

好吧伙计们......最后我找到了解决这个问题的防弹解决方案。使用下面的函数来检查字符串是否是 base64 编码的 -

    private function is_base64_encoded($str) {

       $decoded_str = base64_decode($str);
       $Str1 = preg_replace('/[\x00-\x1F\x7F-\xFF]/', '', $decoded_str);
       if ($Str1!=$decoded_str || $Str1 == '') {
          return false;
       }
       return true;
    }