1、首先使用Composer下载验证码插件。如果没有composer,点击这里下载并安装。
安装完成后,使用以下命令修改composer配置文件,使用国内镜像。原因你懂的。
composer config -g repo.packagist composer https://packagist.phpcomposer.com
然后打开cmd窗口,进入项目根目录,使用以下命令下载验证码插件:
composer require topthink/think-captcha
下载后的路径是:vendor\topthink\think-captcha\src
2、确保项目配置文件application/config.php中,以下两项配置为true:
'auto_start' => true,
'url_route_on' => true,
然后在配置文件中添加:
'captcha' => [
// 验证码字符集合
'codeSet' => '2345678abcdefhijkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY',
// 验证码字体大小(px)
'fontSize' => 20,
// 是否画混淆曲线
'useCurve' => true,
// 验证码图片高度
'imageH' => 30,
// 验证码图片宽度
'imageW' => 100,
// 验证码位数
'length' => 4,
// 验证成功后是否重置
'reset' => true
],
更详细的参数配置,参考vendor\topthink\think-captcha\src\Captcha.php类文件中的说明。
3、显示验证码:
<img src="{:captcha_src()}" onclick="this.src='{:captcha_src()}?x='+Math.random();" />
4、几个问题:
访问http://192.168.0.102/3/public/,验证码无法显示。
但是访问http://192.168.0.102/3/public/index.php,验证码正常显示。
解决方法:
打开vendor\topthink\think-captcha\src\helper.php文件,查找captcha_src方法,设置一个固定路径,比如我是放在web目录下的3文件夹里。
function captcha_src($id = "")
{
$root= \think\Url::root('/3/public/index.php');
return \think\Url::build('/captcha' . ($id ? "/{$id}" : ''));
}
另外,useImgBg参数设置为true后,会找不到图片背景。修改vendor\topthink\think-captcha\src\Captcha.php的_background方法,把$path变量修改为$path = dirname(__FILE__) . ‘/verify/bgs/’;
完整例子源码:
控制器
<?php
namespace app\index\controller;
use think\Controller;
class Index extends Controller
{
public function index()
{
return $this->fetch();
}
public function checkcode()
{
$code=input('yanzhengma');
if(!captcha_check($code))
{
echo "验证码错误!";
} else {
echo "验证通过!";
}
}
}
?>
视图index.html:
<form method="post" action="index.php/index/index/checkcode">
<input name="yanzhengma" type="text" />
<img src="{:captcha_src()}" onclick="this.src='{:captcha_src()}?x='+Math.random();" />
<input name="tijiao" type="submit" />
</form>
上一篇: 什么是微信小程序呢?微信小程序的趋势
下一篇: 严格界定与灵活的分类法?
售后保障
承诺任何问题1小时内解决数据备份
更安全、更高效、更稳定价格公道精准
项目经理精准报价不弄虚作假合作无风险
重合同讲信誉,无效全额退款