整理一個 C 靜態類,封裝專案高頻複用的工具方法,採用單一職責、可測試設計。
<?php
class C {
// 內部隨機字串產生器
private static function random(array $pool, int $len): string {
$out = '';
$max = count($pool) - 1;
for ($i = 0; $i < $len; $i++) {
$out .= $pool[random_int(0, $max)];
}
return $out;
}
// 純數字隨機碼
public static function randNum(int $len = 8): string {
return self::random(range('0','9'), $len);
}
// 混合字元隨機碼(可選大寫)
public static function randStr(int $len = 8, bool $upper = false): string {
$pool = array_merge(range('a','z'), range('A','Z'), range('1','9')); // 排除 0 混淆
$str = self::random($pool, $len);
return $upper ? strtoupper($str) : $str;
}
// 可逆加密(Base64 + XOR 金鑰流)—— 僅供低敏感度資料,高敏感請用 OpenSSL AES-GCM
public static function encrypt(string $data, string $key = 'default_key'): string {
$key = md5($key);
$keyStream = '';
for ($i = 0, $kl = strlen($key); $i < strlen($data); $i++) {
$keyStream .= $key[$i % $kl];
}
$cipher = '';
for ($i = 0; $i < strlen($data); $i++) {
$cipher .= chr((ord($data[$i]) + ord($keyStream[$i])) % 256);
}
return base64_encode($cipher);
}
public static function decrypt(string $data, string $key = 'default_key'): string {
$key = md5($key);
$data = base64_decode($data);
$keyStream = '';
for ($i = 0, $kl = strlen($key); $i < strlen($data); $i++) {
$keyStream .= $key[$i % $kl];
}
$plain = '';
for ($i = 0; $i < strlen($data); $i++) {
$d = ord($data[$i]) - ord($keyStream[$i]);
$plain .= chr($d < 0 ? $d + 256 : $d);
}
return $plain;
}
// 正則驗證:手機號(支援最新段號)
public static function isMobile(string $str): bool {
return (bool)preg_match('/^1(?:3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/', $str);
}
// 郵箱驗證(RFC 5322 簡化版)
public static function isEmail(string $str): bool {
return (bool)preg_match('/^[0-9a-z._%+-]+@[0-9a-z.-]+\.[a-z]{2,}$/i', $str);
}
// 身份證號(15/18 位,最後一位可為 X)
public static function isIdCard(string $str): bool {
return (bool)preg_match('/^\d{15}$|^\d{17}[\dxX]$/i', $str);
}
// 字串清理:去標籤、轉義特殊字元
public static function hStr(?string $str): string {
return $str ? addslashes(strip_tags($str)) : '';
}
}
$token = C::randStr(16); // "aB3fG7hK9mN2pQ5r"
$enc = C::encrypt('secret', 'my_key');
$dec = C::decrypt($enc, 'my_key');
C::isMobile('13800138000'); // true
C::isEmail('test@example.com'); // true
C::hStr(''); // 轉義後安全字串
encrypt/decrypt 為教學級對稱加密,生產環境請改用 openssl_encrypt (AES-256-GCM) 或 libsodium。random_int(CSPRNG),而非 rand()/mt_rand()。