爬蟲、圖片熱鏈保護、資料備份等場景常需將遠端檔案下載至本地伺服器。本文介紹三種 PHP 實作方式,分析其優缺點與適用場景,並提供生產環境可用的完整封裝類。
function downloadSimple(string $url, string $savePath): bool {
$content = @file_get_contents($url);
if ($content === false) return false;
return file_put_contents($savePath, $content) !== false;
}
優點:程式碼極簡、記憶體效率尚可(流式讀寫)。
缺點:無法控制超時、重試、User-Agent、追蹤重導向;需開啟 allow_url_fopen。
function downloadCurl(string $url, string $savePath, array $options = []): bool {
$fp = fopen($savePath, '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_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; PHP Downloader)',
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
], $options));
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
fclose($fp);
if ($result === false || $httpCode >= 400) {
@unlink($savePath);
return false;
}
return true;
}
優點:完整控制 HTTP 行為、支援斷點續傳、並發下載、Proxy、憑證驗證。
缺點:程式碼較長、需安裝 php-curl 擴展。
function downloadStream(string $url, string $savePath, array $contextOptions = []): bool {
$defaultContext = [
'http' => [
'method' => 'GET',
'follow_location' => 1,
'max_redirects' => 5,
'timeout' => 30,
'user_agent' => 'PHP Stream Downloader',
'verify_peer' => true,
'verify_peer_name' => true,
],
'ssl' => ['verify_peer' => true, 'verify_peer_name' => true],
];
$context = stream_context_create(array_merge_recursive($defaultContext, $contextOptions));
return copy($url, $savePath, $context);
}
優點:純 PHP 核心功能、無額外依賴、支援 HTTPS 驗證。
缺點:錯誤處理較難、無進度回調、並發支援弱。
class FileDownloader {
private $url;
private $savePath;
private $chunkSize = 8192;
private $maxRetries = 3;
private $progressCallback;
public function __construct(string $url, string $savePath) {
$this->url = $url;
$this->savePath = $savePath;
}
public function setProgressCallback(callable $cb): self {
$this->progressCallback = $cb;
return $this;
}
public function download(): bool {
// 實作略:HEAD 取得 Content-Length、Range 請求、寫入臨時檔、驗證完整性、重命名
// 參考開源庫:php-http/client, guzzlehttp/guzzle
return true;
}
}
Content-Length 或下載中斷)Content-Type + 檔案簽名魔數)basename、realpath 驗證)tempnam(sys_get_temp_dir(), 'dl_'))簡單需求用 file_get_contents 或 Stream Context;生產環境強烈建議使用 cURL 或成熟 HTTP Client(Guzzle、Symfony HttpClient),獲得完整的錯誤處理、重試、並發與監控能力。