Skip to content
PHP Logo

What are some common challenges when formatting and displaying log-file contents in PHP?

One common challenge when formatting and displaying log-file contents in PHP is dealing with large log files that may slow down the page load time. To solve this, you can implement pagination to display only a certain number of log entries per page.

php
<?php

// Read log file contents
$logFile = 'path/to/logfile.log';
$logContents = file_get_contents($logFile);

// Split log contents by new lines
$logEntries = explode("\n", $logContents);

// Pagination variables
$perPage = 10;
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$totalEntries = count($logEntries);
$totalPages = ceil($totalEntries / $perPage);
$start = ($page - 1) * $perPage;
$end = $start + $perPage;

// Display log entries for current page
for ($i = $start; $i < $end; $i++) {
    if (isset($logEntries[$i])) {
        echo $logEntries[$i] . "<br>";
    }
}

// Pagination links
for ($i = 1; $i <= $totalPages; $i++) {
    echo "<a href='?page=$i'>$i</a> ";
}

?>