php中判断一个字符串是否为base64编码,通常的做法为,将这个字符串进行 base64_decode 解码,然后再进行编码,再对照原有的字符串,如果相等就是BASE64编码后的字符串,如果不等就不是。注意:以上只能判断百分之60左右的base64编码后的字符串 如果遇到字符串长度比较短或者纯字母以及纯数字的话.那么这个方法就不行了。长度为1的非base64编码字符串在base64解码后的内容是空,长度为2以上非base64编码的字符串解码后是显示乱码。

//判断是否为utf8编码
public function is_utf8($str){
  $len = strlen($str);
  for($i = 0; $i < $len; $i++){
    $c = ord($str[$i]);

    if($c > 128){
      if(($c > 247)){
        return false;
      }elseif($c > 239){
        $bytes = 4;
      }elseif($c > 223){
        $bytes = 3;
      }elseif ($c > 191){
        $bytes = 2;
      }else{
        return false;
      }
      if(($i + $bytes) > $len){
        return false;
      }
      while($bytes > 1){
        $i++; $b = ord($str[$i]);
        if($b < 128 || $b > 191){
          return false;
        } $bytes--;
      }
    }

  }

  return true;
}

 

/**
* 判断是否为base64字符串
* @param [type] $str [description]
* @return [type] [description]
*/
public function str_is_base64($str){
  if ($this->is_utf8(base64_decode($str)) && base64_decode($str) != '') {
    return true;
  }
  return false;
}

// 判断是否密码为base64
if($this->str_is_base64($password)){

  $password = base64_decode($password);
}

 

 

原地址:http://180it.com/archives/1459/