hashids/hashids

从数字生成短、唯一、非顺序的id(如YouTube和Bitly)

安装次数: 32,580,223

依赖: 297

建议者: 7

安全: 0

星标: 5,265

关注者: 110

分支: 418

开放问题: 0

5.0.2 2023-02-23 15:00 UTC

This package is auto-updated.

Last update: 2024-09-22 06:25:53 UTC


README

hashids

Build Status Monthly Downloads Latest Version

Hashids是一个小巧的PHP库,可以将数字生成类似于YouTube的id。当您不想将数据库的数字id暴露给用户时,可以使用它:https://hashids.org/php

入门指南

使用Composer在项目的根目录中安装此包。

composer require hashids/hashids

然后您可以将类导入到您的应用程序中

use Hashids\Hashids;

$hashids = new Hashids();

$hashids->encode(1);

注意 Hashids需要启用bcmathgmp扩展才能工作。

快速示例

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更长

注意,输出id仅填充到至少一定长度。这并不意味着它们的长度会正好是那个长度。

use Hashids\Hashids;

$hashids = new Hashids(); // no padding
$hashids->encode(1); // jR

$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

将十六进制编码而不是数字

如果您想对Mongo的ObjectIds进行编码,这很有用。注意,没有限制您可以通过多大的十六进制数(不一定是Mongo的ObjectId)传递。

use Hashids\Hashids;

$hashids = new Hashids();

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

陷阱

  1. 解码时,输出始终是数字数组(即使您只编码了一个数字)

    use Hashids\Hashids;
    
    $hashids = new Hashids();
    
    $id = $hashids->encode(1);
    
    $hashids->decode($id); // [1]
  2. 不支持编码负数。

  3. 如果您向encode()传递无效输入,将返回空字符串

    use Hashids\Hashids;
    
    $hashids = new Hashids();
    
    $id = $hashids->encode('123a');
    
    $id === ''; // true
  4. 不要将此库用作安全措施。**不要**使用它来编码敏感数据。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

诅咒词!#$%@

编写此代码的目的是将输出id放在可见位置,例如URL。因此,算法试图通过生成永远不会相邻包含以下字母的id来避免生成大多数常见的英文诅咒词。

c, f, h, i, s, t, u