secgin / phalcon-recaptcha-plugin
Phalcon 框架的 Google ReCaptcha 插件
v1.0
2023-11-09 19:52 UTC
Requires
- ext-phalcon: ~4.1.2
Requires (Dev)
- phalcon/ide-stubs: ~4.1
README
Phalcon 框架中用于 Google reCAPTCHA v2 的一个扩展插件。
安装
composer require secgin/phalcon-recaptcha-plugin
示例:登录操作中使用 Recaptcha
配置
将以下配置添加到您的项目配置文件中。
<?php return new Phalcon\Config([ 'recaptcha' => [ 'apiUrl' => 'https://www.google.com/recaptcha/api/siteverify', // Zorunlu değil varsayılan olarak bu değeri kullanır 'siteKey' => '', 'secretKey' => '' ] ]);
表单类
<?php class LoginForm extends Form { public function initialize() { $username = new Text('username'); $username->setLabel('Username'); $username->addValidators([ new PresenceOf(['message' => 'Username is required']), new StringLength(['min' => 3, 'messageMinimum' => 'Username is too short. Minimum 3 characters']) ]); $this->add($username); $password = new Password('password'); $password->setLabel('Password'); $password->addValidators([ new PresenceOf(['message' => 'Password is required']), new StringLength(['min' => 8, 'messageMinimum' => 'Password is too short. Minimum 8 characters']) ]); $this->add($password); $recaptcha = new Captcha('recaptcha', $this->config->path('recaptcha.siteKey')); $recaptcha->setLabel('Recaptcha'); $recaptcha->addValidators([ new Response( [ 'message' => 'Recaptcha is required', 'secretKey' => $this->config->path('recaptcha.secretKey'), 'apiUrl' => $this->config->path('recaptcha.apiUrl') ]) ]); $this->add($recaptcha); $submit = new Submit('submit'); $submit->setDefault('Login'); $this->add($submit); } }
控制器类
<?php class IndexController extends Controller { public function indexAction() { $loginForm = new LoginForm(); if ($this->request->isPost()) { $isValid = $loginForm->isValid($this->request->getPost()); $userMessage = ''; if ($isValid) $userMessage = 'Login successful'; else { foreach ($loginForm->getMessages() as $message) $userMessage .= $message->getMessage() . '<br>'; } } $this->view->setVars([ 'form' => new LoginForm(), 'userMessage' => $userMessage ?? null ]); } }