Question

I need help with:

Read a file /var/log/syslog into a HTML page, limit to last 20 lines and next/prev button

Was it helpful?

Solution

Try this code

<?php
$lines = file($_SERVER['DOCUMENT_ROOT'] . '/inc/data.txt'); # This is your text file.
$line_amount = count($lines);
#echo '<pre>'; print_r($lines); echo '</pre>';

$perpage = 20;

$p = isset($_GET['p']) ? $_GET['p'] : 1;
for ($i = (($p * $perpage) - $perpage); $i <= (($perpage * $p) - 1); $i++){
    if($i >= $line_amount){
        break;
    }
    else{
        if($lines[$i] != ''){
            echo ''.$lines[$i].'<br />'; # This is the output loop.
        }
    }
}

//$p = $p + $perpage;

?>            
<table summary="" cellpadding="10" cellspacing="0"  border="0" class="global-links-menu">
        <tr>
<?php

$total_pages = $line_amount/$perpage;
if($line_amount % $perpage != 0){
    $total_pages = $total_pages + 1;
}


if($p!=1)
{
  $back_page=$p-1;
    echo "<td ><a href='?p=$back_page'>Back</a></td>";
}
else
{
    $back_page=$p-1;
    echo "<td >Back</td>";
}

for($j=1;$j<=$total_pages;$j++)
{

    if($j==$p)
    {        
        echo "<td >$p</td>";
    }
    else
    {
        echo "<td ><a href='?p=$j'>$j</a></td>";    
    }
}

if($p <= $total_pages - 1){
    $next_page=$p+1;
    echo "<td ><a href='?p=$next_page'>Next</a></td>";    
}
else
{
    echo "<td >Next</td>";
}
?>
    </tr></table>

OTHER TIPS

Your best option is to spawn a sudoed tail: PHP process can't usually read the syslog file.

Configure properly the sudoers file using visudo or the tool of your choice, and then:

$output = shell_exec('/path/to/sudo /path/to/tail -n 20 /var/log/syslog | head -n 10');

The next/prev button may be used to configure the numbers above. Here, I'm reading the last 20 lines of syslog, and outputting the first 10 of them. Not unlike MySQL's LIMIT option, in a way.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top