WordPress代码实现给网站注册加上图片验证码功能

从体验上来讲,其实我是不想加验证码的,因为这会增加用户的操作,但有时候没有办法,为了防止机器人恶意注册,所以今天我来说一下如何给WordPress的前台注册加上验证码功能。

效果图

教程

1、在主题目录下,新建一个目录及PHP文件,如:/inc/captcha.php;加入生成验证码的代码:

<?php
    require_once(dirname(__FILE__)."/../../../../wp-load.php"); // 目录结构,如果是按照我这种目录的话则不用修改
    $font = get_template_directory()."/fonts/consolas-webfont.ttf"; // 引入验证码的字体文件,后面给出下载地址
    class Imagecode{
        private $width ;
        private $height;
        private $counts;
        private $distrubcode;
        private $fonturl;
        private $session;
        function __construct($width = 120,$height = 30,$counts = 5,$distrubcode="1235467890qwertyuipkjhgfdaszxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM",$fonturl){
            $this->width=$width;
            $this->height=$height;
            $this->counts=$counts;
            $this->distrubcode=empty($distrubcode)?"1235467890qwertyuipkjhgfdaszxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM":$distrubcode;
            $this->fonturl=$fonturl;
            $this->session=$this->sessioncode();
            session_start();
            $_SESSION['um_captcha']=$this->session;
        }
 
         function imageout(){
            $im=$this->createimagesource();
            $this->setbackgroundcolor($im);
            $this->set_code($im);
            $this->setdistrubecode($im);
            ImageGIF($im);
            ImageDestroy($im); 
        }
 
        private function createimagesource(){
            return imagecreate($this->width,$this->height);
        }
        private function setbackgroundcolor($im){
            $bgcolor = ImageColorAllocate($im, rand(200,255),rand(200,255),rand(200,255));
            imagefill($im,0,0,$bgcolor);
        }
        private function setdistrubecode($im){
            $count_h=$this->height;
            $cou=floor($count_h*2);
            for($i=0;$i<$cou;$i++){
                $x=rand(0,$this->width);
                $y=rand(0,$this->height);
                $jiaodu=rand(0,360);
                $fontsize=rand(4,6);
                $fonturl=$this->fonturl;
                $originalcode = $this->distrubcode;
                $countdistrub = strlen($originalcode);
                $dscode = $originalcode[rand(0,$countdistrub-1)];
                $color = ImageColorAllocate($im, rand(40,140),rand(40,140),rand(40,140));
                imagettftext($im,$fontsize,$jiaodu,$x,$y,$color,$fonturl,$dscode);
            }
        }
        private function set_code($im){
            $width=$this->width;
            $counts=$this->counts;
            $height=$this->height;
            $scode=$this->session;
            $y=floor($height/2)+floor($height/4);
            $fontsize=rand(20,25);
            $fonturl=$this->fonturl;
 
            $counts=$this->counts;
            for($i=0;$i<$counts;$i++){
                $char=$scode[$i];
                $x=floor($width/$counts)*$i+8;
                $jiaodu=rand(-20,30);
                $color = ImageColorAllocate($im,rand(0,50),rand(50,100),rand(100,140));
                imagettftext($im,$fontsize,$jiaodu,$x,$y,$color,$fonturl,$char);
            }
 
        }
        private function sessioncode(){
            $originalcode = $this->distrubcode;
            $countdistrub = strlen($originalcode);
            $_dscode = "";
            $counts=$this->counts;
            for($j=0;$j<$counts;$j++){
                $dscode = $originalcode[rand(0,$countdistrub-1)];
                $_dscode.=$dscode;
            }
            return $_dscode;
        }
    }
    Header("Content-type: image/GIF");
    $imagecode=new  Imagecode(90,39,4,'',$font);
    $imagecode->imageout();

2、在前台注册的弹出层中加入DOM结构:

<p id="captcha_inline">
 
    <input class="input-control inline" type="text" id="um_captcha" name="um_captcha" placeholder="输入验证码" required>
 
    <img src="<?php echo get_bloginfo('template_url'). '/inc/captcha.php'; ?>" class="captcha_img inline" alt="验证码" title="点击刷新验证码">
    <input type="hidden" value="<?php echo get_bloginfo('template_url'); ?>" id="tplUrl">
 
