短網址服務(如 bit.ly、t.cn)核心在於將長 URL 映射為短代碼。本文介紹一種基於 SHA-256 雜湊與自定義字符集的 PHP 實作,透過隨機步長切割雜湊值,生成不可預測的短代碼。
<?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
?>
實際部署時建議:
short_code 唯一索引,碰撞時重新生成。