首先, composer.json中如下加入配置:
"require": {
...
"gregwar/captcha": "1.*"
},
然后,已成习惯的命令:
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');
表单内部写的比较简单,看看即可:
<input type="text" name="captcha" class="form-control" style="width: 300px;">
<a onclick="javascript:re_captcha();" ><img src="{{ URL('kit/captcha/1') }}" alt="验证码" title="刷新图片" width="100" height="40" id="c2c98f0de5a04167a9e427d883690ff6" border="0"></a>
<script>
function re_captcha() {
$url = "{{ URL('kit/captcha') }}";
$url = $url + "/" + Math.random();
document.getElementById('c2c98f0de5a04167a9e427d883690ff6').src=$url;
}
</script>
如果使用的是laravel5.1开箱即用的登录功能,我们需要找到框架自带的登录方法
找到位于根目录下/vendor/laravel/framework/src/illuminate/Foundation/Auth/AuthenticatesUsers.php这个文件
查看postlogin方法:
$userInput = $request->get('captcha');
if (Session::get('milkcaptcha') == $userInput) {
$this->validate($request, [
$this->loginUsername() => 'required', 'password' => 'required',
]);
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
$throttles = $this->isUsingThrottlesLoginsTrait();
if ($throttles && $this->hasTooManyLoginAttempts($request)) {
return $this->sendLockoutResponse($request);
}
$credentials = $this->getCredentials($request);
if (Auth::attempt($credentials, $request->has('remember'))) {
return $this->handleUserWasAuthenticated($request, $throttles);
}
if ($throttles) {
$this->incrementLoginAttempts($request);
}
return redirect($this->loginPath())
->withInput($request->only($this->loginUsername(), 'remember'))
->withErrors([
$this->loginUsername() => $this->getFailedLoginMessage(),
]);
} else { //用户输入验证码错误 return '您输入验证码错误';}