Skip to content

Commit f6c094a

Browse files
committed
过滤乱码后的可读文本
1 parent 2297d38 commit f6c094a

1 file changed

Lines changed: 70 additions & 0 deletions

File tree

app/Proxy/Service/MySQLProxyService.php

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -756,7 +756,12 @@ public function onReceive(\Swoole\Server $server, int $fd, int $reactorId, strin
756756

757757
$dataBase64 = base64_encode($data);
758758
$dataBase64Md5 = md5($dataBase64);
759+
760+
// 提取可读文本,过滤乱码
761+
$readableText = $this->extractReadableText($data);
762+
759763
LogEnum::base64DataByClientSendProxy->getLogger('onReceive')->debug('收到客户端数据', [
764+
'readable_text' => $readableText, // 过滤乱码后的可读文本
760765
'data_base64' => $dataBase64,
761766
'data_base64_md5' => $dataBase64Md5,
762767
'getAuthPluginData' => $context ? base64_encode($context->getAuthPluginData()) : null,
@@ -855,6 +860,71 @@ public function onReceive(\Swoole\Server $server, int $fd, int $reactorId, strin
855860
}
856861
}
857862

863+
/**
864+
* 从二进制数据中提取可显示的文本,过滤乱码
865+
*/
866+
private function extractReadableText(string $data): string
867+
{
868+
$readable = '';
869+
870+
// 遍历每个字节
871+
for ($i = 0; $i < strlen($data); $i++) {
872+
$byte = ord($data[$i]);
873+
874+
// 可打印的 ASCII 字符 (32-126)
875+
if ($byte >= 32 && $byte <= 126) {
876+
$readable .= $data[$i];
877+
}
878+
// 制表符、换行符等控制字符 (9-13)
879+
elseif ($byte >= 9 && $byte <= 13) {
880+
$readable .= $data[$i];
881+
}
882+
// 尝试检测 UTF-8 多字节字符
883+
elseif ($byte >= 0xC0 && $byte <= 0xDF) {
884+
// 2字节UTF-8
885+
if ($i + 1 < strlen($data)) {
886+
$byte2 = ord($data[$i + 1]);
887+
if ($byte2 >= 0x80 && $byte2 <= 0xBF) {
888+
$char = $data[$i] . $data[$i + 1];
889+
if (mb_check_encoding($char, 'UTF-8')) {
890+
$readable .= $char;
891+
$i++;
892+
}
893+
}
894+
}
895+
} elseif ($byte >= 0xE0 && $byte <= 0xEF) {
896+
// 3字节UTF-8
897+
if ($i + 2 < strlen($data)) {
898+
$byte2 = ord($data[$i + 1]);
899+
$byte3 = ord($data[$i + 2]);
900+
if ($byte2 >= 0x80 && $byte2 <= 0xBF && $byte3 >= 0x80 && $byte3 <= 0xBF) {
901+
$char = $data[$i] . $data[$i + 1] . $data[$i + 2];
902+
if (mb_check_encoding($char, 'UTF-8')) {
903+
$readable .= $char;
904+
$i += 2;
905+
}
906+
}
907+
}
908+
} elseif ($byte >= 0xF0 && $byte <= 0xF7) {
909+
// 4字节UTF-8
910+
if ($i + 3 < strlen($data)) {
911+
$byte2 = ord($data[$i + 1]);
912+
$byte3 = ord($data[$i + 2]);
913+
$byte4 = ord($data[$i + 3]);
914+
if ($byte2 >= 0x80 && $byte2 <= 0xBF && $byte3 >= 0x80 && $byte3 <= 0xBF && $byte4 >= 0x80 && $byte4 <= 0xBF) {
915+
$char = $data[$i] . $data[$i + 1] . $data[$i + 2] . $data[$i + 3];
916+
if (mb_check_encoding($char, 'UTF-8')) {
917+
$readable .= $char;
918+
$i += 3;
919+
}
920+
}
921+
}
922+
}
923+
}
924+
925+
return $readable;
926+
}
927+
858928
/**
859929
* 处理连接关闭事件
860930
*/

0 commit comments

Comments
 (0)