首页 > 解决方案 > 验证是否使用 base 64 和相等的问题

问题描述

我有验证行是否使用base64编码的问题,因为它的问题是相等的,为了在base64中保存数据我需要不显示相等,但同时我需要验证它的值是否使用base64编码

我使用这个功能:

function is_base64_encoded($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) print "false"; return false;

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

该功能工作正常,如果我替换“=”该功能不检测base64等问题

通过这个,我的问题是如何识别base64编码是否可以替换“=”

例如 Base64 编码:

This it´s the best car 1980
VGhpcyBpdMK0cyB0aGUgYmVzdCBjYXIgMTk4MA==

如果替换“=”,则相同的示例:

This it´s the best car 1980
VGhpcyBpdMK0cyB0aGUgYmVzdCBjYXIgMTk4MA

问题是检测它是否是 base64 编码的功能在没有“=”的情况下不起作用并显示为行不使用 Base64

通过这个我发现如果我替换“=”,我发现如何检测它是否使用Base64编码,并且我不需要显示“=”并检测是否使用Base64。

非常感谢,我希望能帮助我,问候

标签: phpbase64

解决方案


如果您使用正确的正则表达式进行测试,则不再需要编码和解码功能。使用这个功能:

function is_base64_encoded($strBase64){
  $str = preg_replace('~\s~','',$strBase64);  //remove all whitespaces
  $re = '~^(?:[a-z0-9+/]{4})*(?:[a-z0-9+/]{2}==|[a-z0-9+/]{3}=)?$~i';
  return (bool)preg_match($re,$str);
}

我从这里获取了正则表达式,稍微修改了一下,并包含了第一条评论。


推荐阅读