In this second part of our series, we’ll dive deeper into error handling in PHP. We’ll cover how to read, process, and present your error logs so you can monitor and debug more effectively. If you haven’t gone through Part 1 (logging errors), it’s a good idea to start there first.
Reading Error Logs Programmatically
Once you have error logs being generated, the next step is to read them in a usable way. The goal is to convert the log file into a structured format, so you can display recent errors first, filter entries, etc to make error handling easy.
Here is a sample PHP method that reads an error log file:
public function errorLogs($filePath = 'error.log') {
$fileContent = file($filePath);
$errorsArray = array();
if(sizeof($fileContent) == 0) {
return false;
}
foreach($fileContent as $row) {
$errors = explode(": ", $row);
if(empty($errors[1])) continue;
$errorsArray[] = $errors;
}
return array_reverse($errorsArray, true);
}
Explanation:
$fileContent = file($filePath);
This line of code will read the file line by line from the provided file path.
if(sizeof($fileContent) == 0) {
return false;
}
Checks whether the file is empty; if yes, returns false
to indicate there’s nothing to process.
foreach($fileContent as $row) {
$errors = explode(": ", $row);
if(empty($errors[1])) continue;
$errorsArray[] = $errors;
}
This part of the function will loop through the log contents row by row.
explode(": ", $row)
Splits each line at the pattern ": "
— usually separating a timestamp from the error message.
if (empty($errors[1])) continue;
Skips any lines that don’t have an error message portion after splitting.
$errorsArray[] = $errors;
Adds the parsed pieces to an array.
return array_reverse($errorsArray, true);
Reverses the order, so the newest log entries appear first in whatever display you build.
Why You’d Do This
Prioritize recent errors: By reversing the array, newer errors show up first so you don’t have to scroll through older logs.
Filter out noise: Skipping lines with missing data helps prevent malformed entries from causing trouble.
Make things display-friendly: Once you have structured data (e.g. timestamp + message), you can feed this into UI tables or dashboards.