需驗證遠程資源(圖片、頁面、視頻等)是否可訪問,常用於采集器、鏈接檢測、資源完整性校驗等場景。
get_headers() —— 推薦首選原理:發送 HEAD 請求,獲取 HTTP 響應頭,分析狀態碼(200 表示成功)。
前置條件:
php.ini 開啟 allow_url_fopen = Onphp_openssl 擴展支持 HTTPS函數簽名:array get_headers(string $url, int $format = 0)
$format = 0:返回數值索引數組(原始頭部行)$format = 1:返回關聯數組(解析後的鍵值對)function isUrlValid($url) {
if (!function_exists('get_headers')) return false;
$headers = @get_headers($url, 1);
if ($headers === false) return false;
// 檢查狀態行(數值索引 0)或關聯鍵
$statusLine = $headers[0] ?? '';
return (bool)preg_match('/^HTTP\/\d\.\d\s+200\b/', $statusLine);
}
// 使用
$url = "https://example.com/image.jpg";
if (isUrlValid($url)) {
echo "資源有效";
} else {
echo "資源無效或不可達";
}
| 優點 | 缺點 |
|---|---|
| 只獲取頭部,帶寬極低 | 需 allow_url_fopen=On(共享主機常關閉) |
| 代碼簡潔,無需額外擴展 | 跟隨重定向行為不可控(PHP 5.3.4+ 可用 stream context 控制) |
| 可獲取 Content-Type、Content-Length 等元信息 | 超時控制需配合 stream context |
function isUrlValidCurl($url, $timeout = 10) {
if (!function_exists('curl_init')) return false;
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_NOBODY => true, // 只獲取頭部
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => $timeout,
CURLOPT_FOLLOWLOCATION => true, // 允許重定向
CURLOPT_SSL_VERIFYPEER => false, // 生產環境建議開啟並配置 CA
CURLOPT_HEADER => true,
]);
curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $httpCode === 200;
}
優勢:精確控制超時、重定向、SSL 驗證、用戶代理、Cookie、代理等;不依賴 allow_url_fopen。
file_get_contents() / fopen() —— 不推薦用於單純檢測// 僅作演示,實際會下載整個內容,極其低效
$content = @file_get_contents($url);
return $content !== false;
缺點:下載完整內容浪費帶寬與內存;大文件可能導致腳本超時或內存溢出;錯誤處理困難。
ActiveXObject("Microsoft.XMLHTTP"):僅 IE 支持,已過時。$.ajax({type:'HEAD', ...}):受同源策略限制,跨域需 CORS 支持,適用於前端即時校驗。allow_url_fopen。get_headers():簡單場景、確認服務器開啟 allow_url_fopen 時使用。get_headers() → 失敗返回 false,對外提供統一接口。