文章评论增加验证码

@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