首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 使用 copy() 遠端檔案下載到本地

     編輯:PHP 綜合知識

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 "遠端檔案下載成功!";
}
?>

適用場景與限制

進階: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。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
優點缺點
程式碼極簡單無進度條、斷點續傳
支援 HTTP/HTTPS/FTP大檔案易逾時 (受 max_execution_time)
自動處理重導向無法自訂 Header (User-Agent, Referer 等)
記憶體效率尚可 (串流)SSL 驗證失敗會失敗 (需 stream context)