</p>
3、在functions.php中加入下列代码,用于ajax请求用:
//~ AJAX注册验证
function hbao_ajax_register(){
	$result	= array();
	if(isset($_POST['security']) && wp_verify_nonce( $_POST['security'], 'user_security_nonce' ) ){
		$user_login = sanitize_user($_POST['username']);
		$user_pass = $_POST['password'];
		$user_email = apply_filters( 'user_registration_email', $_POST['email'] );
		$captcha = strtolower(trim($_POST['um_captcha']));
		session_start();
		$session_captcha = strtolower($_SESSION['um_captcha']);
		$errors	= new WP_Error();
		if( ! validate_username( $user_login ) ){
			$errors->add( 'invalid_username', __( '请输入一个有效用户名','hbao' ) );
		}elseif(username_exists( $user_login )){
			$errors->add( 'username_exists', __( '此用户名已被注册','hbao' ) );
		}elseif(email_exists( $user_email )){
			$errors->add( 'email_exists', __( '此邮箱已被注册','hbao' ) );
		}
 
		do_action( 'register_post', $user_login, $user_email, $errors );
		$errors = apply_filters( 'registration_errors', $errors, $user_login, $user_email );
		if ( $errors->get_error_code() ){
			$result['success']	= 0;
			$result['message'] 	= $errors->get_error_message();
 
		} else {
			$user_id = wp_create_user( $user_login, $user_pass, $user_email );
			if ( ! $user_id ) {
				$errors->add( 'registerfail', sprintf( __( '抱歉,无法注册,请联系管理员','hbao' ), get_option( 'admin_email' ) ) );
				$result['success']	= 0;
				$result['message'] 	= $errors->get_error_message();		
			} else{
				update_user_option( $user_id, 'default_password_nag', true, true ); //Set up the Password change nag.
				wp_new_user_notification( $user_id, $user_pass );	
				$result['success']	= 1;
				$result['message']	= esc_html__( '注册成功,即将为你自动登录','hbao' );
				// 自动登录
				wp_set_current_user($user_id);
  				wp_set_auth_cookie($user_id);
  				$result['loggedin']	= 1;
			}
		}	
	}else{
		$result['message'] = __('安全认证失败,请重试!','hbao');
	}
	header( 'content-type: application/json; charset=utf-8' );
	echo json_encode( $result );
	exit;	
}
add_action( 'wp_ajax_ajaxregister', 'hbao_ajax_register' );
add_action( 'wp_ajax_nopriv_ajaxregister', 'hbao_ajax_register' );
 
//~ 验证码 - 验证
function um_add_register_captcha_verify($sanitized_user_login,$user_email,$errors){
	if(!isset($_POST['um_captcha'])||empty($_POST['um_captcha'])){
		return $errors->add( 'empty_captcha', __( '请填写验证码','hbao' ) );
	}else{
		$captcha = strtolower(trim($_POST['um_captcha']));
		session_start();
		$session_captcha = strtolower($_SESSION['um_captcha']);
		if($captcha!=$session_captcha){
			return $errors->add( 'wrong_captcha', __( '验证码错误','hbao' ) );
		}
	}
}
add_action('register_post','um_add_register_captcha_verify',10,3);

以上代码加好之后,请对照代码,看好里面post的一些字段,比如:security ,如果没有自己在form中加一下:

<input type="hidden" id="user_security" name="user_security" value="<?php echo wp_create_nonce( 'user_security_nonce' );?>">

还有hbao_ajax_register()我给出的代码是完整版的验证,所以你只要拿其中验证码的部分,即下面这段:

$captcha = strtolower(trim($_POST['um_captcha']));
session_start();
$session_captcha = strtolower($_SESSION['um_captcha']);

4、在主题的js文件里加入下列代码,用于刷新验证码:

//~ Refresh captcha
$('img.captcha_img').on('click',function(){
  var captcha = $('#tplUrl').val()+'/inc/captcha.php?'+Math.random();
  $(this).attr('src',captcha);
});

这里还有一个步骤我就不写了,就是验证码输入的正确错误判断,因为每个主题使用的方式不一样,我这边是ajax验证,所以都是通过js验证是否输入验证码,和输入的验证码是否正确。上面也给出了PHP的验证,可以参考使用。

陌涛

这个博主很懒,懒死了。

相关推荐

暂无评论

微信扫一扫

微信扫一扫

微信扫一扫,分享到朋友圈

WordPress代码实现给网站注册加上图片验证码功能
EA PLAYER &

历史记录 [ 注意:部分数据仅限于当前浏览器 ]清空

      00:00/00:00
      运行于【极速云】