一个 PHP 扩展: 根据数字生成唯一的字符串 ID

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 的版本提升了百倍左右

performance comparison

其他

$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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值