当前位置: 首页 > 工具软件 > hashids > 使用案例 >

php hashids 数字(正整数)加密字条串方法(用于从数字生成类似 YouTube 的 id。不想向用户公开数据库数字 ID 时使用它)

东门楚
2023-12-01

用于从数字(正整数)生成类似 YouTube 的 id。当您不想向用户公开数据库数字 ID 时使用它

官网:

https://hashids.org/php/

https://github.com/vinkla/hashids 下载

安装:

composer require hashids/hashids

一、数字加密

例子:加密1

        $hashids = new Hashids();
        $id = $hashids->encode(1); // jR
        dump($id);//jR
        $numbers = $hashids->decode($id); // [1, 2, 3]
        dump($numbers);die;
        ^ array:1 [▼
              0 => 1
          ]

例子:同时加密多个:1,2,3

use Hashids\Hashids;

$hashids = new Hashids();

$id = $hashids->encode(1, 2, 3); // o2fXhV
//下面的用法与上面一样的效果
//$id->encode(1, 2, 3); // o2fXhV
//$id->encode([1, 2, 3]); // o2fXhV
//$id->encode('1', '2', '3'); // o2fXhV
//$id->encode(['1', '2', '3']); // o2fXhV
//$id = $hashids->decode($id); // [1, 2, 3]
//输出
dump($numbers);
^ array:3 [▼
  0 => 1
  1 => 2
  2 => 3
]

例子:就算加密同一个ID=1,不同的项目得出来都是是不一样的,有唯一性

new Hashids('项目名称', 最少长度,'加密串')

不设置最少长度就自动长度

use Hashids\Hashids;

$hashids = new Hashids('项目1');
$hashids->encode(1); // Z4UrtW

$hashids = new Hashids('项目2');
$hashids->encode(1); // gPUasb

例子:加密出来的字符串有最小长度

new Hashids('项目名称', 最少长度,'加密串')

不设置最少长度就自动长度

use Hashids\Hashids;

//不设置最低长度
$hashids = new Hashids(); // no padding
$hashids->encode(1); // jR

//设置最低长度,这里最少有10个字符串,如果加密值比较大那么加密得出的字符串肯定超过10位
$hashids = new Hashids('', 10); // pad to length 10
$hashids->encode(1); // VolejRejNm

例子:自定义加密串

use Hashids\Hashids;

$hashids = new Hashids('', 0, 'abcdefghijklmnopqrstuvwxyz'); // all lowercase
$hashids->encode(1, 2, 3); // mdfphx

二、字符串加密

如果想把字符串也加密,只能先把字符串转成十六进制数字再加密

字符串转成十六进制数bin2hex()函数方法:

//字符串转成十六进制数字
dump(bin2hex('8c070749-a827-4a8e-afec-47f02f3fa69a'));

再加密码:

use Hashids\Hashids;

$hashids = new Hashids();

$id = $hashids->encodeHex('507f1f77bcf86cd799439011'); // y42LW46J9luq3Xq9XMly
$hex = $hashids->decodeHex($id); // 507f1f77bcf86cd799439011

 类似资料: