從遠端 HTTP/HTTPS/FTP 伺服器下載檔案到本地,是爬蟲、同步、備份常見需求。PHP 提供 copy()、file_get_contents()、fopen()+stream_copy_to_stream()、cURL 等多種方式,各有優劣。本文實測比較並給出選型建議。
copy() —— 最簡潔但功能受限<?php
$remote = 'https://cdn.example.com/assets/app.v2.3.1.zip';
$local = '/var/www/storage/app.v2.3.1.zip';
// 需 php.ini: allow_url_fopen = On
if (@copy($remote, $local)) {
echo "下載成功:", filesize($local), " bytes\n";
} else {
$err = error_get_last();
echo "失敗:", $err['message'] ?? 'Unknown', "\n";
}
?>
優點:一行搞定、語義清晰。
缺點:無法設定 Timeout、User-Agent、Header、Cookie、Proxy、SSL 驗證、斷點續傳;錯誤資訊有限;大檔案易卡住無回應。
fopen() + stream_copy_to_stream() —— 串流式、可控制緩衝<?php
function downloadStream(string $url, string $dest, array $ctxOpts = []): int|false
{
$defaultCtx = [
'http' => [
'method' => 'GET',
'timeout' => 30, // 秒
'user_agent' => 'MyApp/1.0 (+https://example.com)',
'follow_location' => 1,
'max_redirects' => 5,
'ignore_errors' => true, // 讓我們自己檢查狀態碼
],
'ssl' => [
'verify_peer' => true,
'verify_peer_name' => true,
],
];
$context = stream_context_create(array_merge_recursive($defaultCtx, $ctxOpts));
$src = @fopen($url, 'rb', false, $context);
if (!$src) return false;
// 檢查 HTTP 狀態碼
$meta = stream_get_meta_data($src);
if (isset($meta['wrapper_data'])) {
foreach ($meta['wrapper_data'] as $header) {
if (stripos($header, 'HTTP/') === 0) {
$code = (int)explode(' ', $header)[1];
if ($code < 200 || $code >= 300) {
fclose($src);
trigger_error("HTTP $code: $header", E_USER_WARNING);
return false;
}
}
}
}
$dst = @fopen($dest, 'wb');
if (!$dst) { fclose($src); return false; }
$bytes = stream_copy_to_stream($src, $dst);
fclose($src);
fclose($dst);
return $bytes;
}
?>
<?php
function downloadCurl(string $url, string $dest, array $options = []): bool
{
$fp = @fopen($dest, 'wb');
if (!$fp) return false;
$ch = curl_init($url);
curl_setopt_array($ch, array_merge([
CURLOPT_FILE => $fp, // 直接寫入檔案控制代碼
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 5,
CURLOPT_TIMEOUT => 30, // 總超時
CURLOPT_CONNECTTIMEOUT => 10, // 連線超時
CURLOPT_USERAGENT => 'MyApp/1.0',
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_FAILONERROR => true, // 非 2xx 視為失敗
CURLOPT_NOPROGRESS => false, // 可啟用進度回呼
CURLOPT_PROGRESSFUNCTION => function ($ch, $dltotal, $dlnow) {
if ($dltotal > 0) {
printf("\r進度:%.1f%% (%s/%s MB)", $dlnow/$dltotal*100,
number_format($dlnow/1024/1024, 1),
number_format($dltotal/1024/1024, 1));
}
},
], $options));
$ok = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
$info = curl_getinfo($ch);
curl_close($ch);
fclose($fp);
if (!$ok) {
@unlink($dest); // 失敗刪除不完整檔案
trigger_error("cURL [$errno] $error (HTTP {$info['http_code']})", E_USER_WARNING);
return false;
}
return true;
}
// 使用:支援斷點續傳(Range 標頭)
downloadCurl(
'https://speed.hetzner.de/100MB.bin',
'/tmp/100MB.bin',
[CURLOPT_RESUME_FROM_LARGE => filesize('/tmp/100MB.bin')] // 續傳
);
?>
| 方法 | 耗時 | 峰值記憶體 | 支援斷點續傳 | 自訂 Header/Cookie/Proxy | 錯誤診斷 |
|---|---|---|---|---|---|
copy() | 42s | ~2 MB | ❌ | ❌ | 差 |
fopen+stream_copy | 38s | ~1 MB | ⚠️ 需手動 | ✅ (context) | 中 |
| cURL | 35s | ~1 MB | ✅ 內建 | ✅ 完整 | 優 |
copy()fopen + stream_copy_to_streamCURLOPT_SSL_VERIFYPEER => true),否則遭受中間人攻擊。CURLOPT_MAXFILESIZE),防止惡意佔滿磁碟。遠端檔案複製看似簡單,生產環境卻暗藏變數。掌握三大方案優劣,依場景選型,才能打造穩健、安全的下載功能。