登錄時,沒有圖形驗證碼的話,很容被機器人進行模擬登錄,對網站安全有很大的威脅。因此,驗證碼是登錄功能所必須的。下面,我們就給我們的登錄功能,加上驗證碼。
## 下面功能相關的目錄

首先使用Composer安裝think-captcha擴展包,通過命令行,進入 D:\\www\\phper。(您根據實際情況處理)
~~~
composer require topthink/think-captcha
~~~
完整安裝之后,我們在 application 下的 config.php 中添加如下配置:
~~~
<?php
//配置文件
return [
'captcha' => [
// 驗證碼字符集合
'codeSet' => '2345678abcdefhijkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY',
// 驗證碼字體大小(px)
'fontSize' => 25,
// 是否畫混淆曲線
'useCurve' => true,
// 驗證碼圖片高度
'imageH' => 30,
// 驗證碼圖片寬度
'imageW' => 100,
// 驗證碼位數
'length' => 5,
// 驗證成功后是否重置
'reset' => true
]
];
~~~
> 驗證碼的配置必須加到 applocation 下面的config 中才可以準確的控制。
在登錄頁面中,index\\view\\login\\index.html 中,密碼下面,加入如下的代碼:
~~~
<div class="form-group">
<label>驗證碼</label>
<input type="text" placeholder="請輸入驗證碼" class="form-control" name="captcha">
<img src="{:captcha_src()}" alt="captcha" onclick="javascript:this.src='{:captcha_src()}?tm='+Math.random();" style="cursor: pointer"/>
</div>
~~~
> 注意此處的代碼: onclick="javascript:this.src='{:captcha\_src()}?tm='+Math.random();" 段代碼是用來完成,點擊驗證碼圖案,換一個驗證碼的功能。
然后修改 doLogin 方法,添加驗證碼驗證的處理。首先我們要在 Login.php 的開的頭加入:
~~~
use think\captcha;
~~~
后面的 captcha\_check 驗證碼檢測,才能正確的使用。
~~~
// 處理登錄邏輯
public function doLogin()
{
$param = input('post.');
if(empty($param['user_name'])){
$this->error('用戶名不能為空');
}
if(empty($param['user_pwd'])){
$this->error('密碼不能為空');
}
if(empty($param['captcha'])){
$this->error('驗證碼不能為空');
}
// 處理驗證碼
if(!captcha_check($param['captcha'])){
$this->error('驗證碼錯誤');
};
// 驗證用戶名
$has = db('users')->where('user_name', $param['user_name'])->find();
if(empty($has)){
$this->error('用戶名密碼錯誤');
}
// 驗證密碼
if($has['user_pwd'] != md5($param['user_pwd'])){
$this->error('用戶名密碼錯誤');
}
// 記錄用戶登錄信息
cookie('user_id', $has['id'], 3600); // 一個小時有效期
cookie('user_name', $has['user_name'], 3600);
$this->redirect(url('index/index'));
}
~~~
至此,驗證碼添加完成。
