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

PHP 使用 stream_copy_to_stream() 串流複製檔案

     編輯:PHP 綜合知識

stream_copy_to_stream() 高效複製串流資料,不將整個檔案載入記憶體,適合大檔案複製。

函數封裝

function streamCopy($src, $dest): int|false {
    $fsrc = fopen($src, 'rb');
    $fdest = fopen($dest, 'wb');
    if (!$fsrc || !$fdest) return false;
    $bytes = stream_copy_to_stream($fsrc, $fdest);
    fclose($fsrc);
    fclose($fdest);
    return $bytes;
}

優勢

  • 內核層級複製 (零拷貝可能),速度極快
  • 記憶體佔用極低 (固定緩衝區)
  • 支援所有串流封裝協定 (HTTP, FTP, compress.zlib, php://memory 等)

進階:加入進度回呼

function streamCopyProgress($src, $dest, callable $progress = null): int {
    $fsrc = fopen($src, 'rb');
    $fdest = fopen($dest, 'wb');
    $total = fstat($fsrc)['size'] ?? 0;
    $copied = 0;
    $bufferSize = 8192;
    
    while (!feof($fsrc)) {
        $buffer = fread($fsrc, $bufferSize);
        fwrite($fdest, $buffer);
        $copied += strlen($buffer);
        if ($progress) $progress($copied, $total);
    }
    fclose($fsrc);
    fclose($fdest);
    return $copied;
}

適用場景

  • 大檔案備份、遷移
  • 上傳檔案移動到永久儲存
  • 壓縮/解壓串流處理

掌握串流複製,大檔案操作不再記憶體爆滿。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved