短網址服務核心在於將長網址映射為短代碼。本文示範以 crc32 雜湊長網址,再以 Base62(0-9, a-z, A-Z)編碼為短代碼的完整實作,包含 HTML 表單與 PHP 後端邏輯。
index.html<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8"><title>URL Shortener</title></head>
<body>
<form action="urlShort.php" method="post">
<input type="text" name="url" size="40" placeholder="輸入欲縮短的網址">
<input type="submit" value="生成短網址">
</form>
</body>
</html>
urlShort.php<?php
header("Content-Type: text/html; charset=UTF-8");
/** Base62 編碼:0-9, A-Z, a-z */
function base62($x) {
$show = '';
while ($x > 0) {
$s = $x % 62;
if ($s > 35) { // 36-61 -> a-z
$s = chr($s + 61);
} elseif ($s > 9) { // 10-35 -> A-Z
$s = chr($s + 55);
} // 0-9 保持數字
$show .= $s;
$x = floor($x / 62);
}
return $show ?: '0';
}
/** 產生短代碼 */
function url_short($url) {
$hash = crc32($url); // 32 位無號整數
$unsigned = sprintf("%u", $hash); // 轉無號字串
return base62($unsigned);
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['url'])) {
$short = url_short($_POST['url']);
echo "生成的短代碼:<a href='{$_POST['url']}' target='_blank'>$short</a>";
}
?>
https://example.com/very/long/pathcrc32() 計算 32-bit 雜湊值(如 1234567890)sprintf("%u") 確保無號整數字串base62() 將整數轉為 62 進位字串(如 3y7)https://your.domain/3y7short_code -> long_url 映射,並處理碰撞(crc32 碰撞機率約 1/40 億,可接受)。md5 取前 64 位再 Base62,或引入分散式 ID 生成器(Snowflake)。更多短網址演算法討論:PHP 短網址生成原理與實現