PHP 內建 copy() 雖方便,但在處理大型檔案、需自訂緩衝區、或欲在複製過程中進行資料轉換(如加密、壓縮)時,透過 檔案讀寫流(fopen/fread/fwrite) 手動實作更具彈性。本文示範核心邏輯並分析優缺點。
<?php
function copyFileManual(string $source, string $dest, int $bufferSize = 8192): bool
{
// 開啟來源檔(唯讀二進位)
$srcHandle = @fopen($source, 'rb');
if (!$srcHandle) {
return false;
}
// 開啟目標檔(寫入二進位,截斷現有內容)
$destHandle = @fopen($dest, 'wb');
if (!$destHandle) {
fclose($srcHandle);
return false;
}
// 分塊複製
while (!feof($srcHandle)) {
$chunk = fread($srcHandle, $bufferSize);
if ($chunk === false) {
fclose($srcHandle);
fclose($destHandle);
return false;
}
if (fwrite($destHandle, $chunk) === false) {
fclose($srcHandle);
fclose($destHandle);
return false;
}
}
fclose($srcHandle);
fclose($destHandle);
return true;
}
// 使用範例
$ok = copyFileManual('/path/to/large_video.mp4', '/backup/large_video.mp4');
var_dump($ok); // bool(true)
?>
rb/wb:Windows 下避免換行符轉換(\n ↔ \r\n),確保位元級完整複製。1024 * 1024)。chmod()、touch() 補齊。<?php
function copyAndEncrypt(string $source, string $dest, string $password): bool
{
$src = @fopen($source, 'rb');
$dst = @fopen($dest, 'wb');
if (!$src || !$dst) return false;
// 簡易 XOR 加密示範(實務請用 openssl_encrypt)
$key = hash('sha256', $password, true);
$keyLen = strlen($key);
$pos = 0;
while (!feof($src)) {
$chunk = fread($src, 8192);
$len = strlen($chunk);
for ($i = 0; $i < $len; $i++) {
$chunk[$i] = $chunk[$i] ^ $key[$pos % $keyLen];
$pos++;
}
fwrite($dst, $chunk);
}
fclose($src);
fclose($dst);
return true;
}
?>
| 方法 | 適用場景 | 記憶體佔用 | 靈活度 |
|---|---|---|---|
copy() | 一般小/中型檔案、單純複製 | 低(內核層優化) | 低 |
stream_copy_to_stream() | 串流間複製、需進度控制 | 低 | 中 |
手動 fread/fwrite | 大檔案、邊複製邊處理、自訂緩衝 | 可控(由緩衝區決定) | 高 |
結論:日常開發優先用 copy();大檔案、需中介處理、或學習檔案 I/O 底層運作時,手動串流讀寫是必備技能。