使用Hashids隐藏自增ID

通过Composer安装Hashids
[root@localhost ~]# mkdir Hashids
[root@localhost ~]# cd Hashids/
[root@localhost Hashids]# composer require hashids/hashids
Do not run Composer as root/super user! See https://getcomposer.org/root for details
Continue as root/super user [yes]? yes
Using version ^2.0 for hashids/hashids
./composer.json has been created
Running composer update hashids/hashids
Loading composer repositories with package information
Updating dependencies
Lock file operations: 1 install, 0 updates, 0 removals
  - Locking hashids/hashids (2.0.4)
Writing lock file
Installing dependencies from lock file (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
  - Installing hashids/hashids (2.0.4): Extracting archive
2 package suggestions were added by new dependencies, use `composer suggest` to see details.
Generating autoload files
[root@localhost Hashids]# 
 
把/Hashids目录复制到项目,PHP文件引入/Hashids/vendor/autoload.php即可使用Hashids,下面是demo代码:

<?php
require_once __DIR__ . '/Hashids/vendor/autoload.php';

// 实例化时可加盐及指定密文最短长度
$hashids = new \Hashids\Hashids('俺是加盐字符串,俺可以更改为任意字符串!', 32);

//========== 单个ID加密 ==========//
$id       = 12345; // 注意只能使用数字或数字字符串,如果字符串包含字母则会报Notice错误
$idEncode = $hashids->encode($id);
$idDecode = $hashids->decode($idEncode)[0]; // 注意decode()方法后面要加“[0]”
echo "原始ID:{$id}" . PHP_EOL;       // 原始ID:12345
echo "加密ID:{$idEncode}" . PHP_EOL; // 加密ID:bv9wj4yWdO0xXQ4WwB1qVPDrGl8nNoJ3
echo "解密ID:{$idDecode}" . PHP_EOL; // 解密ID:12345

//========== 多个ID加密 ==========//
$idArr       = array(12345, 10086, 67890);
$idArrEncode = $hashids->encode($idArr); // 多个ID加密的结果也是一串字符串
$idArrDecode = $hashids->decode($idArrEncode);
print_r($idArrDecode);
/********** 输出结果·开始 **********
Array
(
    [0] => 12345
    [1] => 10086
    [2] => 67890
)
**********输出结果·结束 **********/

Copyright © 2024 码农人生. All Rights Reserved