短網址服務的核心在於將冗長的 URL 轉換為 5-6 碼的唯一字串。本文示範使用 PHP 實作 Base62 編碼演算法,搭配 CRC32 雜湊確保分布均勻。
<?php
function code62($x) {
$show = '';
while ($x > 0) {
$s = $x % 62;
if ($s > 35) {
$s = chr($s + 61); // a-z
} elseif ($s > 9 && $s <= 35) {
$s = chr($s + 55); // A-Z
}
$show .= $s;
$x = floor($x / 62);
}
return $show;
}
function shorturl($url) {
$url = crc32($url);
$result = sprintf("%u", $url);
return code62($result);
}
?>
這組函式可將任意網址轉換為類似 abcfc 的短代碼,最終網址形式為 https://z.cn/abcfc。
為讓短網址可直接存取,需在 .htaccess 中設定重寫規則:
RewriteEngine On
RewriteBase /
RewriteRule ^/(.*)$ link.php?url=$1 [L]
此規則將 https://z.cn/zHEYrvV 內部轉向至 link.php?url=zHEYrvV,由 PHP 解析短代碼並導向原始網址。
實際部署時,建議建立對應表儲存 short_code 與 original_url 的映射關係,避免雜湊碰撞導致誤導向。