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)
    {
        // POST リクエストの 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 を参照してください。