0x3FFFFFFF (30 個 1) 按位與,丟棄高 2 bits。<?php
/**
* 微博風格短網址生成器
*
* @param string $url 原始長網址
* @param string $prefix 鹽值前綴 (可選,防止碰撞、區分業務)
* @param string $suffix 鹽值後綴 (可選)
* @return array 4 組 6 字符短碼
*/
function shortUrl(string $url, string $prefix = '', string $suffix = ''): array {
// 1. 自定義 Base32 字符表 (避免 0/O, 1/I, l 等易混淆字符)
$base32 = [
'a','b','c','d','e','f','g','h',
'i','j','k','l','m','n','o','p',
'q','r','s','t','u','v','w','x',
'y','z','0','1','2','3','4','5'
];
// 2. MD5 雜湊
$hex = md5($prefix . $url . $suffix); // 32 字符十六進制
// 3. 分片處理
$output = [];
$segmentCount = strlen($hex) / 8; // 固定 4
for ($i = 0; $i < $segmentCount; $i++) {
$subHex = substr($hex, $i * 8, 8); // 8 字符 = 32 bits
$intVal = hexdec($subHex) & 0x3FFFFFFF; // 取低 30 bits
$code = '';
for ($j = 0; $j < 6; $j++) { // 30 bits / 5 = 6 字符
$index = $intVal & 0x1F; // 取低 5 bits (0-31)
$code .= $base32[$index];
$intVal >>= 5; // 右移 5 bits
}
$output[] = $code;
}
return $output;
}
// 使用範例
$urls = shortUrl('https://www.example.com/very/long/url/with/query?param=value&foo=bar', 'myapp_', '_v1');
print_r($urls);
/*
Array
(
[0] => k9x2m1
[1] => p4q8r3
[2] => w7z0b5
[3] => y2c6d4
)
*/
演算法單向不可逆,**必須建立映射表** 儲存 short_code → long_url:
CREATE TABLE short_urls (
code CHAR(6) NOT NULL PRIMARY KEY, -- 短碼
long_url TEXT NOT NULL, -- 原始長網址
prefix VARCHAR(32) DEFAULT '', // 鹽值前綴
suffix VARCHAR(32) DEFAULT '', // 鹽值後綴
hits INT UNSIGNED DEFAULT 0, // 訪問計數
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
expires_at TIMESTAMP NULL DEFAULT NULL -- 可選過期時間
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 唯一索引加速查詢
CREATE UNIQUE INDEX idx_long_url_prefix_suffix ON short_urls (long_url(255), prefix, suffix);
function createShortUrl(PDO $pdo, string $longUrl, string $prefix = '', string $suffix = ''): string {
$codes = shortUrl($longUrl, $prefix, $suffix);
// 嘗試插入 4 組碼的任一組,遇到主鍵衝突則嘗試下一組
foreach ($codes as $code) {
try {
$stmt = $pdo->prepare('INSERT INTO short_urls (code, long_url, prefix, suffix) VALUES (?, ?, ?, ?)');
$stmt->execute([$code, $longUrl, $prefix, $suffix]);
return $code; // 成功
} catch (PDOException $e) {
if ($e->getCode() === '23000') continue; // Duplicate entry,試下一組
throw $e;
}
}
throw new RuntimeException('無法生成唯一短碼,請更換鹽值重試');
}
<?php
// r.php (短網址入口)
require 'bootstrap.php';
$code = $_GET['code'] ?? '';
if (!preg_match('/^[a-z0-9]{6}$/', $code)) {
http_response_code(404);
exit('Invalid code');
}
$stmt = $pdo->prepare('SELECT long_url FROM short_urls WHERE code = ?');
$stmt->execute([$code]);
$longUrl = $stmt->fetchColumn();
if ($longUrl) {
// 非同步增加點擊數 (避免阻塞重導向)
$pdo->prepare('UPDATE short_urls SET hits = hits + 1 WHERE code = ?')->execute([$code]);
// 302 臨時重導向 (保留來源 referer、利於 SEO 追蹤)
header('Location: ' . $longUrl, true, 302);
exit;
}
http_response_code(404);
exit('Short URL not found or expired');
GET short:{code} 直接獲取長網址,Miss 才查 DB,異步回填。微博短網址演算法以 MD5 分散性 + Base32 緊湊編碼 實現「長網址 → 固定 6 字符短碼」的單向映射。核心優勢:無需中央協調、天然分散式、碰撞概率極低 (4 組備選)。實際部署時,配合資料庫唯一約束、Redis 熱點緩存、非同步統計、防濫用體系,即可構建高可用、高效能的短網址服務。