在開發爬蟲、連結驗證、圖片檢查、API 健康檢查等功能時,我們常需判斷一個遠端 URL(網頁、圖片、影片、檔案)是否真實可存取。PHP 提供了多種途徑,本文深度解析三種主流方法:**cURL**、**get_headers()**、**file_get_contents()** 的原理、優缺點、適用場景與最佳實踐代碼。
<?php
function is_url_valid_curl(string $url, int $timeout = 10): bool
{
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_NOBODY => true, // HEAD 請求
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true, // 追蹤 301/302
CURLOPT_CONNECTTIMEOUT => $timeout,
CURLOPT_TIMEOUT => $timeout,
CURLOPT_SSL_VERIFYPEER => false, // 正式環境請設 true 並配置 CA
CURLOPT_USERAGENT => 'Mozilla/5.0 (PHP URL Validator)',
]);
$result = curl_exec($ch);
$valid = false;
if ($result !== false) {
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 2xx 成功、3xx 重定向(已追蹤至最終)通常視為有效
// 嚴格模式只接受 200;寬鬆模式接受 2xx/3xx
$valid = ($code >= 200 && $code < 400);
}
curl_close($ch);
return $valid;
}
// 進階:取得詳細資訊
function get_url_info_curl(string $url, int $timeout = 10): ?array
{
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_NOBODY => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_CONNECTTIMEOUT => $timeout,
CURLOPT_TIMEOUT => $timeout,
]);
curl_exec($ch);
if (curl_errno($ch)) {
curl_close($ch);
return null;
}
$info = curl_getinfo($ch);
curl_close($ch);
return [
'http_code' => $info['http_code'],
'content_type' => $info['content_type'] ?? 'unknown',
'content_length' => $info['content_length_download'] ?? -1,
'total_time' => $info['total_time'],
'effective_url' => $info['url'], // 重定向後最終 URL
];
}
?>
Content-Type、Content-Length 等allow_url_fopen = On(php.ini 設定,許多共享主機關閉)default_socket_timeout 限制,預設 60 秒,易卡死腳本)get_headers() 可能誤判(實際發送的是 HEAD)<?php
function is_url_valid_get_headers(string $url): bool
{
// 檢查環境支援
if (!ini_get('allow_url_fopen')) {
trigger_error('allow_url_fopen 關閉,無法使用 get_headers()', E_USER_WARNING);
return false;
}
// 可選參數 1:解析標頭為關聯陣列
$headers = @get_headers($url, 1);
if ($headers === false) {
return false; // 連線失敗、DNS 解析失敗、超時等
}
// $headers[0] 為狀態行,如 "HTTP/1.1 200 OK"
$statusLine = $headers[0] ?? '';
return (bool)preg_match('~HTTP/\d\.\d\s+(2\d\d|3\d\d)~', $statusLine);
}
// 取得 Content-Type 等資訊
$headers = @get_headers('https://example.com/image.png', 1);
if ($headers) {
echo "Content-Type: " . ($headers['Content-Type'] ?? 'unknown');
echo "Content-Length: " . ($headers['Content-Length'] ?? 'unknown');
}
?>
allow_url_fopen = Ondefault_socket_timeout 限制)@ 抑制或 try-catch(需配合錯誤處理器)極小型檔案(如幾 KB 的設定檔)、確定環境允許、不介意效能的一次性腳本。
<?php
// 不推薦用於單純驗證 URL
$content = @file_get_contents($url);
$valid = ($content !== false); // 即使是 404 頁面 HTML 也會回傳字串,非 false!
// 還需額外解析 HTTP 狀態碼($http_response_header 變數),麻煩且不靠譜
?>
| 維度 | cURL (HEAD) | get_headers() | file_get_contents() |
|---|---|---|---|
| 速度/頻寬 | ⭐⭐⭐⭐⭐ (只取標頭) | ⭐⭐⭐⭐ (只取標頭) | ⭐ (下載全文) |
| 超時控制 | ⭐⭐⭐⭐⭐ (毫秒級精確) | ⭐ (只能靠 ini_set) | ⭐ (只能靠 ini_set) |
| HTTPS/重定向/認證 | ⭐⭐⭐⭐⭐ 完整支援 | ⭐⭐ 基礎支援 | ⭐⭐ 基礎支援 |
| 依賴擴展/設定 | 需 cURL 擴展 (標準內建) | 需 allow_url_fopen=On | 需 allow_url_fopen=On |
| 並發檢查 | ⭐⭐⭐⭐⭐ (curl_multi) | ❌ 不支援 | ❌ 不支援 |
| 獲取元資料 | ⭐⭐⭐⭐⭐ (curl_getinfo) | ⭐⭐⭐ (標頭陣列) | ⭐ ($http_response_header) |
| 推薦指數 | ⭐⭐⭐⭐⭐ 首選 | ⭐⭐⭐ 備選 | ⭐ 不推薦 |
function_exists('curl_init') 判斷自動降級。curl_multi_* 並發,單執行緒循環會慢到不可接受。200 OK2xx、3xx(已追蹤重定向)<?php
class UrlValidator
{
private int $timeout;
private string $userAgent;
public function __construct(int $timeout = 10, string $userAgent = 'Mozilla/5.0 (PHP UrlValidator)')
{
$this->timeout = $timeout;
$this->userAgent = $userAgent;
}
public function isValid(string $url, bool $strict = true): bool
{
if (function_exists('curl_init')) {
return $this->checkByCurl($url, $strict);
}
return $this->checkByGetHeaders($url, $strict);
}
public function getInfo(string $url): ?array
{
if (function_exists('curl_init')) {
return $this->getInfoByCurl($url);
}
return $this->getInfoByGetHeaders($url);
}
private function checkByCurl(string $url, bool $strict): bool
{
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_NOBODY => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_CONNECTTIMEOUT => $this->timeout,
CURLOPT_TIMEOUT => $this->timeout,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_USERAGENT => $this->userAgent,
]);
$result = curl_exec($ch);
$valid = false;
if ($result !== false) {
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$valid = $strict ? ($code === 200) : ($code >= 200 && $code < 400);
}
curl_close($ch);
return $valid;
}
private function checkByGetHeaders(string $url, bool $strict): bool
{
if (!ini_get('allow_url_fopen')) return false;
$headers = @get_headers($url, 1);
if ($headers === false) return false;
$line = $headers[0] ?? '';
if ($strict) {
return (bool)preg_match('~HTTP/\d\.\d\s+200\s~', $line);
}
return (bool)preg_match('~HTTP/\d\.\d\s+(2\d\d|3\d\d)\s~', $line);
}
private function getInfoByCurl(string $url): ?array
{
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_NOBODY => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_CONNECTTIMEOUT => $this->timeout,
CURLOPT_TIMEOUT => $this->timeout,
CURLOPT_USERAGENT => $this->userAgent,
]);
curl_exec($ch);
if (curl_errno($ch)) { curl_close($ch); return null; }
$info = curl_getinfo($ch);
curl_close($ch);
return [
'http_code' => $info['http_code'],
'content_type' => $info['content_type'] ?? null,
'content_length' => $info['content_length_download'] ?? -1,
'total_time' => $info['total_time'],
'final_url' => $info['url'],
];
}
private function getInfoByGetHeaders(string $url): ?array
{
if (!ini_get('allow_url_fopen')) return null;
$headers = @get_headers($url, 1);
if ($headers === false) return null;
return [
'http_code' => (int)preg_replace('~\D~', '', $headers[0] ?? '0'),
'content_type' => $headers['Content-Type'] ?? null,
'content_length' => isset($headers['Content-Length']) ? (int)$headers['Content-Length'] : -1,
];
}
}
// 使用
$validator = new UrlValidator(5);
var_dump($validator->isValid('https://www.google.com'));
var_dump($validator->getInfo('https://www.google.com/logo.png'));
?>
判斷遠端 URL 有效性,**cURL 是專業級首選**,功能完整、效能最優、可控性最強;get_headers() 為無 cURL 環境下的備選方案;file_get_contents() 僅適合極簡單、極小檔、一次性任務。根據專案環境與需求選擇正確工具,並封裝成可複用元件,才能構建穩健、高效的系統。