Reputation: 6394
I'm trying to read a file when ever an error occurs within my scripts so I can throw a custom error page.
When using ob_start/set_error_handler I am unable to use file_get_contents or ob_start within the callback to get the contents of my error template.
Does anyone know how I can output my custom template (and using eval) within the callback?
Edit: Some code
error_reporting(E_ALL);
ini_set("display_errors", 1);
function fatal_error_handler($buffer) {
if (ereg("(error</b>:)(.+)(<br)", $buffer, $regs) ) {
$ErrorString = preg_replace("/<.*?>/","",$regs[2]);
error_log($ErrorString);
$template = file_get_contents(sprintf('%s/errors/Error.php', TEMPLATES));
return eval(sprintf('?>%s<?', $template);
//return "ERROR CAUGHT check log file";
}
return $buffer;
}
function handle_error ($errno, $errstr, $errfile, $errline)
{
error_log("$errstr in $errfile on line $errline");
if($errno == FATAL || $errno == ERROR){
ob_end_flush();
echo "ERROR CAUGHT check log file";
exit(0);
}
}
ob_start("fatal_error_handler");
set_error_handler("handle_error");
The above just displays an empty page.
error_reporting(E_ALL);
ini_set("display_errors", 1);
function fatal_error_handler($buffer) {
if (ereg("(error</b>:)(.+)(<br)", $buffer, $regs) ) {
$ErrorString = preg_replace("/<.*?>/","",$regs[2]);
error_log($ErrorString);
ob_start();
include(sprintf('%s/errors/Error.php', TEMPLATES));
$template = ob_get_contents();
ob_end_clean();
return eval(sprintf('?>%s<?', $template));
//return "ERROR CAUGHT check log file";
}
return $buffer;
}
function handle_error ($errno, $errstr, $errfile, $errline)
{
error_log("$errstr in $errfile on line $errline");
if($errno == FATAL || $errno == ERROR){
ob_end_flush();
echo "ERROR CAUGHT check log file";
exit(0);
}
}
ob_start("fatal_error_handler");
set_error_handler("handle_error");
and the above gives the following:
Fatal error: ob_start() [<a href='ref.outcontrol'>ref.outcontrol</a>]: Cannot use output buffering in output buffering display handlers in /var/www/index.php on line 16
Upvotes: 0
Views: 1270
Reputation: 400972
You have to :
file_get_contents
returns false when it encounters an error.
false
, you can display your templateIt would give that kind of code :
$result = @file_get_contents('non-existing-file');
if ($result === false) {
echo "An error has occured";
}
Which, in my case, displays :
An error has occured
Now, up to you to display your error template, depending on the Framework you might be using and all that ;-)
Upvotes: 2