專案需求:預覽遠端圖片前先確認檔案是否存在。本文比較 cURL HEAD、file_get_contents、fsockopen、fopen 等方法在 Windows/Linux 下的表現差異,並給出推薦做法。
<?php
function file_exists_curl($url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true); // 不下載內容
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$found = false;
if ($result !== false) {
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$found = ($status >= 200 && $status < 400); // 2xx, 3xx 視為存在
}
curl_close($ch);
return $found;
}
?>
<?php
function file_exists_fgc($url) {
return @file_get_contents($url, 0, null, 0, 1) !== false;
}
?>
<?php
function file_exists_fsock($url) {
$info = parse_url($url);
$host = $info['host'];
$path = $info['path'] ?? '/';
$fp = @fsockopen($host, 80, $errno, $errstr, 10);
if (!$fp) return false;
fputs($fp, "HEAD {$path} HTTP/1.1\r\nHost: {$host}\r\nConnection: Close\r\n\r\n");
$headers = '';
while (!feof($fp)) {
$line = fgets($fp);
$headers .= $line;
if ($line === "\r\n") break;
}
fclose($fp);
return (bool)preg_match('/^HTTP\/\d\.\d\s+2\d\d/', $headers);
}
?>
<?php
function file_exists_fopen($url) {
return @fopen($url, 'r') !== false;
}
?>
<?php
function file_exists_curl_full($url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
$content = curl_exec($ch);
curl_close($ch);
return !preg_match('/404/', $content);
}
?>
| 方法 | Windows | Linux | 備註 |
|---|---|---|---|
| cURL HEAD | ✅ 準確 | ✅ 準確 | 推薦,效能佳、可攜帶 Cookie/Header |
| file_get_contents | ✅ 可行 | ❌ 全回 true | Linux 下 stream wrapper 行為不同 |
| fsockopen | ✅ 可行 | ✅ 可行 | 無需 cURL 擴充,但需自行組裝請求 |
| fopen | ⚠️ 視設定 | ⚠️ 視設定 | 受 allow_url_fopen 影響 |
| cURL 全內容 | ✅ 可行 | ✅ 可行 | 浪費頻寬,不建議 |
最佳實踐:優先使用 cURL HEAD,若環境無 cURL 則退而使用 fsockopen。避免使用 get_headers()(效率較差且易受阻塞)。