universetech-inc / hashids
从数字生成短小、唯一、非顺序的ID(如YouTube和Bitly)
v0.1.1
2023-06-08 02:09 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 (*).
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]
更多选项
将输入ID传递给encode()
函数的几种方法
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的ObjectIds,这很有用。请注意,没有对您可以传递的十六进制数的限制(它不一定是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