atk14/recaptcha-field

用于保护 ATK14 应用中表单免受垃圾邮件侵害的字段

v0.1.3 2023-07-21 18:16 UTC

This package is auto-updated.

Last update: 2024-09-21 21:09:28 UTC


README

RecaptchaField 是用于保护 ATK14 应用中表单免受垃圾邮件侵害的字段。

它使用 Google 的 reCAPTCHA v2(见 https://www.google.com/recaptcha/intro/index.html

安装

只需使用 Composer

cd path/to/your/atk14/project/
composer require atk14/recaptcha-field

您必须在 config/settings.php 中定义两个常量。获取它们的正确值请访问 https://www.google.com/recaptcha/admin#list

<?php
// file: config/settings.php

// ...
define("RECAPTCHA_SITE_KEY","fksjfu2094389SAKJDPOSAIIaskalkslamcbuyid");
define("RECAPTCHA_SECRET_KEY","pwofe994883eiDJKHFISIYTTSSSSSkfdt7poieqnx");

可选地,您可以将 RecaptchaField 文件链接到您的项目中

ln -s ../../vendor/atk14/recaptcha-field/src/app/fields/recaptcha_field.php app/fields/recaptcha_field.php
ln -s ../../vendor/atk14/recaptcha-field/src/app/widgets/recaptcha_widget.php app/widgets/recaptcha_widget.php

在 ATK14 应用中使用

在表单中

<?php
// file: app/forms/users/create_new_form.php
class CreateNewForm extends ApplicationForm {

  function set_up(){
    $this->add_field("firstname", new CharField([
      "label" => "Firstname",
      "max_length" => 200,
    ]));

    $this->add_field("lastname", new CharField([
      "label" => "Lastname",
      "max_length" => 200,
    ]));

    // other fields

    $this->add_field("captcha",new RecaptchaField([
      "label" => "Spam protection"
    ]));
  }

  function clean(){
    list($err,$values) = parent::clean();

    // perhaps you may not want to have "captcha" in the cleaned data
    if(is_array($values)){ unset($values["captcha"]); }

    return [$err,$values];
  }
}

在模板中(使用来自 Atk14Skelet 的共享模板)

<h1>User Registration</h1>

{form}

  <fieldset>
    {render partial="shared/form_field" fields="firstname,lastname,..."}
  </fieldset>

  <fieldset>
    {render partial="shared/form_field" fields="captcha"}
  </fieldset>

  <button type="submit">Register</button>

{/form}

在控制器中

<?php
// file: app/controllers/users_controller.php
class UsersController extends ApplicationController {
  
  function create_new(){
    if($this->request->post() && ($values = $this->form->validate($this->params))){
      // There's no need to care about the $values["captcha"] since it was unset in CreateNewForm::clean()
      User::CreateNewRecord($values);
      $this->flash->success("Your registration has been successfully performed");
      $this->_redirect_to("main/index");
    }
  }
}

使用示例

例如,RecaptchaField 用于在 注册表单 上,如在 ATK14 论坛 上。

许可证

RecaptchaField 是免费软件,根据 MIT 许可证的条款分发 https://open-source.org.cn/licenses/mit-license