laravel的验证码_laravel 验证码

Laravel的验证码_laravel 验证码

在Laravel项目中,验证码是一种常见的安全措施,用于防止恶意用户提交表单或进行其他自动化操作。介绍如何在Laravel中实现验证码功能,并提供多种实现思路。

1. 使用Laravel自带的验证码包

Laravel本身并没有内置验证码功能,但可以通过安装第三方包来实现。最常用的包是mews/captcha,它提供了简单易用的验证码生成和验证功能。

安装mews/captcha

通过Composer安装mews/captcha包:

bash
composer require mews/captcha

发布配置文件

安装完成后,发布配置文件:

bash
php artisan vendor:publish --provider="MewsCaptchaCaptchaServiceProvider"

修改配置文件

发布后的配置文件位于config/captcha.php,你可以根据需要进行修改。默认配置如下:

php
return [
'default' => [
'length' => 5,
'width' => 120,
'height' => 36,
'quality' => 90,
'math' => false,
],
];

在控制器中生成验证码

在控制器中生成验证码并返回给视图:

php
use MewsCaptchaFacadesCaptcha;</p>

<p>class CaptchaController extends Controller
{
    public function index()
    {
        return view('captcha');
    }</p>

<pre><code>public function createCaptcha()
{
    return response()->json(['captcha' => captcha_img()]);
}

public function checkCaptcha(Request $request)
{
    if (Captcha::check($request->captcha)) {
        return response()->json(['success' => true]);
    } else {
        return response()->json(['success' => false, 'message' => '验证码错误']);
    }
}

}

在视图中显示验证码

在视图中显示验证码并添加表单:

html
</p>



    <title>Laravel 验证码</title>


    
        @csrf
        <div>
            <img src="{{ route('create-captcha') }}" alt="验证码" id="captcha">
            <button type="button">换一张</button>
        </div>
        <div>
            
        </div>
        <div>
            <button type="submit">提交</button>
        </div>
    

    
        function reloadCaptcha() {
            document.getElementById('captcha').src = "{{ route('create-captcha') }}" + '?' + Math.random();
        }
    



<p>

路由配置

配置路由:

php
use AppHttpControllersCaptchaController;</p>

<p>Route::get('/captcha', [CaptchaController::class, 'index']);
Route::get('/create-captcha', [CaptchaController::class, 'createCaptcha'])->name('create-captcha');
Route::post('/check-captcha', [CaptchaController::class, 'checkCaptcha']);

2. 使用自定义验证码

如果你希望完全自定义验证码的生成和验证逻辑,可以参考以下步骤:

创建验证码生成器

创建一个生成验证码的类:

php
namespace AppServices;</p>

<p>class CaptchaGenerator
{
    public function generate()
    {
        $code = str_random(5);
        session(['captcha' => $code]);
        $image = imagecreatetruecolor(120, 36);
        $bgColor = imagecolorallocate($image, 255, 255, 255);
        $textColor = imagecolorallocate($image, 0, 0, 0);</p>

<pre><code>    imagefilledrectangle($image, 0, 0, 120, 36, $bgColor);
    imagettftext($image, 20, 0, 10, 30, $textColor, __DIR__ . '/arial.ttf', $code);

    ob_start();
    imagepng($image);
    $contents = ob_get_contents();
    ob_end_clean();

    imagedestroy($image);

    return base64_encode($contents);
}

}

在控制器中使用生成器

在控制器中使用生成器生成验证码:

php
use AppServicesCaptchaGenerator;</p>

<p>class CustomCaptchaController extends Controller
{
    public function index()
    {
        return view('custom-captcha');
    }</p>

<pre><code>public function createCaptcha(CaptchaGenerator $generator)
{
    return response()->json(['captcha' => 'data:image/png;base64,' . $generator->generate()]);
}

public function checkCaptcha(Request $request)
{
    if ($request->captcha == session('captcha')) {
        return response()->json(['success' => true]);
    } else {
        return response()->json(['success' => false, 'message' => '验证码错误']);
    }
}

}

在视图中显示自定义验证码

