php实现tail
PHP 实现类似 tail 命令的功能
在 PHP 中实现类似 Unix tail 命令的功能,可以读取文件的最后几行内容。以下是几种实现方法:
使用 file() 函数读取文件末尾行
function tail($filepath, $lines = 10) {
$file = file($filepath);
return implode("", array_slice($file, -$lines));
}
这种方法简单但会加载整个文件到内存,不适合大文件。
高效处理大文件的方法
function tail($filepath, $lines = 10) {
$handle = fopen($filepath, "r");
$cursor = -1;
$linecounter = $lines;
$output = '';
fseek($handle, $cursor, SEEK_END);
$char = fgetc($handle);
while ($linecounter > 0) {
if ($char == "\n") $linecounter--;
$output .= $char;
fseek($handle, --$cursor, SEEK_END);
$char = fgetc($handle);
}
fclose($handle);
return strrev($output);
}
使用 SplFileObject 实现
function tail($filepath, $lines = 10) {
$file = new SplFileObject($filepath);
$file->seek(PHP_INT_MAX);
$lastLine = $file->key();
$file->seek(max(0, $lastLine - $lines));
$output = '';
while (!$file->eof()) {
$output .= $file->current();
$file->next();
}
return $output;
}
持续监控文件变化(类似 tail -f)
function tailFollow($filepath, $callback) {
$size = filesize($filepath);
while (true) {
clearstatcache();
$currentSize = filesize($filepath);
if ($currentSize > $size) {
$fh = fopen($filepath, "r");
fseek($fh, $size);
while (!feof($fh)) {
$line = fgets($fh);
$callback($line);
}
fclose($fh);
$size = $currentSize;
}
sleep(1);
}
}
性能优化建议
对于非常大的文件,建议使用第二种方法,因为它不会将整个文件加载到内存中。如果只需要查看日志文件的最后几行,这种方法最为高效。
注意文件权限问题,确保 PHP 有权限读取目标文件。在生产环境中使用时,应考虑添加适当的错误处理机制。







