一个 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 中设置,这样你能够拥有更好的性能。php

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

performance comparison

其余

$hashids = new Hashids();

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

构造方法的参数github

new Hashids(string $salt, int $min_hash_length, string $alphabet);

//example
new Hashids("this is salt.", 20, 'abcdefghijklmnopqrstuvwxyz');

16 进制加密和解密shell

$hashids = new Hashids();

$hash = $hashids->encodeHex('FFFFDD'); // rYKPAK
$hex = $hashids->decodeHex($hash); // FFFFDD
相关文章
相关标签/搜索