萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 實作短網址生成演算法(Base62 編碼變體)

前言

短網址服務(如 bit.ly、t.cn)核心在於將長 URL 映射為短代碼。本文介紹一種基於 SHA-256 雜湊與自定義字符集的 PHP 實作,透過隨機步長切割雜湊值,生成不可預測的短代碼。

演算法流程

  1. 對原始 URL 計算 SHA-256 雜湊值(64 字元十六進制)。
  2. 設定隨機步長(8~16),將雜湊值切割為多段。
  3. 每段轉為整數,對自定義字符集長度取模,映射為字符。
  4. 拼接所有字符組成最終短代碼。

程式碼實作

<?php
class ShortUrlGenerator {
    private $charset = '1qaz2wsx3edc4rfv5t-gb6yhn7ujm8ik9ol0p_'; // 64 字元
    private $charsetLen;

    public function __construct() {
        $this->charsetLen = strlen($this->charset);
    }

    public function createCode($url) {
        $hash = hash('sha256', $url);
        $step = mt_rand(8, 16); // 隨機步長增加不可預測性
        $count = ceil(strlen($hash) / $step);
        $code = '';

        for ($i = 0; $i < $count; $i++) {
            $segment = substr($hash, $i * $step, $step);
            $num = 0x3fffffff & (1 * '0x' . $segment); // 限制為 30 位整數
            $index = $num % $this->charsetLen;
            $code .= $this->charset[$index];
        }
        return $code;
    }
}

// 使用範例
$generator = new ShortUrlGenerator();
$shortCode = $generator->createCode('https://www.example.com/very/long/url/path?param=value');
echo "短代碼: $shortCode"; // 如: 8ik9ol0p
?>

特點與注意事項

  • 碰撞機率低:SHA-256 + 隨機步長使碰撞極難發生,但生產環境仍需資料庫唯一索引保障。
  • 非可逆:無法從短代碼反推原 URL,需資料庫存儲映射關係。
  • 字符集可自定義:避開易混淆字元(如 0/O, 1/l),提升用戶體驗。

擴展建議

實際部署時建議:

  1. 使用 Redis/Memcached 緩存熱門映射。
  2. 資料庫建立 short_code 唯一索引,碰撞時重新生成。
  3. 加入訪問統計、過期時間等業務欄位。
copyright © 萬盛學電腦網 all rights reserved