kytleblanker / hashids
从数字生成短、唯一、非顺序的id(如YouTube和Bitly)
4.1.0
2020-11-26 19:24 UTC
Requires
- php: ^7.2 || ^8.0
- ext-mbstring: *
Requires (Dev)
- phpunit/phpunit: ^8.0 || ^9.4
- squizlabs/php_codesniffer: ^3.5
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);
快速示例
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的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