copy() 支援 URL 來源 (需 allow_url_fopen=On),可直接將遠端檔案複製到本地路徑。
基本範例
<?php
$source = 'https://someserver.com/somefile.zip';
$dest = './somefile.zip';
if (!@copy($source, $dest)) {
$err = error_get_last();
echo "複製失敗: {$err['message']}";
} else {
echo "遠端檔案下載成功!";
}
?>
適用場景與限制
| 優點 | 缺點 |
| 程式碼極簡單 | 無進度條、斷點續傳 |
| 支援 HTTP/HTTPS/FTP | 大檔案易逾時 (受 max_execution_time) |
| 自動處理重導向 | 無法自訂 Header (User-Agent, Referer 等) |
| 記憶體效率尚可 (串流) | SSL 驗證失敗會失敗 (需 stream context) |
進階:stream context 自訂選項
$ctx = stream_context_create([
'http' => [
'timeout' => 60,
'user_agent' => 'MyApp/1.0',
'header' => "Referer: https://example.com\r\n",
'follow_location' => 1,
'max_redirects' => 5,
'verify_peer' => true,
'verify_peer_name' => true,
],
'ssl' => [
'cafile' => '/etc/ssl/certs/ca-certificates.crt',
]
]);
copy($source, $dest, $ctx);
現代替代:cURL / Guzzle
- cURL:功能完整、效能佳、支援並發、斷點續傳
- Guzzle:PHP HTTP Client 套件、Promise/異步、Middleware、PSR-7/18 相容
簡單下載用 copy(),複雜需求改用 cURL 或 Guzzle。
- 上一篇文章: PHP 登入驗證類 (Auth) 完整實作
- 下一篇文章: PHP 使用 stream_copy_to_stream() 串流複製檔案
Copyright ©
程式碼之家 All Rights Reserved