文章評論增加驗證碼

@zgcwkj  2025年03月24日

分類:

代碼 網站 

為 Typecho 評論系統,增加驗證碼功能代碼。可以過濾大部分垃圾評論~

理論所有主題都可以用

編輯 functions.php 文件:

/*
 * 在初始化皮膚函數時調用
 */
function themeInit($archive) {
    //檢查評論數據
    Typecho_Plugin::factory('Widget_Feedback')->comment = 'validateCaptcha';
}

/*
 * 生成評論驗證碼
 */
function generateCaptcha() {
    //啟動會話
    session_start();
    //隨機數字
    $num1 = rand(1, 9);
    $num2 = rand(1, 9);
    //隨機選擇一個運算符
    $operations = ['+','-','*'];
    $operation = $operations[rand(0, 2)];
    //根據運算符計算答案
    switch ($operation) {
        case '+':
            $answer = $num1 + $num2;
            break;
        case '-':
            //保證結果為正數
            if ($num1 < $num2) {
                $temp = $num1;
                $num1 = $num2;
                $num2 = $temp;
            }
            $answer = $num1 - $num2;
            break;
        case '*':
            $answer = $num1 * $num2;
            break;
    }
    //存儲數據
    $_SESSION['captcha'] = $answer;
    //輸出公式
    echo "$num1 $operation $num2";
}

/*
 * 驗證評論驗證碼
 */
function validateCaptcha($comment) {
    //啟動會話
    session_start();
    //獲取存儲的驗證碼
    $sessionCaptcha = isset($_SESSION['captcha']) ? $_SESSION['captcha'] : '';
    //獲取用戶提交的驗證碼
    $userCaptcha = isset($_POST['captcha']) ? trim($_POST['captcha']) : '';
    if ($userCaptcha != $sessionCaptcha) {
        throw new Typecho_Exception('驗證碼錯誤,請重新輸入。');
    }
    //驗證通過後清除驗證碼
    unset($_SESSION['captcha']);
    //繼續處理評論
    return $comment;
}

comments.php 文件的適當位置增加以下代碼:

<span>
<label for="captcha" class="required"><?php _e('驗證碼'); ?></label>
<input type="number" name="captcha" id="captcha" class="text" placeholder="<?php generateCaptcha(); ?>" />
</span>
刷新頁面,不出意外就出驗證碼輸入框了


評論已關閉

Top