middlewares / honeypot
中间件,用于实现蜜罐垃圾邮件预防
v2.0.1
2020-12-02 00:06 UTC
Requires
- php: ^7.2 || ^8.0
- middlewares/utils: ^3.0
- psr/http-server-middleware: ^1.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.0
- laminas/laminas-diactoros: ^2.3
- oscarotero/php-cs-fixer-config: ^1.0
- phpstan/phpstan: ^0.12
- phpunit/phpunit: ^8|^9
- squizlabs/php_codesniffer: ^3.0
README
中间件,用于实现蜜罐垃圾邮件预防。该技术基于创建一个应该对真实用户不可见且留空的输入字段,但大多数垃圾邮件机器人会填写该字段。中间件检查传入的请求中是否存在该值且为空(是真实用户)或不存在或包含值(是机器人),并返回403响应。
要求
- PHP >= 7.2
- PSR-7 http 库
- PSR-15 中间件分发器
安装
此包可以通过Composer安装和自动加载,名称为 middlewares/honeypot。
composer require middlewares/honeypot
示例
$dispatcher = new Dispatcher([ new Middlewares\Honeypot() ]); $response = $dispatcher->dispatch(new ServerRequest());
用法
在您的表单中,您必须包含一个 <input>
元素,该元素将用作陷阱
<html> <head> <style type="text/css"> input[name="hpt_name"] { display: none; } </style> </head> <body> <form method="POST"> <!-- This is the honeypot --> <input type="text" name="hpt_name" arial-label="Please, do not fill this input"> <label> User: <input type="text" name="username"> </label> <label> Password: <input type="password" name="password"> </label> </form> </body> </html>
默认情况下,中间件期望输入名称为 hpt_name
,但您可以更改它。请注意,CSS代码用于隐藏蜜罐,因此用户看不到任何内容,只有机器人。您可能还需要添加一些可访问性属性,如 aria-label
以供屏幕阅读器使用。
//Check the default "htp_name" value $honeypot = new Middlewares\Honeypot(); //Check other value, for example "nobots" $honeypot = new Middlewares\Honeypot('nobots');
可选地,您可以为检测到垃圾邮件时创建错误响应(403
)提供 Psr\Http\Message\ResponseFactoryInterface
作为第二个参数。如果没有定义,将自动使用 Middleware\Utils\Factory。
$responseFactory = new MyOwnResponseFactory(); $honeypot = new Middlewares\Honeypot('htp_name', $responseFactory);
辅助工具
getField
此静态方法提供了一种轻松创建输入字段的方式,接受两个参数:输入名称和用于屏幕阅读器的标签。如果没有提供名称,则使用之前传递给中间件的名称。
示例
<form method="POST"> <?= Middlewares\Honeypot::getField('htp_name', 'Please, do not fill this input') ?> <label> User: <input type="text" name="username"> </label> <label> Password: <input type="password" name="password"> </label> </form>
getHiddenField
此静态方法生成的输入字段与 getField()
相似,但添加了内联CSS以直接隐藏字段。注意:这可能更容易被某些机器人检测到。如果您想用隐藏字段的方式更有创意,请结合使用 getField()
和自定义CSS(或JS)。
<form method="POST"> <?= Middlewares\Honeypot::getHiddenField() ?> <label> User: <input type="text" name="username"> </label> <label> Password: <input type="password" name="password"> </label> </form>
有关最近更改的更多信息,请参阅 CHANGELOG,有关贡献的详细信息,请参阅 CONTRIBUTING。
MIT许可(MIT)。有关更多信息,请参阅 LICENSE。