Thành phần mã xác nhận
Địa chỉ dự án https://github.com/webman-php/captcha
Cài đặt
composer require webman/captcha
Sử dụng
Tạo tệp app/controller/LoginController.php
<?php
namespace app\controller;
use support\Request;
use Webman\Captcha\CaptchaBuilder;
class LoginController
{
/**
* Trang thử nghiệm
*/
public function index(Request $request)
{
return view('login/index');
}
/**
* Xuất hình ảnh mã xác nhận
*/
public function captcha(Request $request)
{
// Khởi tạo lớp mã xác nhận
$builder = new CaptchaBuilder;
// Tạo mã xác nhận
$builder->build();
// Lưu giá trị mã xác nhận vào session
$request->session()->set('captcha', strtolower($builder->getPhrase()));
// Lấy dữ liệu nhị phân hình ảnh mã xác nhận
$img_content = $builder->get();
// Xuất dữ liệu nhị phân hình ảnh mã xác nhận
return response($img_content, 200, ['Content-Type' => 'image/jpeg']);
}
/**
* Kiểm tra mã xác nhận
*/
public function check(Request $request)
{
// Lấy trường captcha từ yêu cầu post
$captcha = $request->post('captcha');
// So sánh giá trị captcha trong session
if (strtolower($captcha) !== $request->session()->get('captcha')) {
return json(['code' => 400, 'msg' => 'Mã xác nhận nhập vào không đúng']);
}
return json(['code' => 0, 'msg' => 'ok']);
}
}
Tạo tệp mẫu app/view/login/index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Thử nghiệm mã xác nhận</title>
</head>
<body>
<form method="post" action="/login/check">
<img src="/login/captcha" /><br>
<input type="text" name="captcha" />
<input type="submit" value="Gửi" />
</form>
</body>
</html>
Truy cập trang http://127.0.0.1:8787/login
giao diện tương tự như sau:
Thiết lập tham số thường gặp
/**
* Xuất hình ảnh mã xác nhận
*/
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']);
}
Tham khảo thêm các giao diện và tham số tại https://github.com/webman-php/captcha