800MB、500 萬行日志文件,需讀取最後 N 行。`file()` 全讀入記憶體會 OOM,`exec('tail')` 依賴外部命令。本文對比三種純 PHP 方案並給出實測耗時,推薦生產環境直接使用的最優解。
| 方案 | 原理 | 耗時 | 記憶體 | 推薦度 |
|---|---|---|---|---|
| 1. `file()` 全讀 | 一次性載入陣列 | 116 秒 | >800MB (OOM 風險) | ❌ 禁用 |
| 2. `exec('tail -n 10')` | 系統命令 | 0.003 秒 | 極低 | ⚠️ 依賴外部命令、權限、注入風險 |
| 3. `fseek` 單字節倒讀 | 從 EOF 逐字節找 `\n` | 0.009 秒 | 極低 | ✅ 可用 |
| 4. `fseek` 分塊緩衝 (4KB) | 倒讀塊、數 `\n` | 0.0009 秒 | 極低 | ✅✅ 推薦 |
| 5. 指數退避分塊 (5x) | 跳躍式增大讀取窗口 | 0.0003 秒 | 極低 | 🏆 最快 |
<?php
function tailFile(string $file, int $lines = 10, int $chunk = 4096): string
{
$fp = fopen($file, 'rb');
if (!$fp) throw new RuntimeException("Cannot open $file");
$size = (int)filesize($file);
$buffer = '';
$read = 0;
for ($offset = $chunk; $read < $size; $offset += $chunk) {
$seek = min($offset, $size);
fseek($fp, -$seek, SEEK_END);
$block = fread($fp, $seek);
$buffer = $block . $buffer;
$read += $seek;
if (substr_count($buffer, "\n") > $lines) {
// 取最後 $lines 行
if (preg_match("!(.*?\n){$lines}$!", $buffer, $m)) {
fclose($fp);
return $m[0];
}
}
}
fclose($fp);
return $buffer; // 檔案行數不足 $lines
}
?>
<?php
function tailFileFast(string $file, int $n = 10, int $base = 5): array
{
$fp = fopen($file, 'rb');
if (!$fp) throw new RuntimeException("Cannot open $file");
$pos = $n + 1;
$lines = [];
while (count($lines) <= $n) {
try {
fseek($fp, -$pos, SEEK_END);
} catch (Throwable) { // 到達檔案開頭
fseek($fp, 0);
break;
}
$pos *= $base; // 5, 25, 125, 625... 字節
while (!feof($fp)) {
array_unshift($lines, rtrim(fgets($fp), "\r\n"));
}
}
fclose($fp);
return array_slice($lines, 0, $n);
}
// 用法
$last10 = tailFileFast('/var/log/nginx/access.log', 10);
print_r($last10);
?>
<?php
class LogTailer
{
public function __construct(private string $file, private string $encoding = 'UTF-8') {}
public function lastLines(int $n = 50): array
{
return array_map(
fn($l) => mb_convert_encoding($l, 'UTF-8', $this->encoding),
tailFileFast($this->file, $n)
);
}
public function follow(callable $onLine, int $intervalMs = 500): void
{
$fp = fopen($this->file, 'rb');
fseek($fp, 0, SEEK_END);
while (true) {
$line = fgets($fp);
if ($line !== false) {
$onLine(mb_convert_encoding(rtrim($line), 'UTF-8', $this->encoding));
} else {
usleep($intervalMs * 1000);
}
}
}
}
?>
結論:**方案 5(指數退避)最快、代碼最簡、無正則依賴**,適合所有大檔案尾部讀取場景;需跨平臺、追蹤、編碼轉換時使用封裝類。