ส่วนประกอบ CAPTCHA

ที่อยู่โปรเจกต์ https://github.com/webman-php/captcha

การติดตั้ง

composer require webman/captcha

การใช้งาน

สร้างไฟล์ app/controller/LoginController.php

<?php
namespace app\controller;

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

class LoginController
{
    /**
     * หน้าทดลอง
     */
    public function index(Request $request)
    {
        return view('login/index');
    }

    /**
     * ส่งออกภาพ CAPTCHA
     */
    public function captcha(Request $request)
    {
        // เริ่มต้นคลาส CAPTCHA
        $builder = new CaptchaBuilder;
        // สร้าง CAPTCHA
        $builder->build();
        // เก็บค่าของ CAPTCHA ลงในเซสชัน
        $request->session()->set('captcha', strtolower($builder->getPhrase()));
        // รับข้อมูลบิตของภาพ CAPTCHA
        $img_content = $builder->get();
        // ส่งออกข้อมูลบิตของ CAPTCHA
        return response($img_content, 200, ['Content-Type' => 'image/jpeg']);
    }

    /**
     * ตรวจสอบ CAPTCHA
     */
    public function check(Request $request)
    {
        // รับค่าฟิลด์ captcha จากคำร้องโพสต์
        $captcha = $request->post('captcha');
        // เปรียบเทียบค่าของ captcha ในเซสชัน
        if (strtolower($captcha) !== $request->session()->get('captcha')) {
            return json(['code' => 400, 'msg' => 'CAPTCHA ที่ป้อนไม่ถูกต้อง']);
        }
        return json(['code' => 0, 'msg' => 'ok']);
    }

}

สร้างไฟล์เทมเพลต app/view/login/index.html

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>ทดสอบ CAPTCHA</title>  
</head>
<body>
    <form method="post" action="/login/check">
       <img src="/login/captcha" /><br>
        <input type="text" name="captcha" />
        <input type="submit" value="ส่ง" />
    </form>
</body>
</html>

เข้าสู่หน้าที่ http://127.0.0.1:8787/login หน้าจอจะมีลักษณะคล้ายดังนี้:

การตั้งค่าพารามิเตอร์ทั่วไป

    /**
     * ส่งออกภาพ CAPTCHA
     */
    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']);
    }

สำหรับส่วนต่อประสานและพารามิเตอร์เพิ่มเติมโปรดดูที่ https://github.com/webman-php/captcha