Laravel5.5生成驗證碼與驗證正確與否
阿新 • • 發佈:2019-01-01
第一步:引入gregwar/captcha包:
composer require gregwar/captcha
第二步:在幫助函式中建立函式:
use Gregwar\Captcha\CaptchaBuilder; use Illuminate\Http\Request; use Session; class HelperController extends Controller { //生成驗證碼 public function captcha($tmp) { //生成驗證碼圖片的Builder物件,配置相應屬性 $builder = new CaptchaBuilder; //可以設定圖片寬高及字型 $builder->build($width = 250, $height = 70, $font = null); //獲取驗證碼的內容 $phrase = $builder->getPhrase(); //把內容存入session Session::flash('milkcaptcha', $phrase); //生成圖片 header("Cache-Control: no-cache, must-revalidate"); header('Content-Type: image/jpeg'); $builder->output(); } //驗證註冊碼的正確與否 public function verifyCaptcha() { $userInput = request('captcha'); if (Session::get('milkcaptcha') == $userInput) { //使用者輸入驗證碼正確 return $this->outPutJson('', 200, '驗證碼正確!'); } else { //使用者輸入驗證碼錯誤 return $this->outPutJson('', 301, '驗證碼輸入錯誤!'); } } }
第三步:如果想要替換自己的驗證碼字型,可以在包內的Font資料夾內替換,按照格式命名即可。看這個原始碼就明白了,隨機生成一個數字,字型命名格式如下:captcha4.ttf。一般自帶的就夠用了。
D:\phpStudy\WWW\api.douxiaoli.com\vendor\gregwar\captcha\Font\
if ($font === null) {
$font = __DIR__ . '/Font/captcha' . $this->rand(0, 8) . '.ttf';
}
在postman裡面效果就是這樣的:
如果前臺要呼叫,也很簡單,直接把這個介面返回的結果放到img標籤裡面就可以了:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1>我是index.html</h1>
<img src="http://api.commas-studio.com/helper/captcha/11">
效果如下: