萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 生成隨機字串的兩種實用函數

函數一:高度可配置的 rand_string()

<?php
/**
 * 產生隨機字串
 *
 * @param int    $len      長度(預設 30)
 * @param int    $type     字元集類型:0=字母數字, 1=純數字, 2=大寫, 3=小寫, 4=混合模式
 * @param string $addChars 額外允許字元
 * @return string
 */
function rand_string(int $len = 30, int $type = 0, string $addChars = ''): string {
    switch ($type) {
        case 0: $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' . $addChars; break;
        case 1: $chars = str_repeat('0123456789', 3); break;
        case 2: $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' . $addChars; break;
        case 3: $chars = 'abcdefghijklmnopqrstuvwxyz' . $addChars; break;
        default:
            // 預設排除易混淆字元 oOLl01
            $chars = 'ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789' . $addChars;
    }

    if ($len > 10) {
        $chars = ($type == 1) ? str_repeat($chars, $len) : str_repeat($chars, 5);
    }

    if ($type != 4) {
        $chars = str_shuffle($chars);
        return substr($chars, 0, $len);
    }

    // 模式 4:逐字隨機挑選(允許重複)
    $result = '';
    for ($i = 0; $i < $len; $i++) {
        $result .= $chars[mt_rand(0, strlen($chars) - 1)];
    }
    return $result;
}

// 使用範例
echo rand_string();           // 預設 30 字元,排除易混淆字元
echo rand_string(6, 1);       // 6 位數字驗證碼
echo rand_string(8, 0, '@#$'); // 含特殊符號的密碼
?>

函數二:簡易帶分隔符的 generateWeirdStr()

<?php
function generateWeirdStr(int $var = 0): string {
    $table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    $len = mt_rand(30, 30 + $var);
    $text = '';
    for ($i = 0; $i < $len; $i++) {
        $ch = $table[mt_rand(0, 61)];
        $text .= ($i > 0) ? '|' . $ch : $ch;
    }
    return $text;
}

echo generateWeirdStr(15); // 例:K|9|f|2|...
?>

應用場景:反采集干擾

在內容頁面隨機插入不可見字元(<span style="display:none">...</span>)或偽造隱藏欄位,干擾採集器解析。配合 IP 限流、User-Agent 檢查、行為分析可構建多層防護。

安全性提醒

  • 若用於 Token、密碼重設碼等安全敏感場景,必須使用 random_bytes() / random_int()(PHP 7+),上述函數僅適用於非加密用途。
  • 避免使用 rand()、mt_rand() 生成加密金鑰,其輸出可預測。
copyright © 萬盛學電腦網 all rights reserved