第一步:引入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';
}
如果前臺要調用,也很簡單,直接把這個接口返回的結果放到img標籤裏面就可以了:
<img src="http://api.commas-studio.com/helper/captcha/11">