海胖博客一直都是开放注册,但自从博客弄好邮件系统之后,每天都会有大量新用户注册邮件发到我邮箱,非常讨厌。正所谓,兵来将挡,水来土掩。对付机器注册,最好的方法莫过于加上一些需要智商才能解决的验证码了!

效果如上,代码如下,把下面的代码放到主题模板下的 function.php 中就行了。当然,懂PHP的小伙伴还可以对此代码进行拓展,弄出更复杂的验证。这下应该不会有机器注册了吧?还得观察几天~

代码

if(!class_exists('register_capatcha')) {
    class register_capatcha {
        function __construct() {
            add_action('register_form', array(& $this, 'print_capatcha'));
            add_filter('register_post', array(& $this, 'preprocess_register'));
        }
        function print_capatcha() {
            session_start();
            $rand_1 = mt_rand(1,20);
            $rand_2 = mt_rand(1,20);
            $_SESSION['capatcha_register'] = $rand_1 + $rand_2;

            $str  = '<div id="capatcha-area"><label>';
            $str .= "{$rand_1} + {$rand_2} = ".'<input type="text" name="capatcha" id="capatcha" />';
            $str .= '</label></div>';

            echo $str;
        }
        function preprocess_register($registerdata) {
            session_start();
            $capatcha = $_SESSION['capatcha_register'];
            if($capatcha != $_POST['capatcha']){
                    wp_die( __('提示:计算出错啦,请返回重新计算。') );
            }
            unset($_SESSION['capatcha_register']);
            return $registerdata;
        }
    }

}

if( !isset($register_capatcha) ) {
    $register_capatcha =& new register_capatcha();
}
转载保留版权:http://haipz.com/blog/i/6058 - 海胖博客