PHP 內建變數 `$http_response_header` 在使用 `fopen()`、`file_get_contents()` 等串流函式開啟 HTTP/HTTPS URL 後,會自動填入伺服器回應的標頭陣列。無需 cURL 即可快速檢測遠端資源資訊。
<?php
$url = 'https://www.example.com/';
$handle = @fopen($url, 'r'); // @ 抑制警告,自行檢查回傳值
if ($handle) {
echo "<h3>HTTP 回應標頭:</h3><pre>";
foreach ($http_response_header as $header) {
echo htmlspecialchars($header) . "\n";
}
echo "</pre>";
fclose($handle);
} else {
echo "無法開啟連線:{$url}";
}
| 標頭 | 用途 |
|---|---|
HTTP/1.1 200 OK | 狀態碼,判斷資源是否存在、重導向、錯誤 |
Server: nginx/1.24.0 | 伺服器軟體與版本 |
Content-Type: text/html; charset=utf-8 | MIME 類型與編碼 |
Content-Length: 1256 | 回應內容長度(位元組) |
Last-Modified: Wed, 15 May 2024 10:30:00 GMT | 資源最後修改時間,可用於快取驗證 |
ETag: "abc123" | 實體標籤,條件請求依據 |
Set-Cookie: session=abc; HttpOnly; Secure | Cookie 設定,含安全屬性 |
X-Powered-By: PHP/8.2.10 | 後端技術棧洩露(建議隱藏) |
Content-Security-Policy: ... | CSP 政策 |
<?php
function remoteFileExists(string $url): bool
{
$handle = @fopen($url, 'r');
if (!$handle) return false;
// 僅讀取標頭,關閉連線
fclose($handle);
// 解析狀態行
$statusLine = $http_response_header[0] ?? '';
return (bool)preg_match('/^HTTP\/\d\.\d\s+2\d\d/', $statusLine);
}
var_dump(remoteFileExists('https://www.php.net/images/logos/php-logo.svg')); // true
var_dump(remoteFileExists('https://www.php.net/not-exist.xyz')); // false
<?php
function getRemoteFileSize(string $url): ?int
{
$handle = @fopen($url, 'r');
if (!$handle) return null;
fclose($handle);
foreach ($http_response_header as $header) {
if (stripos($header, 'Content-Length:') === 0) {
return (int)trim(substr($header, strlen('Content-Length:')));
}
}
return null; // 可能為分塊傳輸編碼
}
<?php
function detectServerStack(string $url): array
{
$info = ['server' => 'Unknown', 'powered_by' => 'Unknown', 'cms' => 'Unknown'];
@fopen($url, 'r');
foreach ($http_response_header as $h) {
if (stripos($h, 'Server:') === 0) {
$info['server'] = trim(substr($h, 7));
} elseif (stripos($h, 'X-Powered-By:') === 0) {
$info['powered_by'] = trim(substr($h, 13));
} elseif (stripos($h, 'X-Generator:') === 0) {
$info['cms'] = trim(substr($h, 12));
}
}
return $info;
}
<?php
// cURL 完整控制版
function fetchHeadersCurl(string $url): array
{
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_NOBODY => true, // HEAD 請求
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 5,
CURLOPT_TIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_USERAGENT => 'MyBot/1.0 (+https://mysite.com/bot)',
]);
curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
return $info;
}
`$http_response_header` 是 PHP 隱藏的小寶藏,適合快速檢測、簡單監控、教學示範。生產環境需要完整 HTTP 客戶端功能(認證、重試、並發、異步)時,請改用 **Guzzle** 或 **Symfony HttpClient**,擁有更豐富的功能與更好的錯誤處理。