MENU

php中通过Hashids将整数转化为类似YouTube唯一字符串

June 3, 2019 • 已被 128 位童鞋围观过 • 代码分享,教程文章

hashids是一个可以生成类似于 YouTuBe 那种唯一字符串 ID 的功能,可以对用户隐藏数据库中的真正数字ID
下面是 官方介绍的翻译

从整数生成简短的唯一id, 可以理解为数字编码库即可,几乎支持市面上所有语言。 
它的原理就是从数字经过一个加盐(salted)算法产生一个哈希(hash)字符串。这样算法就是通过混淆使结果具有不可预测性,而唯一性依然由数字本身来达成,从而得到足够短,不可预测且唯一的 ID。

OK 话不多说 开始安装 以下是WDCP环境下的 其他环境 自行替换 phpize 和 configure地址

git clone https://github.com/cdoco/hashids.phpc.git
cd hashids.phpc
/www/wdlinux/apache_php-7.1.10/bin/phpize
./configure --with-php-config=/www/wdlinux/apache_php-7.1.10/bin/php-config  && make && make install

OK 安装完毕 修改PHP.ini 你可以设置一些选项在 php.ini 里,或者你也可以在构造方法里面设置,但是我推荐你在 php.ini 中设置,这样你可以拥有更好的性能。

[hashids]
extension=hashids.so
//默认是空字符串
hashids.salt=yooer.me
//默认长度是 0
hashids.min_hash_length=10
//默认是 abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890
//你可以自己设置它,比如你使用全部小写的字符
hashids.alphabet=abcdefghijklmnopqrstuvwxyz

上Demo

$hashids = new Hashids();
$hash = $hashids->encode(1, 2, 3, 4, 5);
$numbers = $hashids->decode($hash);
//或者你可以用静态方法调用
$hash = Hashids::encode(1, 2, 3, 4, 5);
$numbers = Hashids::decode($hash);

性能提升

原来有纯 php 代码实现的一个功能,现在把它封装成了一个 php 扩展,性能比纯 php 的版本提升了百倍左右

其他

$hashids = new Hashids();
$hash = $hashids->encode(1, 2, 3, 4, 5); 
$hash = $hashids->encode([1, 2, 3, 4, 5]); 

构造方法的参数

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
Last Modified: September 28, 2023