PHP使用Hashids生产可以加密/解密的短ID
Song •
0 次浏览 •
0个评论 •
2026年07月10日
Hashids是什么?
Hashids 是一个小型的 PHP 库,用于从数字生成类似 YouTube 的 ID。当你不希望将数据库的数字 ID 暴露给用户时,可以使用它:https://hashids.org/php
开始使用
在项目的根目录中,使用 Composer 安装这个包。
composer require hashids/hashids然后你可以将类导入到你的应用程序中:
use Hashids\Hashids;
$hashids = new Hashids();
$hashids->encode(1);“注意 Hashids 需要 bcmath 或 gmp 扩展才能工作。
快速示例
use Hashids\Hashids;
$hashids = new Hashids();
$id = $hashids->encode(1, 2, 3); // o2fXhV
$numbers = $hashids->decode($id); // [1, 2, 3]更多选项
向 encode() 函数传递输入 ID 的几种更多方式:
use Hashids\Hashids;
$hashids = new Hashids();
$hashids->encode(1, 2, 3); // o2fXhV
$hashids->encode([1, 2, 3]); // o2fXhV
$hashids->encode('1', '2', '3'); // o2fXhV
$hashids->encode(['1', '2', '3']); // o2fXhV
使输出 ID 唯一
通过传递一个项目名称来使你的输出 ID 唯一:
use Hashids\Hashids;
$hashids = new Hashids('My Project');
$hashids->encode(1, 2, 3); // Z4UrtW
$hashids = new Hashids('My Other Project');
$hashids->encode(1, 2, 3); // gPUasb使用填充来使输出 ID 更长
Hashids 请注意,输出 ID 仅填充至至少一定长度。这并不意味着它们将恰好是那个长度。
use Hashids\Hashids;
$hashids = new Hashids(); // 无填充
$hashids->encode(1); // jR
$hashids = new Hashids('', 10); // 填充至长度 10
$hashids->encode(1); // VolejRejNm
使用自定义字母表
use Hashids\Hashids;
$hashids = new Hashids('', 0, 'abcdefghijklmnopqrstuvwxyz'); // 全小写
$hashids->encode(1, 2, 3); // mdfphx
编码十六进制而不是数字
如果你想要编码 MongoDB 的 ObjectIds,这很有用。请注意,可以传递的十六进制数字大小没有限制(它不必是 MongoDB 的 ObjectId)。
use Hashids\Hashids;
$hashids = new Hashids();
$id = $hashids->encodeHex('507f1f77bcf86cd799439011'); // y42LW46J9luq3Xq9XMly
$hex = $hashids->decodeHex($id); // 507f1f77bcf86cd799439011陷阱
- 解码时,输出总是一个数字数组(即使你只编码了一个数字):
use Hashids\Hashids;
$hashids = new Hashids();
$id = $hashids->encode(1);
$hashids->decode($id); // [1]
不支持编码负数。
如果你向 encode() 传递无效输入,将返回一个空字符串:
use Hashids\Hashids;
$hashids = new Hashids();
$id = $hashids->encode('123a');
$id === ''; // true
- 不要使用这个库作为安全措施。不要用它来编码敏感数据。Hashids 不是一个加密库。
随机性
Hashids 的主要目的是混淆数字ID。它不是作为安全或压缩工具设计或测试的。话虽如此,这个算法确实试图使这些 ID 随机且不可预测,当编码多个相同的数字时(以下示例中显示了 3 个),没有显示模式:
use Hashids\Hashids;
$hashids = new Hashids();
$hashids->encode(5, 5, 5); // A6t1tQ
当编码一系列数字与分别编码它们时,也是如此:
use Hashids\Hashids;
$hashids = new Hashids();
$hashids->encode(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // wpfLh9iwsqt0uyCEFjHM
$hashids->encode(1); // jR
$hashids->encode(2); // k5
$hashids->encode(3); // l5
$hashids->encode(4); // mO
$hashids->encode(5); // nR-
laravel队列出现Failed to open stream: Too many open files 2025-12-26 -
Laravel保存文件到public文件夹出现Failed to open stream: Permission denied 2025-12-17 -
nginx如何查看当前访问的是哪个网址 2025-11-17 -
微信公众号回复菜单点击回复文本 2025-10-24 -
laravel+easywechat6出现No component_verify_ticket found以及修改缓存为redis 2025-09-09

ubuntu 如何安装php后如何查看php-fpm.sock文件位置?