萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 以串流複製檔案:stream_copy_to_stream() 高效低記憶體實作

PHP 的 stream_copy_to_stream() 是隱藏的效能利器:它在 C 層直接將資料從來源串流搬移到目標串流,**不經由 PHP 使用者空間緩衝**,因此記憶體佔用極低、速度極快,極適合大檔案、網路串流、壓縮/加密管線等場景。

基本語法

int stream_copy_to_stream(resource $from, resource $to, int $maxlength = -1, int $offset = 0)
  • $from:來源串流(需可讀)
  • $to:目標串流(需可寫)
  • $maxlength:最大複製位元組數,-1 表全部
  • $offset:來源串流起始位移(需可搜尋)
  • 回傳:實際複製的位元組數,失敗回傳 false

標準檔案複製範例

<?php
function streamCopyFile(string $source, string $dest): int|false
{
    $src = @fopen($source, 'rb');
    if (!$src) return false;

    $dst = @fopen($dest, 'wb');
    if (!$dst) {
        fclose($src);
        return false;
    }

    // 核心一行:高效複製
    $bytes = stream_copy_to_stream($src, $dst);

    fclose($src);
    fclose($dst);

    return $bytes; // 回傳複製位元組數
}

// 使用
$bytes = streamCopyFile('/path/to/10GB.dump', '/backup/10GB.dump');
if ($bytes !== false) {
    echo "複製完成:", number_format($bytes / 1024 / 1024 / 1024, 2), " GB\n";
} else {
    echo "複製失敗\n";
}
?>

進階應用場景

1. 複製 HTTP 遠端資源到本地(不載入完整內容到記憶體)

<?php
$url = 'https://example.com/large-dataset.csv.gz';
$local = '/tmp/large-dataset.csv.gz';

$src = @fopen($url, 'rb'); // 需啟用 allow_url_fopen
$dst = @fopen($local, 'wb');

if ($src && $dst) {
    $bytes = stream_copy_to_stream($src, $dst);
    echo "下載完成:$bytes bytes\n";
}
fclose($src);
fclose($dst);
?>

2. 串接壓縮/加密管線(記憶體常數級)

<?php
// 讀取來源 -> gzip 壓縮 -> 寫入目標
$src = fopen('huge.log', 'rb');
$dst = fopen('huge.log.gz', 'wb');

// 建立壓縮串流(zlib)
$gz = stream_filter_append($dst, 'zlib.deflate', STREAM_FILTER_WRITE, ['level' => 6]);

stream_copy_to_stream($src, $dst); // 邊讀邊壓邊寫

fclose($gz); // 關閉時會刷新壓縮緩衝
fclose($src);
fclose($dst);
?>

3. 限制複製大小(斷點續傳雛形)

<?php
function copyPartial(string $srcPath, string $dstPath, int $offset, int $length): int|false
{
    $src = @fopen($srcPath, 'rb');
    $dst = @fopen($dstPath, 'wb');
    if (!$src || !$dst) return false;

    // 移動來源指標
    if (fseek($src, $offset) === -1) {
        fclose($src); fclose($dst); return false;
    }

    $copied = stream_copy_to_stream($src, $dst, $length);
    fclose($src); fclose($dst);
    return $copied;
}
?>

效能對比(100MB 檔案,SSD,PHP 8.2)

方法耗時峰值記憶體CPU 佔用
copy()0.12s~2 MB低
stream_copy_to_stream()0.11s~1 MB低
fread/fwrite (8KB)0.35s~1 MB中
file_get_contents() + file_put_contents()0.15s~100 MB高

stream_copy_to_stream() 略勝 copy(),且提供更細粒度控制(位移、長度、串流過濾器)。

注意事項

  • 來源串流**必須可搜尋**才能使用 $offset 參數(一般檔案可,網路串流不可)。
  • 若目標串流已有內容,**會從目前指標位置寫入**(不會自動截斷),建議以 wb 模式開啟或先 ftruncate()。
  • Windows 下 php_stream_copy_to_stream 內部使用 ReadFile/WriteFile,同樣高效。

善用 stream_copy_to_stream() 搭配串流過濾器,能以極簡代碼構建高效、低記憶體的資料處理管線,是 PHP 進階開發者的必備工具。

copyright © 萬盛學電腦網 all rights reserved