boxmoe_header_banner_img

Hello! 欢迎来到松子博客!

加载中

文章导读

Typecho评论算数验证码(代码版)


avatar
szfx_blog 2022年10月22日 2.26k

前言

Typecho添加验证码,防止垃圾评论的出现,验证码相关的插件也有很多,但我偏爱代码版,这里分享函数纯代码实现简单的算术验证码。

使用步骤

主题function.php文件添加如下代码:

//算术验证评论
function themeInit($comment){
$comment = spam_protection_pre($comment, $post, $result);
}
function spam_protection_math(){
    $num1=rand(1,49);
//数字范围,自定义修改
    $num2=rand(1,49);
    echo "验证码:<input type=\"text\" name=\"sum\" class=\"text\" value=\"\" size=\"25\" tabindex=\"4\" style=\"width:100px\" placeholder=\"$num1 + $num2 = ?\">\n";
    echo "<input type=\"hidden\" name=\"num1\" value=\"$num1\">\n";
    echo "<input type=\"hidden\" name=\"num2\" value=\"$num2\">";
}
function spam_protection_pre($comment, $post, $result){
    $sum=$_POST['sum'];
    switch($sum){
        case $_POST['num1']+$_POST['num2']:
        break;
        case null:
        throw new Typecho_Widget_Exception(_t('对不起: 请输入验证码。<a href="javascript:history.back(-1)">返回上一页</a>','评论失败'));
        break;
        default:
        throw new Typecho_Widget_Exception(_t('对不起: 验证码错误,请<a href="javascript:history.back(-1)">返回</a>重试。','评论失败'));
    }
    return $comment;
}

主题comments.php文件,找到合适位置插入以下代码:

<?php spam_protection_math();?>
感谢您的支持
微信赞赏

微信扫一扫

支付宝赞赏

支付宝扫一扫



评论(2)

查看评论列表
显示IP属地
评论头像
淘金城镇 2023年11月17日
Edge 119.0.0.0 Windows 10
找到合适位置插入以下代码:
评论头像
szfx_blog 博主 2025年11月13日
Edge 142.0.0.0 Windows 10
1231测试

发表评论

表情 颜文字

插入代码
隐藏
变装