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

发布时间:2019-08-07 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了一个 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 的版本提升了百倍左右

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

其他

$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

脚本宝典总结

以上是脚本宝典为你收集整理的一个 PHP 扩展: 根据数字生成唯一的字符串 ID全部内容,希望文章能够帮你解决一个 PHP 扩展: 根据数字生成唯一的字符串 ID所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: