如果验证码显示不出来 出来的是一个裂开的小图标 那说明 很有可能是Mac自带
的PHP没有 gd下面freetype这个扩展库
建议使用 MAMP这个Mac端的PHP集成环境 相当于Window端的 PHPStudy 还是很方便很好用的
MAMP下载地址👇
链接:https://pan.baidu.com/s/174hjy9M6aDZGcDDuD06UMw 密码:41r5
实现验证码功能
LoginValidate 验证器的代码
<?php
namespace app\index\validate;
use think\Validate;
class LoginValidate extends Validate
{
/**
* 定义验证规则
* 格式:'字段名' => ['规则1','规则2'...]
*
* @var array
*/
protected $rule = [
'code' => 'require|captcha|token'
];
/**
* 定义错误信息
* 格式:'字段名.规则名' => '错误信息'
*
* @var array
*/
protected $message = [
'code.require' => '你想干什么,验证码都不录入',
"code.captcha" => "您输入的验证码有错误"
];
}
Login控制器的代码
<?php
namespace app\index\controller;
use app\index\validate\LoginValidate;
use think\captcha\Captcha;
use think\Controller;
use think\Request;
use verify\Verify;
class Login extends Controller {
// pathinfo模式
/*protected $middleware = [
// 中间件的类名称
'CheckLogin'1
# 中间件传值
#'CheckLogin:user'
];*/
// 登录界面
public function index() {
//dump(phpinfo());
return view('index@login/index');
}
// 登录处理
public function login(Request $request) {
// 验证器去验证验证码 推荐方式
$ret = $this->validate($request->post(), LoginValidate::class);
if (true !== $ret) {
return $this->error($ret);
}
// 独立去验证验证码
/* $code = $request->post();
// 如果验证不通过,则返回false
if (!captcha_check($code)) {
return $this->error('验证不正确');
}*/
dump($request->post());
}
}
view -> index.html的代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户登录</title>
<link rel="stylesheet" href="/static/index/css/bootstrap.css"/>
<link rel="stylesheet" href="/static/index/css/bootstrap-theme.css"/>
<style>
#vcode {
cursor: pointer;
}
</style>
</head>
<body>
<br>
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">用户登录</h3>
</div>
<div class="panel-body">
<form class="form-horizontal" method="post" action="{:url('index/login/login')}">
<!--csrf验证-->
{:token()}
<div class="form-group">
<label class="col-sm-2 control-label">账号:</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="title">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">密码:</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="desn">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">验证码:</label>
<div class="col-sm-5">
<input type="text" class="form-control" name="code">
</div>
<div class="col-sm-5">
<img src="{:captcha_src()}" id="vcode">
<!-- <div>{:captcha_img()}</div>-->
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">用户登录</button>
</div>
</div>
</form>
</div>
</div>
</div>
<script src="/static/js/jquery.min.js"></script>
<script src="/static/index/js/bootstrap.js"></script>
<script>
// 点击更新验证码图片
$('#vcode').click(function () {
let src = $(this).attr('src') + '?vt=' + Math.random();
//alert(src);
$(this).attr('src',src);
})
</script>
</body>
</html>
我这里使用了 bootstrap框架实现验证码登陆功能