爬蟲、連結檢查、短網址還原等場景常需取得經過 301/302/307 重定向後的最終目標 URL。本文提供基於 Socket `HEAD` 請求的輕量級實作,避免下載完整 Body、支援多層重定向追蹤、防循環、可設定超時。
<?php
class RedirectUrl
{
private $url;
private $maxRedirects = 10;
private $timeout = 10;
public function __construct(string $url, int $maxRedirects = 10, int $timeout = 10) {
$this->url = $url;
$this->maxRedirects = $maxRedirects;
$this->timeout = $timeout;
}
/** 取得最終 URL */
public function getFinalUrl(): string {
$redirects = $this->getAllRedirects($this->url);
return $redirects ? end($redirects) : $this->url;
}
/** 取得所有重定向鏈 */
public function getAllRedirects(string $url): array {
$redirects = [];
$currentUrl = $url;
$count = 0;
while ($count < $this->maxRedirects) {
$nextUrl = $this->getRedirectUrl($currentUrl);
if (!$nextUrl) break;
if (in_array($nextUrl, $redirects, true)) break; // 循環偵測
$redirects[] = $nextUrl;
$currentUrl = $nextUrl;
$count++;
}
return $redirects;
}
/** 單次 HEAD 請求取得 Location */
private function getRedirectUrl(string $url): ?string {
$parts = @parse_url($url);
if (!$parts || empty($parts['host'])) return null;
$parts['path'] = $parts['path'] ?? '/';
$port = $parts['port'] ?? ($parts['scheme'] === 'https' ? 443 : 80);
$host = $parts['host'];
$path = $parts['path'] . ($parts['query'] ? '?' . $parts['query'] : '');
// 建立 Socket 連線 (支援 SSL)
$schemePrefix = ($parts['scheme'] === 'https') ? 'ssl://' : '';
$fp = @fsockopen($schemePrefix . $host, $port, $errno, $errstr, $this->timeout);
if (!$fp) return null;
// 發送 HEAD 請求
$request = "HEAD {$path} HTTP/1.1\r\n";
$request .= "Host: {$host}\r\n";
$request .= "Connection: Close\r\n";
$request .= "User-Agent: PHP-RedirectResolver/1.0\r\n\r\n";
fwrite($fp, $request);
// 讀取回應標頭
$response = '';
while (!feof($fp)) {
$response .= fread($fp, 8192);
if (strpos($response, "\r\n\r\n") !== false) break; // 僅需標頭
}
fclose($fp);
// 解析 Location
if (preg_match('/^Location:\s*(.+?)\s*$/mi', $response, $m)) {
$location = trim($m[1]);
// 處理相對 URL
if (strpos($location, 'http') !== 0) {
$base = $parts['scheme'] . '://' . $host;
if ($location[0] === '/') {
$location = $base . $location;
} else {
$location = $base . dirname($parts['path']) . '/' . $location;
}
}
return $location;
}
return null;
}
}
<?php
require 'RedirectUrl.php';
$resolver = new RedirectUrl('https://t.cn/shortlink', 5, 5);
echo "最終 URL: " . $resolver->getFinalUrl() . "\n";
echo "完整重定向鏈:\n";
foreach ($resolver->getAllRedirects('https://t.cn/shortlink') as $i => $u) {
echo " {$i}. {$u}\n";
}
// 進階:檢查圖片是否為預設圖 (防盜鏈回退)
function getShowPic(string $url, string $noimg = 'noimg.gif', string $fallback = ''): string {
$resolver = new RedirectUrl($url);
$realUrl = $resolver->getFinalUrl();
return (strpos($realUrl, $noimg) !== false && $fallback) ? $fallback : $url;
}
echo getShowPic('https://example.com/img.jpg', 'default.jpg', 'https://cdn.example.com/placeholder.jpg');
function getFinalUrlCurl(string $url, int $maxRedirects = 10): string {
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_HEADER => true,
CURLOPT_NOBODY => true, // HEAD 請求
CURLOPT_FOLLOWLOCATION => false, // 手動處理重定向
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_USERAGENT => 'PHP-RedirectResolver/1.0',
CURLOPT_SSL_VERIFYPEER => false, // 生產環境請設 true 並配置 CA
CURLOPT_MAXREDIRS => $maxRedirects,
]);
$redirects = [];
$currentUrl = $url;
for ($i = 0; $i < $maxRedirects; $i++) {
curl_setopt($ch, CURLOPT_URL, $currentUrl);
$response = curl_exec($ch);
if ($response === false) break;
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode < 300 || $httpCode >= 400) break;
// 從標頭解析 Location
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $headerSize);
if (preg_match('/^Location:\s*(.+?)\s*$/mi', $header, $m)) {
$nextUrl = trim($m[1]);
if (in_array($nextUrl, $redirects)) break;
$redirects[] = $nextUrl;
$currentUrl = $nextUrl;
} else {
break;
}
}
curl_close($ch);
return $currentUrl;
}
| 特性 | Socket (fsockopen) | cURL |
|---|---|---|
| HTTPS 支援 | 需 `ssl://` 前綴、手動驗證憑證 | 原生支援、完整 TLS 選項 |
| 重定向處理 | 手動遞迴、完全可控 | 可自動/手動、支援 `CURLOPT_MAXREDIRS` |
| Cookie/Session | 手動管理 | `CURLOPT_COOKIEJAR/FILE` 自動 |
| Proxy 支援 | 手動 CONNECT | 原生 `CURLOPT_PROXY` |
| 效能 | 較輕量、無依賴 | 功能豐富、略重 |
| 建議場景 | 簡單 HTTP/HTTPS、無外部依賴環境 | 生產爬蟲、複雜認證、Proxy、HTTP/2 |
此實作輕量、無外部依賴 (Socket 版),適合嵌入各類專案作為 URL 解析基礎組件。