<?
/**
* 读取文本倒数$n行
*
* @param string $filename
* @param int $n $n不能大于10
* @return array
*/
header("Content-type: text/html;charset=gb2312");
$filename = "log/log.txt";
$fileData = tail($filename,100);
for($i=0;$i<count($fileData);$i++)
{
echo $fileData[$i]."<br>";
}
function tail($filename,$n)
{
$fp = fopen($filename, 'rb');
$n = (int)$n;
if($n>10) trigger_error("取文件倒数N行的时候,不能大于10行", E_USER_ERROR);
if ($fp) {
flock($fp, LOCK_SH);
$i = -2;//从第二个字符开始,因为最后一个是"\n"
fseek($fp,$i,SEEK_END);
$buffer = array();
while ($n>=0) {
fseek($fp,$i--,SEEK_END);
if(fgetc($fp)=="\n") {
$buffer[] = fgets($fp,1024);
$n--;
}
}
flock($fp, LOCK_UN);
fclose($fp);
unset($tmp);
return $buffer;
} else {
return false;
}
}
?>
/**
* 读取文本倒数$n行
*
* @param string $filename
* @param int $n $n不能大于10
* @return array
*/
header("Content-type: text/html;charset=gb2312");
$filename = "log/log.txt";
$fileData = tail($filename,100);
for($i=0;$i<count($fileData);$i++)
{
echo $fileData[$i]."<br>";
}
function tail($filename,$n)
{
$fp = fopen($filename, 'rb');
$n = (int)$n;
if($n>10) trigger_error("取文件倒数N行的时候,不能大于10行", E_USER_ERROR);
if ($fp) {
flock($fp, LOCK_SH);
$i = -2;//从第二个字符开始,因为最后一个是"\n"
fseek($fp,$i,SEEK_END);
$buffer = array();
while ($n>=0) {
fseek($fp,$i--,SEEK_END);
if(fgetc($fp)=="\n") {
$buffer[] = fgets($fp,1024);
$n--;
}
}
flock($fp, LOCK_UN);
fclose($fp);
unset($tmp);
return $buffer;
} else {
return false;
}
}
?>
转载于:https://blog.51cto.com/strugglelinux/232465