前言
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();?>



显示IP属地- 
                        
						                          
                            
                              
							   
 
 游客
 
                            
                              
                                淘金城镇                                
                                
                                                                Edge 119.0.0.0 Edge 119.0.0.0 Windows 10 Windows 10
 
                               
 
 
找到合适位置插入以下代码: