首頁  >  文章  >  後端開發  >  PHP 擴充功能之根據數字產生唯一的字串 ID

PHP 擴充功能之根據數字產生唯一的字串 ID

不言
不言原創
2018-04-13 16:01:282211瀏覽

這篇文章給大家分享的內容是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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn