工学1号馆

home

« | 返回首页 | »

使用tp5自定义验证码

By Wu Yudong on June 13, 2019

最近项目中需要实现自定义的验证码,首先在控制器中添加:

use think\captcha\Captcha;

接着实现一个方法

public function verify()
{
	$captcha = new Captcha();
	$captcha->fontSize = 14;
	$captcha->length   = 4;
	$captcha->useNoise = true;
	$captcha->useCurve = false;
	$captcha->imageH = 34;
	$captcha->imageW = 100;
	$captcha->fontttf = '4.ttf';
	return $captcha->entry();
}

主要是一些配置信息,接着就在前端显示,这里实现点击刷新验证码功能

<img class="verify_img" id="verify_img" src="{:url('user/verify')}" 
onclick="changeVerify()" style="cursor: pointer;width:100s;
border: 1px solid #d5d5d5;" title="点击获取">

接着实现changeVerify函数:

<script>
	function changeVerify(){
		var img = document.getElementById('verify_img');
		img.src = "{:url('user/verify')}";
	}
</script>

当然也可以直接实现,不需要使用单独的js函数:

<img class="verify_img" id="verify_img" src="{:url('verify')}" 
onClick="this.src='{:url('verify')}'+'?'+Math.random()" 
style="cursor: pointer;width:100s;border: 1px solid #d5d5d5;" title="点击获取">

接着在服务端写下面的代码:

$verify_code = input("verify");
if(!captcha_check($verify_code)){
    $this->error("验证码错误!");
}

 

如果文章对您有帮助,欢迎点击下方按钮打赏作者

Comments

No comments yet.
To verify that you are human, please fill in "七"(required)