在Laravel中有很多圖片驗證碼的庫可以使用,本篇介紹其中之一:gregwar/captcha,這個庫比較簡單,在Laravel中比較常用。下面我們就來介紹下使用細節:
首先, composer.json中如下加入配置:
"require": { ... "gregwar/captcha": "1.*" },
然后,已成習慣的命令:用cmd執行下面這條命令
composer update
以下演示了其中一種使用方式,直接輸出圖片到網頁。
我定義了一個Controller:
<?php namespace App\Http\Controllers; use App\Http\Requests; use App\Http\Controllers\Controller; use Illuminate\Http\Request; //引用對應的命名空間 use Gregwar\Captcha\CaptchaBuilder; use Session; class KitController extends Controller { /** * Display a listing of the resource. * * @return Response */ public function captcha($tmp) { //生成驗證碼圖片的Builder對象,配置相應屬性 $builder = new CaptchaBuilder; //可以設置圖片寬高及字體 $builder->build($width = 100, $height = 40, $font = null); //獲取驗證碼的內容 $phrase = $builder->getPhrase(); //把內容存入session Session::flash('milkcaptcha', $phrase); //生成圖片 header("Cache-Control: no-cache, must-revalidate"); header('Content-Type: image/jpeg'); $builder->output(); } }
下面我們可以設置相應的router訪問這個驗證碼圖片, 修改router.php:
Route::get('kit/captcha/{tmp}', 'KitController@captcha');
現在可以通過具體的url,可以訪問看到這張圖片了

驗證碼
表單內部寫的比較簡單,看看即可:
<form action="wer_add" method="get">
<table>
用戶名: <input type="text" name="username"><br>
密碼: <input type="text" name="password"><br>
11: <input type="text" name="captcha" style="width: 100px; height:20px "></br>
<a onclick="javascript:re_captcha();" >
<img src="{{ URL('kit/captcha/1') }}" alt="驗證碼" title="刷新圖片" width="100" height="40" id="c2c98f0de5a04167a9e427d883690ff6" border="0">
</a><br>
<input type="submit" value="提交">
</table>
</form> <script> function re_captcha() { $url = "{{ URL('kit/captcha') }}"; $url = $url + "/" + Math.random(); document.getElementById('c2c98f0de5a04167a9e427d883690ff6').src=$url; } </script>
最后就是在form提交頁面驗證相應驗證碼,庫中也為我們提供了相應方法:
public function wer_add(){
$username=Request::input("username");
$password=Request::input("password");
//讀取驗證碼
$captcha = Session::get('milkcaptcha');
if(Request::input("captcha")==$captcha){
$results = DB::select('select * from v9_admin where username = ? and password = ? ',array($username,$password));
if(empty($results)){
echo '用戶名或密碼錯誤';
}else{
$userid=$results[0]->userid;
Session::put('username',$username);
Session::put('userid',$userid);
echo '登陸成功';
}
}else{
echo '驗碼錯誤';
}
}
至此,驗證碼就完成了。 如有疑問,歡迎回復探討。