Home >Backend Development >PHP Tutorial >PHP extension to generate unique string ID based on numbers

PHP extension to generate unique string ID based on numbers

不言
不言Original
2018-04-13 16:01:282289browse

The content shared with you in this article is a PHP extension that generates a unique string ID based on numbers. It has a certain reference value. Friends in need can refer to it.

Hashids is a method that can generate unique string IDs. Non-sequential string ID numbers, it can also decrypt these IDs, you can use it to encrypt numeric IDs that you don't want to expose to users.

Installation

$ git clone https://github.com/cdoco/hashids.phpc.git
$ cd hashids.phpc
$ phpize && ./configure && make && make install

You can set some options in php.ini, or you can set them in the constructor, but I recommend you set them in php.ini so that you can have Better performance.

[hashids]
extension=hashids.so

//默认是空字符串
hashids.salt=cdoco

//默认长度是 0
hashids.min_hash_length=20

//默认是 abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890
//你可以自己设置它,比如你使用全部小写的字符
hashids.alphabet=abcdefghijklmnopqrstuvwxyz

Quick Start

$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]

Performance

Originally there was a function implemented by pure PHP code, now it is encapsulated into a PHP extension, and the performance is improved compared to the pure PHP version About a hundred times more

PHP extension to generate unique string ID based on numbers

##Others

$hashids = new Hashids();

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

Parameters of the construction method

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

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

16 hexadecimal encryption and decryption

$hashids = new Hashids();

$hash = $hashids->encodeHex('FFFFDD'); // rYKPAK
$hex = $hashids->decodeHex($hash); // FFFFDD

                                                                                               

The above is the detailed content of PHP extension to generate unique string ID based on numbers. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn