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 를 참조하세요.