使用Laravel写一个验证码
时间: 2023-07-20 09:09:29 浏览: 51
在 Laravel 中实现生成验证码需要使用 Laravel 的 Session 和 Image 类。下面是一个生成验证码的示例代码:
首先在 `routes/web.php` 文件中添加路由:
```php
Route::get('/captcha', function () {
$captcha = app('captcha')->create('default', true);
return response($captcha->inline());
})->name('captcha');
```
然后在控制器中定义 `captcha` 方法:
```php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Response;
use Gregwar\Captcha\CaptchaBuilder;
class CaptchaController extends Controller
{
public function captcha()
{
$builder = new CaptchaBuilder();
$builder->build();
$phrase = $builder->getPhrase();
Session::put('captcha', $phrase);
$response = Response::make($builder->output(), 200);
$response->header('Content-Type', 'image/jpeg');
return $response;
}
}
```
在 `composer.json` 文件中添加 `gregwar/captcha` 依赖:
```json
{
"require": {
"gregwar/captcha": "^2.0"
}
}
```
然后在终端中运行 `composer update` 命令安装依赖。
最后在视图中使用 `img` 标签来显示验证码:
```html
<img src="{{ route('captcha') }}" alt="captcha">
```
当用户提交表单时,你可以在控制器中使用以下代码来验证用户输入的验证码是否正确:
```php
if ($request->input('captcha') !== Session::get('captcha')) {
// 验证码输入错误
}
```