souplette/fusbup

到 Mozilla Public Suffix List 的快速且内存高效的接口。

1.0.8 2024-05-15 07:30 UTC

README

codecov

一个快速且内存高效的 PHP 库,用于查询 Mozilla 公共后缀列表

安装

composer require souplette/fusbup

基本用法

查询有效顶级域名(eTLD)

use Souplette\FusBup\PublicSuffixList;

$psl = new PublicSuffixList();
// get the eTLD (short for Effective Top-Level Domain) of a domain
assert($psl->getEffectiveTLD('foo.co.uk') === 'co.uk');
// check if a domain is an eTLD
assert($psl->isEffectiveTLD('fukushima.jp'));
// split a domain into it's private and eTLD parts
assert($psl->splitEffectiveTLD('www.foo.co.uk') === ['www.foo', 'co.uk']);

查询可注册域名(即 eTLD+1)

use Souplette\FusBup\PublicSuffixList;

$psl = new PublicSuffixList();
// get the registrable part (eTLD+1) of a domain
assert($psl->getRegistrableDomain('www.foo.co.uk') === 'foo.co.uk');
// split a domain into it's private and registrable parts.
assert($psl->splitRegistrableDomain('www.foo.co.uk') === ['www', 'foo.co.uk']);

检查 Cookie 域名的适用性

PublicSuffixList 类实现了 RFC6265 算法,用于将 Cookie 域名与请求域名匹配。

use Souplette\FusBup\PublicSuffixList;

$psl = new PublicSuffixList();
// check if a cookie domain is applicable to a hostname
$requestDomain = 'my.domain.com'
$cookieDomain = '.domain.com';
assert($psl->isCookieDomainAcceptable($requestDomain, $cookieDomain));
// cookie are rejected if their domain is an eTLD:
assert(false === $psl->isCookieDomainAcceptable('foo.com', '.com'))

国际化域名

所有返回域名的 PublicSuffixList 方法都将它们以它们的 规范 ASCII 形式返回。

use Souplette\FusBup\PublicSuffixList;
use Souplette\FusBup\Utils\Idn;

$psl = new PublicSuffixList();
assert($psl->getRegistrableDomain('☕.example') === 'xn--53h.example');
// use Idn::toUnicode() to convert them back to unicode if needed:
assert(Idn::toUnicode('xn--53h.example') === '☕.example');

性能

截至 2023 年,公共后缀列表包含大约 10,000 条规则。为了在所有使用场景中达到最大效率,PublicSuffixList 类可以使用两种具有不同性能特性的搜索算法。

第一个(默认)使用编译为二进制字符串的 DAFSA(这是 Gecko 和 Chromium 引擎中使用的算法)。第二个使用编译为 PHP 代码的压缩后缀树。

这里是他们各自优缺点的总结

  • DAFSA
    • 👍 更高效的内存使用(这只是 50Kb 的内存字符串)
    • 👍 加载更快(在 SSD 上大约 20μs)
    • 👎 搜索较慢(大约 100,000 ops/sec 的顺序)
  • 后缀树
    • 👎 内存效率较低(大约 4Mb 的内存)
    • 👎 加载较慢(没有 opcache 大约 4ms,使用 opcache 预加载时 500μs)
    • 👍 搜索更快(大约 1,000,000 ops/sec 的顺序)

注意,在这两种情况下,数据库都将被惰性加载。

我应该使用哪种搜索算法?

嗯,这取决于你的使用场景,但基于上述特性,我会说:除非你的应用程序每秒将进行数百次搜索,否则请坚持使用默认的(DAFSA)算法。

告诉我如何使用它们?

可以通过将适当的加载器传递给 PublicSuffixList 构造函数来使用这两种算法。

DAFSA

use Souplette\FusBup\Loader\DafsaLoader;
use Souplette\FusBup\PublicSuffixList;

$psl = new PublicSuffixList(new DafsaLoader());
// since DafsaLoader is the default, the following is equivalent:
$psl = new PublicSuffixList();

后缀树

use Souplette\FusBup\Loader\SuffixTreeLoader;
use Souplette\FusBup\PublicSuffixList;

$psl = new PublicSuffixList(new SuffixTreeLoader());

你还应该配置 opcache 以预加载数据库

在你的 php.ini

opcache.enabled=1
opcache.preload=/path/to/my/preload-script.php

在你的预加载脚本中

opcache_compile_file('/path/to/vendor/ju1ius/fusbup/Resources/psl.php');