Hashids 是一个可以生成唯一的非顺序的字符串 ID 号码,它还可以对这些 ID 进行解密,你可以利用它来加密你不想暴露给用户的数字 ID。
安装
$ git clone https://github.com/cdoco/hashids.phpc.git
$ cd hashids.phpc
$ phpize && ./configure && make && make install
你可以设置一些选项在 php.ini 里,或者你也可以在构造方法里面设置,但是我推荐你在 php.ini 中设置,这样你可以拥有更好的性能。
[hashids]
extension=hashids.so//默认是空字符串
hashids.salt=cdoco//默认长度是 0
hashids.min_hash_length=20//默认是 abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890
//你可以自己设置它,比如你使用全部小写的字符
hashids.alphabet=abcdefghijklmnopqrstuvwxyz
快速开始
$hashids = new Hashids();$hash = $hashids->encode(1, 2, 3, 4, 5); // ADf9h9i0sQ
$numbers = $hashids->decode($hash); // [1, 2, 3, 4, 5]//或者你可以用静态方法调用
$hash = Hashids::encode(1, 2, 3, 4, 5); // ADf9h9i0sQ
$numbers = Hashids::decode($hash); // [1, 2, 3, 4, 5]
性能
原来有纯 php 代码实现的一个功能,现在把它封装成了一个 php 扩展,性能比纯 php 的版本提升了百倍左右
其他
$hashids = new Hashids();$hash = $hashids->encode(1, 2, 3, 4, 5); // ADf9h9i0sQ
$hash = $hashids->encode([1, 2, 3, 4, 5]); // ADf9h9i0sQ
构造方法的参数
new Hashids(string $salt, int $min_hash_length, string $alphabet);//example
new Hashids("this is salt.", 20, 'abcdefghijklmnopqrstuvwxyz');
16 进制加密和解密
$hashids = new Hashids();$hash = $hashids->encodeHex('FFFFDD'); // rYKPAK
$hex = $hashids->decodeHex($hash); // FFFFDD