实现功能之前运行命令composer require gregwar/captcha=1.*
1.登录表单
登录表单
<form action="verifyCaptcha" method="post">
{{csrf_field()}}//这里一定要写 因为你有form表单 所以一定要加上这段代码,否则会报419错误
<tr>
<td>用户名</td>
<td><input name="uname" type="text" placeholder="请输入账号/用户名..."></td>
</tr>
<tr>
<td>密码</td>
<td><input name="upwd" type="password" placeholder="请输入密码"></td>
</tr>
<tr>
<td>验证码</td>
<td><input name="captcha" type="text" placeholder="请输入验证码"></td>
<td><img src="{{$code}}" height="36" width="80"></td>
</tr>
<input type="submit" value="验证">
</form>
2.登录控制器
<?php
namespace app\Http\Controllers;
header("content-type:text/html;charset=utf-8");
use App\Http\Controllers\Controller;
//使用redis之前需要引入我们的redis类
// use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Db;
use Illuminate\Support\Facades\Session;
use Gregwar\Captcha\CaptchaBuilder;
use Illuminate\Http\Request;
// use Session;
use Gregwar\Captcha\PhraseBuilder;
// use App\Models\Reg;
class YzmController extends Controller
{
//生成验证码
public function captcha() {
$builder = new CaptchaBuilder;
$builder->build();
$code = $builder->inline(); //获取图形验证码的url
// echo $code;die;
session()->put('piccode', $builder->getPhrase()); //将图形验证码的值写入到session中
return view('yzm/admin_log',['code'=>$code]);
}
//验证注册码的正确与否
public function verifyCaptcha() {
$captcha = request('captcha');
$code = Session::get('piccode');
if($captcha == ''){
echo "<script>alert('请输入验证码!');</script>";
return $this->captcha();
exit();
}elseif($captcha!=$code){
echo "<script>alert('验证码错误!');</script>";
return $this->captcha();
exit();
}else{
$uname = request('uname');
$upwd = md5(request('upwd'));
$res = DB::select("select * from reg where uname='$uname' and upwd='$upwd'");
if($res){
echo "<script>alert('login-ok');</script>";
return $this->captcha();
exit();
}else{
echo "<script>alert('login-error');</script>";
return $this->captcha();
exit();
}
}
}
}
3.路由
路由
验证码路由
Route::get('yzm/captcha', 'YzmController@captcha');
Route::post('yzm/verifyCaptcha', 'YzmController@verifyCaptcha');
总结:
以上这些就是laravel中使用验证码类实现验证码的显示和验证以及在登录功能的使用