首页 > 技术文章 > php中使用验证码的方法大全

fengzhiqiangcaisangzi 2013-10-15 10:41 原文

1)使用控制器来控制

views:

<tr>
<td width="100"><?php echo $form->textField($model, 'captcha', array('class' => 'input_s', 'style' => 'width:80px')); ?></td>
<td width="110"><img id="captcha_img" src="<?php echo $this->createUrl('captcha/getPic') . '?' . rand(0, 99); ?>" style="cursor: pointer" title="看不清楚,点击换一张验证码" alt="验证码" onclick="change_captcha();" /></td>
<td><a href="javascript:void(0);" style=" font-family:'宋体'; font-size:12px; color:#0065A9" onclick="change_captcha();">换一张</a></td>
</tr>

点击换一张的js:

function change_captcha(){
                $('#captcha_img').attr('src', "<?php echo $this->createUrl('captcha/getPic'); ?>?"+Math.floor(Math.random()*200+1));
                $('#LoginForm_captcha').val('');
            }

  

CaptchaController:

<?php

/**
 * 验证码
 */
class CaptchaController extends CController {
    
    public function actionGetPic(){
        Yii::import("application.helpers.captcha.Captcha"); 
        
        header("Content-type:image/png");
        $captcha5 = new Captcha();

        //@设置验证码宽度
        $captcha5->setWidth(99);
        //@设置验证码高度
        $captcha5->setHeight(30);
        //@设置字符个数
        $captcha5->setTextNumber(4);

        //@设置字符颜色
        //$captcha5->setFontColor('#ff9900');
        //@设置字号大小
        //$captcha5->setFontSize(25);
        //@设置字体
        //$captcha5->setFontFamily('t1.ttf');

        //@设置语言
        //$captcha5->setTextLang('cn');

        //@设置背景颜色
        //$captcha5->setBgColor('#000000');
        //@设置干扰点数量
        $captcha5->setNoisePoint(100);
        //@设置干扰线数量
        //$captcha5->setNoiseLine(10);
        //@设置是否扭曲
        $captcha5->setDistortion(true);
        //@设置是否显示边框
        $captcha5->setShowBorder(false);

        //输出验证码
        $code = $captcha5->createImage();
        
        Yii::app()->session['captchaCode'] = array(
            'content' => $code,   //验证码的内容
            'time' => time()      //验证码的使用时间
        );
        exit;
    }
}
//注意这里要引入包

将验证码作为一个登陆模型的属性:

<?php

class LoginForm extends CFormModel {

public $email;
    public $password;
    public $captcha;
    public $rememberMe = false;
    public $userInfo;
	
	
	public function rules() {
        return array(
            array('email, password, captcha', 'required', 'message' => '{attribute}不能为空'),
            array('captcha', 'checkCaptcha'),
            array('password', 'authenticate'),
        );
    }
	
	
	
	public function checkCaptcha($attribute, $params) {
        if (!$this->hasErrors()) {
            $captcha = Yii::app()->session['captchaCode'];
            if (!isset($captcha['time']) || $captcha['time'] + 300 < time()) {
                $this->addError('captcha', '验证码过期。');
            } else if (strtolower($captcha['content']) != strtolower($this->captcha)) {
                $this->addError('captcha', '验证码错误。');
            }
        }
    }
	
	/**
     * 登陆验证
     * @param type $attribute
     * @param type $params 
     */
    public function authenticate($attribute, $params) {
        if (!$this->hasErrors()) {
            $user = ComUser::model()->findByAttributes(array('email' => $this->email));

            if ($user && $user->password == $user->hashPassword($this->password, $user->salt)) {
                if ($user->status == 1) {
                    $this->userInfo = $user;
                    unset(Yii::app()->session['captchaCode']);
                } else if ($user->status == 0) {
                    $this->addError('email', '用户暂未审核通过。');
                } else {
                    $this->addError('email', '用户已被禁用。');
                }
            } else {
                $this->addError('password', '账号或密码错误。');
            }
        }
    }
	
	public function attributeLabels() {
        return array(
            'email' => '用户名',
            'password' => '密码',
            'captcha' => '验证码',
            'rememberMe' => '记住登陆'
        );
    }
	
}

  

 

 

2).使用yii的验证码物件(参数可自己调试):

1.把public $captcha加入管理员Model的一个属性

验证rule时:

array('username, password, captcha', 'required', 'on'=>'login'),

array('captcha', 'captcha', 'allowEmpty'=>!extension_loaded('gd'), 'on'=>'login'),

然后控制器实例化时要使用场景。

2.视图页面:

<dt>验证码</dt>
<dd> <?php echo $form->textField($model,'captcha', array('class'=>'input-password verify-code')); ?>
<?php $this->widget ( 'CCaptcha', array ('showRefreshButton' => true, 'clickableImage' => true, 'buttonType' => 'link', 'buttonLabel' => '换一张', 'imageOptions' => array ('alt' => '点击换图', 'align'=>'absmiddle' ) ) );?>
<?php echo $form->error($model,'captcha'); ?> </dd>

3.在控制器Controller.php

public function actions ()
{
return array ('captcha' => array ('class' => 'CCaptchaAction' , 'minLength' => 1 , 'maxLength' => 5 , 'backColor' => 0xFFFFFF , 'width' => 100 , 'height' => 40 ) );
}

 

推荐阅读