**絕對禁止** 對大檔案使用 file_get_contents()、file()、fread($fp, filesize($file)) 等一次性載入整個檔案到記憶體。PHP 記憶體限制 (memory_limit) 通常為 128M-512M,讀取 GB 級日誌會直接 OOM (Out of Memory) 導致進程崩潰。
<?php
function readLargeFileLineByLine($filepath, callable $callback)
{
if (!is_readable($filepath)) {
throw new InvalidArgumentException("檔案不可讀: $filepath");
}
$handle = fopen($filepath, 'r');
if (!$handle) {
throw new RuntimeException("無法開啟檔案: $filepath");
}
try {
$lineNumber = 0;
while (($line = fgets($handle)) !== false) {
$lineNumber++;
$callback($line, $lineNumber); // 處理每一行
}
} finally {
fclose($handle);
}
}
// 使用範例:統計錯誤日誌行數
$errorCount = 0;
readLargeFileLineByLine('/var/log/nginx/error.log', function($line, $num) use (&$errorCount) {
if (strpos($line, 'ERROR') !== false) {
$errorCount++;
}
});
echo "錯誤行數: $errorCount";
<?php
/**
* 高效讀取檔案最後 N 行 (不讀取整個檔案)
* 原理:從檔案末尾向前搜尋換行符
*/
function fileTail($filepath, int $lines = 10, int $bufferSize = 4096): array
{
if (!is_file($filepath) || !is_readable($filepath)) {
return [];
}
$handle = fopen($filepath, 'rb');
$fileSize = fstat($handle)['size'];
if ($fileSize === 0) {
fclose($handle);
return [];
}
$output = [];
$position = $fileSize;
$newlineCount = 0;
$buffer = '';
while ($position > 0 && $newlineCount < $lines) {
// 計算下一個讀取位置
$readSize = min($bufferSize, $position);
$position -= $readSize;
fseek($handle, $position);
$chunk = fread($handle, $readSize);
$buffer = $chunk . $buffer;
// 計算完整行數
$newlineCount = substr_count($buffer, "\n");
}
fclose($handle);
// 分割並取最後 N 行
$allLines = explode("\n", rtrim($buffer, "\n"));
return array_slice($allLines, -$lines);
}
// 使用
$last100 = fileTail('/var/log/access.log', 100);
foreach ($last100 as $line) {
echo $line . "\n";
}
<?php
function readInChunks($filepath, int $chunkSize = 8192, callable $callback)
{
$handle = fopen($filepath, 'rb');
if (!$handle) return;
try {
while (!feof($handle)) {
$chunk = fread($handle, $chunkSize);
if ($chunk === '') break;
$callback($chunk);
}
} finally {
fclose($handle);
}
}
// 使用:計算大檔案 MD5 (不載入記憶體)
$hash = hash_init('md5');
readInChunks('large_backup.tar.gz', 8192, function($chunk) use ($hash) {
hash_update($hash, $chunk);
});
echo "MD5: " . hash_final($hash);
<?php
function processLargeCsv($filepath, callable $rowHandler, $delimiter = ',', $enclosure = '"')
{
$handle = fopen($filepath, 'r');
if (!$handle) return;
$header = null;
$rowNum = 0;
try {
while (($row = fgetcsv($handle, 0, $delimiter, $enclosure)) !== false) {
$rowNum++;
if ($header === null) {
$header = $row; // 第一行作為標題
continue;
}
// 組合關聯陣列
$record = array_combine($header, $row);
$rowHandler($record, $rowNum);
}
} finally {
fclose($handle);
}
}
// 使用:匯入百萬筆會員資料
processLargeCsv('members.csv', function($record, $rowNum) {
// 批次寫入資料庫 (每 1000 筆 commit 一次)
static $batch = [];
$batch[] = $record;
if (count($batch) >= 1000) {
insertBatch('members', $batch);
$batch = [];
}
});
<?php
$file = new SplFileObject('large.log', 'r');
// 可設定旗標
$file->setFlags(
SplFileObject::READ_AHEAD | // 預讀
SplFileObject::SKIP_EMPTY // 跳過空行
);
foreach ($file as $lineNum => $line) {
// $line 已自動去除換行符
if (strpos($line, 'CRITICAL') !== false) {
echo "Line $lineNum: $line\n";
}
}
// 直接跳到特定行 (需先 seek)
$file->seek(1000);
echo $file->current(); // 第 1001 行
| 方法 | 記憶體 | 速度 | 適用場景 | 支援 Seek |
|---|---|---|---|---|
| fgets() 迴圈 | O(1) 常數 | 快 | 一般文本逐行處理 | 否 (單向) |
| fseek + fread (tail) | O(1) | 極快 (僅讀尾部) | 日誌尾部查看、即時監控 | 是 |
| fread 固定分塊 | O(1) | 快 | 二進位、哈希、加密、串流傳輸 | 是 |
| fgetcsv() | O(1) | 中 | CSV/TSV 結構化資料 | 否 |
| SplFileObject | O(1) | 中 | 物件導向、需隨機存取行號 | 是 (seek) |
| Generator 封裝 | O(1) | 快 | 現代 PHP 風格、可組合管線 | 否 |
<?php
function readLines(string $filepath): Generator
{
$handle = fopen($filepath, 'r');
if (!$handle) return;
try {
while (($line = fgets($handle)) !== false) {
yield rtrim($line, "\r\n");
}
} finally {
fclose($handle);
}
}
// 使用:極其優雅的管線操作
$errors = readLines('/var/log/app.log')
| array_filter(fn($line) => strpos($line, 'ERROR') !== false)
| array_map(fn($line) => "[ERROR] $line")
// 實際需自行實作管線或用迴圈
;
foreach (readLines('/var/log/app.log') as $line) {
if (strpos($line, 'ERROR') !== false) {
echo $line . "\n";
}
}
| 錯誤 | 後果 | 正確做法 |
|---|---|---|
| file_get_contents 大檔案 | OOM 崩潰 | 改用 fgets/fread 串流 |
| file() 讀取大檔 | 載入全檔到陣列,OOM | 逐行處理 |
| fopen 後未 fclose | 檔案句柄洩漏,系統上限 | try-finally 或 SplFileObject 自動關閉 |
| fgets 未指定長度參數 | PHP 8.1+ 棄用預設值 | fgets($fp, 0) 或不傳第二參數 (0 代表無限制) |
| 二進位檔用 'r' 模式 | Windows 下換行符轉換損壞資料 | 二進位檔必須用 'rb' |
| 忽略編碼問題 | 中文截斷亂碼 | 確認檔案編碼,必要時 mb_convert_encoding |
<?php
// composer require react/filesystem
use React\Filesystem\Filesystem;
use React\EventLoop\Factory;
$loop = Factory::create();
$filesystem = Filesystem::create($loop);
$file = $filesystem->file('large.log');
$stream = $file->createReadStream();
$stream->on('data', function($chunk) {
// 非阻塞處理 chunk
processChunk($chunk);
});
$stream->on('end', function() {
echo "讀取完成\n";
$loop->stop();
});
$loop->run();
PHP 處理大檔案的核心是**串流處理**。掌握 fopen/fgets/fread/fseek 等底層函數,配合 try-finally 確保資源釋放,即可安全高效處理任意大小檔案。現代 PHP 建議使用 Generator 或 SplFileObject 封裝,提升程式碼可讀性與可組合性。