在视图中显示自定义验证码并添加表单:

html
</p>



    <title>Laravel 自定义验证码</title>


    
        @csrf
        <div>
            <img src="{{ route('create-custom-captcha') }}" alt="验证码" id="custom-captcha">
            <button type="button">换一张</button>
        </div>
        <div>
            
        </div>
        <div>
            <button type="submit">提交</button>
        </div>
    

    
        function reloadCustomCaptcha() {
            document.getElementById('custom-captcha').src = "{{ route('create-custom-captcha') }}" + '?' + Math.random();
        }
    



<p>

路由配置

配置路由:

php
use AppHttpControllersCustomCaptchaController;</p>

<p>Route::get('/custom-captcha', [CustomCaptchaController::class, 'index']);
Route::get('/create-custom-captcha', [CustomCaptchaController::class, 'createCaptcha'])->name('create-custom-captcha');
Route::post('/check-custom-captcha', [CustomCaptchaController::class, 'checkCaptcha']);

以上两种方法都可以在Laravel项目中实现验证码功能,选择适合你项目需求的方法进行实现即可。

Image

文章来源网络,作者:管理,如若转载,请注明出处:https://shuyeidc.com/wp/67762.html<

(0)
管理的头像管理
上一篇2025-02-06 14:05
下一篇 2025-02-06 14:06

相关推荐

  • 骨干网络体系结构能干什么?骨干网络体系结构的作用

    骨干网络体系结构是现代信息社会的“超级高速公路网”,它通过分层设计、冗余备份和智能调度,确保海量数据在全球范围内高速、稳定、安全地传输,是支撑云计算、物联网及人工智能应用的底层基石,想象一下,如果你把互联网比作一个巨大的城市交通系统,那么骨干网络就是连接各个城市的主干道和立交桥,没有它,你的每一次微信发送、每一……

    2026-06-18
    0
  • 高io数据库可以干什么用?高io数据库适合什么场景

    高IO数据库的核心价值在于通过极高的读写吞吐量,解决海量数据场景下的性能瓶颈,是支撑高并发交易、实时分析及大规模内容分发的关键基础设施,在数字化转型的深水区,数据不再仅仅是静态的记录,而是流动的资产,传统的机械硬盘或普通SSD早已无法满足现代应用对速度的极致追求,高IO(Input/Output)数据库,就是那……

    2026-06-18
    0
  • 高io服务器性能如何?高io服务器适合什么场景

    高IO服务器并非单纯指代某种硬件,而是指在随机读写、高并发连接及小文件处理场景下,具备极致IOPS(每秒输入输出操作次数)和低延迟特性的计算资源,它是支撑现代高并发应用稳定运行的核心基石,在2026年的数字化浪潮中,业务负载早已从简单的静态页面展示演变为复杂的实时数据处理,许多开发者在排查系统瓶颈时,往往忽略了……

    2026-06-18
    0
  • 隔离网络空间哪里便宜?国内隔离网络空间价格

    隔离网络空间并没有统一的“便宜”标准,其成本高度取决于物理隔离等级、带宽需求及安全合规要求,通常物理网闸方案初期投入较高但长期运维成本低,而逻辑隔离方案虽初期便宜但存在潜在安全风险,建议根据业务敏感度选择混合隔离架构以平衡成本与安全,在数字化时代,企业构建独立网络环境的需求日益增长,但“隔离网络空间哪里便宜”这……

    2026-06-18
    0
  • 骨干网络体系结构设备为何故障?常见原因有哪些

    骨干网络体系结构设备故障的核心原因通常归结为硬件老化、配置错误、物理链路中断及外部攻击四大类,其中电源模块失效与光模块性能衰减是占比最高的隐性故障源,骨干网作为数字经济的“大动脉”,其稳定性直接关乎国计民生,当核心路由器或交换机出现丢包、震荡甚至宕机时,运维人员往往面临巨大的压力,很多人第一反应是检查软件配置……

    2026-06-18
    0

发表回复

您的邮箱地址不会被公开。必填项已用 * 标注