首页 > PHP > php生成验证码插件captcha的使用
2014
06-02

php生成验证码插件captcha的使用

1、安装php captcha 插件

d:\xampp\php\php.exe composer.phar require gregwar/captcha "dev-master"

2、封装一个调用函数

<?php
use Gregwar\Captcha\CaptchaBuilder;

    /**
     * Generates the captcha, "returns" a real image,
     * this is why there is header('Content-type: image/jpeg')
     * Note: This is a very special method, as this is echoes out binary data.
     * Eventually this is something to refactor
     */
    public function generateCaptcha()
    {
        // create a captcha with the CaptchaBuilder lib
        $builder = new CaptchaBuilder;
        $builder->build();

        // write the captcha character into session
        $_SESSION['captcha'] = $builder->getPhrase();

        // render an image showing the characters (=the captcha)
        header('Content-type: image/jpeg');
        $builder->output();
    }

    /**
     * Checks if the entered captcha is the same like the one from the rendered image which has been saved in session
     * @return bool success of captcha check
     */
    private function checkCaptcha()
    {
        if (isset($_POST["captcha"]) AND ($_POST["captcha"] == $_SESSION['captcha'])) {
            return true;
        }
        // default return
        return false;
    }
}

 

3、在表单中调用

			<img style="cursor:pointer" title="刷新验证码" id="refresh" border='0' src='<?php echo URL; ?>login/showCaptcha' onclick="document.getElementById('refresh').src='<?php echo URL; ?>login/showCaptcha?t='+Math.random()"/>  
            <label>
                请输入验证码
                <span style="display: block; font-size: 11px; color: #999;">
                    提示:如果看不清请点击图片刷新验证码。
                </span>
            </label>
            <input type="text" name="captcha" required />

 

 

最后编辑:
作者:dnybz
这个作者貌似有点懒,什么都没有留下。