1,安裝擴展
在Laravel中有很多圖片驗證碼的庫可以使用,我們使用:gregwar/captcha,這個庫比較簡單,在Laravel中比較常用
composer gregwar/captcha
2,獲取圖形驗證碼
這裏我們使用的是base64給前端,前後端分離項目上這樣比較方便
use Gregwar\Captcha\CaptchaBuilder;
/**
* 獲取圖形驗證碼
* @param Request $request
* @return mixed
*/
public function getCaptcha(Request $request){
$builder = new CaptchaBuilder();
$builder->build();
$captcha = $builder->inline(); //輸出base64格式圖片
$code = $builder->getPhrase(); //驗證碼
session()->put('phrase',$code);
if(config('app.debug')){//調試模式輸出正確明文給前端
return $this->resultData('$_0',compact('captcha','code'));
}else{
return $this->resultData('$_0',compact('captcha'));
}
}
通過路由訪問此接口,即可獲取到base64類型的驗證碼
3,驗證圖形驗證碼
在需要使用圖形驗證碼的方法裏驗證
//驗證圖形碼
if(!$code){
throw new ApiException("驗證碼不能爲空");
}
$phrase = session('phrase'); //獲取session內的驗證碼
if(!$phrase||$code!=$phrase){
session()->forget('phrase'); //刪除session驗證碼
throw new ApiException("驗證碼錯誤");
}