mojgenie / hashids
从数字生成短、唯一、非顺序的ID(例如YouTube和Bitly)
dev-master / 5.0.x-dev
2023-03-29 05:23 UTC
Requires
- php: ^8.1
- ext-mbstring: *
Requires (Dev)
- phpunit/phpunit: ^10.0
Suggests
- ext-bcmath: Required to use BC Math arbitrary precision mathematics (*).
- ext-gmp: Required to use GNU multiple precision mathematics (*).
This package is not auto-updated.
Last update: 2024-09-26 10:27:33 UTC
README
Hashids 是一个小型PHP库,可以从数字生成类似于YouTube的ID。当您不希望将数据库的数字ID暴露给用户时使用它:[https://hashids.org/php](https://hashids.org/php)
入门指南
使用 Composer 在项目根目录中安装此包。
composer require hashids/hashids
然后您可以将类导入到您的应用程序中
use Hashids\Hashids; $hashids = new Hashids(); $hashids->encode(1);
注意 Hashids需要
bcmath
或gmp
扩展才能工作。
快速示例
use Hashids\Hashids; $hashids = new Hashids(); $id = $hashids->encode(1, 2, 3); // o2fXhV $numbers = $hashids->decode($id); // [1, 2, 3]
更多选项
向encode()
函数传递输入ID的几种方法
use Hashids\Hashids; $hashids = new Hashids(); $hashids->encode(1, 2, 3); // o2fXhV $hashids->encode([1, 2, 3]); // o2fXhV $hashids->encode('1', '2', '3'); // o2fXhV $hashids->encode(['1', '2', '3']); // o2fXhV
使输出ID唯一
传递一个项目名称以使输出ID唯一
use Hashids\Hashids; $hashids = new Hashids('My Project'); $hashids->encode(1, 2, 3); // Z4UrtW $hashids = new Hashids('My Other Project'); $hashids->encode(1, 2, 3); // gPUasb
使用填充使输出ID更长
注意输出ID仅填充以适应至少一定长度。这并不意味着它们将正好是那个长度。
use Hashids\Hashids; $hashids = new Hashids(); // no padding $hashids->encode(1); // jR $hashids = new Hashids('', 10); // pad to length 10 $hashids->encode(1); // VolejRejNm
使用自定义字符集
use Hashids\Hashids; $hashids = new Hashids('', 0, 'abcdefghijklmnopqrstuvwxyz'); // all lowercase $hashids->encode(1, 2, 3); // mdfphx
编码十六进制而不是数字
如果您想编码Mongo的ObjectId,这很有用。请注意,没有对您可以传递的十六进制数字大小限制(它不必是Mongo的ObjectId)。
use Hashids\Hashids; $hashids = new Hashids(); $id = $hashids->encodeHex('507f1f77bcf86cd799439011'); // y42LW46J9luq3Xq9XMly $hex = $hashids->decodeHex($id); // 507f1f77bcf86cd799439011
陷阱
-
在解码时,输出始终是数字数组(即使您只编码了一个数字)
use Hashids\Hashids; $hashids = new Hashids(); $id = $hashids->encode(1); $hashids->decode($id); // [1]
-
不支持编码负数。
-
如果您向
encode()
传递无效输入,则将返回空字符串use Hashids\Hashids; $hashids = new Hashids(); $id = $hashids->encode('123a'); $id === ''; // true
-
不要将此库用作安全措施。**不要**使用它来编码敏感数据。Hashids**不是**一个加密库。
随机性
Hashids的主要目的是混淆数字ID。它**不是**用于作为安全或压缩工具的意图或测试。话虽如此,此算法确实试图使这些ID随机且不可预测。
在编码多个相同的数字时(以下示例中显示为3)不会显示出任何模式
use Hashids\Hashids; $hashids = new Hashids(); $hashids->encode(5, 5, 5); // A6t1tQ
当编码一系列数字与单独编码它们时,结果相同
use Hashids\Hashids; $hashids = new Hashids(); $hashids->encode(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // wpfLh9iwsqt0uyCEFjHM $hashids->encode(1); // jR $hashids->encode(2); // k5 $hashids->encode(3); // l5 $hashids->encode(4); // mO $hashids->encode(5); // nR
诅咒词!#$%@
此代码的编写目的是将输出ID放置在可见位置,如URL。因此,算法试图通过生成永远不会相邻出现以下字母的ID来避免生成大多数常见的英文诅咒词。
c, f, h, i, s, t, u