fpassthru()
函數在 PHP 中用于將數據從文件直接傳輸到輸出流,而無需在內存中存儲整個文件。這在處理大文件時非常有用,因為它可以顯著降低內存使用量。
以下是使用 fpassthru()
函數處理大文件流的方法:
$inputFile = fopen('large_file.txt', 'rb');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="output.txt"');
fpassthru()
函數將文件指針從輸入流直接傳輸到輸出流。這將逐塊讀取文件并將其發送到瀏覽器,而無需將整個文件加載到內存中。while (!feof($inputFile)) {
fpassthru($inputFile);
}
fclose($inputFile);
這是一個完整的示例,用于將大文件流式傳輸到瀏覽器:
<?php
$inputFile = fopen('large_file.txt', 'rb');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="output.txt"');
while (!feof($inputFile)) {
fpassthru($inputFile);
}
fclose($inputFile);
?>
請注意,fpassthru()
函數不會顯示任何進度信息。如果你需要跟蹤大文件的傳輸進度,可以考慮使用其他方法,例如分塊傳輸或計算已傳輸的字節數。