Captcha Component

Project address: https://github.com/webman-php/captcha

Installation

composer require webman/captcha

Usage

Create the file app/controller/LoginController.php

<?php
namespace app\controller;

use support\Request;
use Webman\Captcha\CaptchaBuilder;

class LoginController
{
    /**
     * Test page
     */
    public function index(Request $request)
    {
        return view('login/index');
    }

    /**
     * Output captcha image
     */
    public function captcha(Request $request)
    {
        // Initialize the captcha class
        $builder = new CaptchaBuilder;
        // Generate captcha
        $builder->build();
        // Store the captcha value in the session
        $request->session()->set('captcha', strtolower($builder->getPhrase()));
        // Get the binary data of the captcha image
        $img_content = $builder->get();
        // Output the captcha binary data
        return response($img_content, 200, ['Content-Type' => 'image/jpeg']);
    }

    /**
     * Check captcha
     */
    public function check(Request $request)
    {
        // Get the captcha field from the post request
        $captcha = $request->post('captcha');
        // Compare with the captcha value in the session
        if (strtolower($captcha) !== $request->session()->get('captcha')) {
            return json(['code' => 400, 'msg' => 'The captcha you entered is incorrect']);
        }
        return json(['code' => 0, 'msg' => 'ok']);
    }

}

Create the template file app/view/login/index.html

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>Captcha Test</title>  
</head>
<body>
    <form method="post" action="/login/check">
       <img src="/login/captcha" /><br>
        <input type="text" name="captcha" />
        <input type="submit" value="Submit" />
    </form>
</body>
</html>

Visit the page http://127.0.0.1:8787/login, the interface is similar to the following:

Common Parameter Settings

    /**
     * Output captcha image
     */
    public function captcha(Request $request)
    {
        $builder = new PhraseBuilder(4, 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ');
        $captcha = new Captcha(null, $builder);
        $captcha->build();
        $request->session()->set('join', strtolower($captcha->getPhrase()));
        $img_content = $captcha->get();
        return response($img_content, 200, ['Content-Type' => 'image/jpeg']);
    }

For more interfaces and parameters, refer to https://github.com/webman-php/captcha