isometriks/spam-bundle

此包最新版本(v1.2.0)没有可用的许可信息。

为 Symfony 表单提供垃圾邮件防护

v1.2.0 2024-01-08 09:36 UTC

This package is auto-updated.

Last update: 2024-08-29 13:07:15 UTC


README

请随意发送拉取请求。我希望将大量垃圾邮件方法集成到这个项目中。

安装

通过 Composer 安装

$ composer require isometriks/spam-bundle

如果你不使用 Symfony Flex,请将捆绑包添加到你的 config/bundles.php 文件

// config/bundles.php

return [
    // ...
    Isometriks\Bundle\SpamBundle\IsometriksSpamBundle::class => ['all' => true],
];

目前我们有

定时垃圾邮件防护

要求表单在一段时间后发送。大多数机器人不会等待提交你的表单,所以要求在渲染和提交之间有一段时间可以阻止这些机器人。

这种垃圾邮件防护的副作用是,你将无法刷新页面以重新提交数据,除非再次渲染视图 $form->createView()。这是因为事件监听器会移除表单的开始时间,当它找不到时,会导致表单无效。你可以将最小时间设置为0,仅使用此功能

请注意,这种垃圾邮件防护也将此限制应用于需要重新提交的填写不正确的表单。较高的最小时间可能会影响那些只需要快速修复一个字段的用户

配置

# config/packages/isometriks_spam.yaml

# Copying this config is not necessary. These are defaults, only copy 
# what you'd like to change. 
isometriks_spam:
    timed:
        min: 7 # seconds
        max: 3600
        global: false
        # message also takes translator strings.
        message: You're doing that too quickly.

使用方法

$this->createForm(MyType:class, null, [
    'timed_spam' => true, // Just this line is required to enable this feature, the rest is to override settings
    'timed_spam_min' => 3,
    'timed_spam_max' => 40,
    'timed_spam_message' => 'Please wait 3 seconds before submitting',
]);

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults([
        'timed_spam' => true,
        // ...
    ]);
}

蜜罐垃圾邮件防护

蜜罐是一种欺骗机器人填写不应填写的字段的方法。它是隐藏的,可以命名为一些常见名称,以便任何机器人/爬虫都会认为它是一个真实字段。

如果填写了这个字段,那么表单就无效了。你可以选择使用类名来隐藏表单元素,以防机器人尝试检查样式属性。

# Copying this config is not necessary. These are defaults, only copy 
# what you'd like to change. 
isometriks_spam:
    honeypot:
        field: email_address
        use_class: false
        hide_class: hidden
        global: false
        message: Form fields are invalid

使用方法

// Only honeypot = true is required to enable, the rest are to override settings
$this->createForm(MyType::class, null, [
    'honeypot' => true,
    'honeypot_field' => 'email_address',
    'honeypot_use_class' => false,
    'honeypot_hide_class' => 'hidden',
    'honeypot_message' => 'Form fields are invalid',
]);

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults([
        'honeypot' => true,
        // ...
    ]);
}

Twig 表单错误消息渲染

表单错误来自表单本身,所以如果你想显示错误,你需要确保这已经在你的模板中。

{% if form.vars.errors is not empty %}
    {{ form_errors(form) }}
{% endif %}