For Programmers: Free Programming Magazines  


Home > Archive > PHP Language > December 2006 > read "tail -f file"









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author read "tail -f file"
_mario.lat

2006-12-11, 7:01 pm

hallo,
In a file are added logs from routers.
I'd like to read these log.
I think about reading data from command "tail -f file" but how can I do
that?
Thank you in advance,
Mario.
petersprc

2006-12-11, 7:01 pm

Hi,

You can display a running tail of a log file with this function:

<?

//
// tailFile
//
// Monitor a file and print new data to the browser as it
// becomes available.
//

function tailFile($path)
{
echo <<<end
<script type="text/javascript">
function scrollDown()
{
sh = document.body.scrollHeight
ch = document.body.clientHeight
if (sh > ch){
window.scrollTo(0, sh - ch)
}
}
</script>
<pre>
end;

$tail = popen('tail -50f ' . escapeshellarg($path) . ' 2>&1', 'r');
if (!$tail) {
trigger_error('tail failed.', E_USER_ERROR);
} elseif (stream_set_blocking($tail, 0) === false) {
trigger_error('stream_set_blocking', E_USER_ERROR);
} else {
$buf = '';
$bytes = 0;
$updateTime = 0;

for (;;) {
if (stream_select($r = array($tail), $w = null, $x = null, 9, 0)
=== false) {
trigger_error('stream_select', E_USER_ERROR);
break;
}

$buf .= fread($tail, 8192);
$len = strlen($buf);
$part = false;

if (($nl = strrpos($buf, "\n")) !== false) {
$part = substr($buf, 0, $nl + 1);
$buf = substr($buf, $nl + 1);
} elseif ($len > 65536 || time() - $updateTime > 5) {
$part = $buf;
$buf = '';
}

if ($part !== false) {
$updateTime = time();
$part = htmlentities($part, ENT_QUOTES);
$bytes += strlen($part);
echo '<script type="text/javascript">scrollDown()</script>';
echo $part;
echo '<script type="text/javascript">scrollDown()</script>';
if ($bytes > 262144) {
echo '<script type="text/javascript">window.location = '' .
htmlentities($_SERVER['PHP_SELF'], ENT_QUOTES) .
''</script>';
}
flush();
}

sleep(1);
}

pclose($tail) or trigger_error('pclose', E_USER_ERROR);
}

echo '</pre>';
}

tailFile('/tmp/mylog');

?>

To just run tail once, you can use:

<?

exec('tail -20 /my/file 2>&1', $lines, $exitCode);
if ($exitCode != 0) {
trigger_error('tail failed.', E_USER_ERROR);
} else {
echo '<pre>' . htmlentities(join("\n", $lines), ENT_QUOTES) .
'</pre>';
}

?>

_mario.lat wrote:
> hallo,
> In a file are added logs from routers.
> I'd like to read these log.
> I think about reading data from command "tail -f file" but how can I do
> that?
> Thank you in advance,
> Mario.


Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com