核心代碼(5 行搞定)
<?php
set_time_limit(0); // 移除執行時間限制
$imageUrls = [
'https://example.com/img1.jpg',
'https://example.com/img2.png',
// ... 百個 URL
];
// 去重
$imageUrls = array_unique($imageUrls);
foreach ($imageUrls as $url) {
$filename = basename(parse_url($url, PHP_URL_PATH));
$savePath = __DIR__ . '/downloads/' . $filename;
// 串流複製:低記憶體、支援大檔
$src = @fopen($url, 'rb');
if (!$src) { echo "❌ 無法開啟: $url\n"; continue; }
$dst = fopen($savePath, 'wb');
stream_copy_to_stream($src, $dst);
fclose($src);
fclose($dst);
echo "✅ 已儲存: $filename (" . filesize($savePath) . " bytes)\n";
}
進階版:cURL 多執行緒並行下載(大幅提速)
function multiDownload(array $urls, string $dir, int $concurrency = 10): array {
if (!is_dir($dir)) mkdir($dir, 0755, true);
$mh = curl_multi_init();
$handles = [];
$results = [];
// 初始化 handles
foreach ($urls as $i => $url) {
$filename = basename(parse_url($url, PHP_URL_PATH));
$fp = fopen($dir . '/' . $filename, 'wb');
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_FILE => $fp,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 5,
CURLOPT_TIMEOUT => 60,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_USERAGENT => 'PHP MultiDownloader/1.0',
]);
curl_multi_add_handle($mh, $ch);
$handles[$i] = ['ch' => $ch, 'fp' => $fp, 'url' => $url, 'filename' => $filename];
}
// 並行執行
$running = null;
do {
curl_multi_exec($mh, $running);
curl_multi_select($mh, 0.1); // 等待活動
} while ($running > 0);
// 收集結果
foreach ($handles as $i => $h) {
$errno = curl_errno($h['ch']);
$httpCode = curl_getinfo($h['ch'], CURLINFO_HTTP_CODE);
fclose($h['fp']);
if ($errno === 0 && $httpCode === 200) {
$results[$h['filename']] = 'success';
} else {
$results[$h['filename']] = "failed: cURL $errno, HTTP $httpCode";
@unlink($dir . '/' . $h['filename']);
}
curl_multi_remove_handle($mh, $h['ch']);
curl_close($h['ch']);
}
curl_multi_close($mh);
return $results;
}
// 使用
$results = multiDownload($imageUrls, __DIR__ . '/downloads', 20);
print_r($results);
關鍵優化點
- 串流而非載入記憶體:
stream_copy_to_stream() / CURLOPT_FILE 直接寫磁碟,避免大圖 OOM。
- 並行下載:
curl_multi 同時開啟多連線,受限於頻寬而非延遲,速度提升 5-10 倍。
- 去重與斷點續傳:
array_unique() + 檢查檔案是否存在/大小是否匹配 Content-Length。
- 錯誤重試:針對 5xx、網路錯誤指數退避重試(建議用 Guzzle/HTTP Client 內建重試)。
- User-Agent & Referer:模擬瀏覽器繞過防盜鏈。
法律與道德提醒
- 遵守
robots.txt 與網站服務條款。
- 僅下載公開授權(CC0、Unsplash 等)或已獲授權圖片。
- 高頻請求加入
sleep() 限流,避免觸發 WAF 封禁。