0

I might not be using the right approach here, but I have an ErrorHandler class that spits out an error page upon error, like so:

private function loadErrorPage() {

  if( file_exists( $this->errorPagePath ) ) {
    // load the error page: since it's an include, it'll have access all of this classe's properties!
    // i.e. $this->errstr, $this->errid, etc.
    include ( $this->errorPagePath ); 
  }
  // no error page! print generic message!
  else {
    echo 'Got a problem! Contact the admin!';
  }

  exit(); 
}

The problem I'm having is that sometimes my pages are called through an AJAX call! If I have an error in my POST that's caught by the errorhandler, I need to be able exit(), returning the full generated page in a JSON response, or just the link to it, and in JS, redirect to the actual $this->errorPagePath it was given in the response. However, this later solution will not quite work, since it would need all of required errorhandler properties, such as the errid, the error string, etc.

Not sure how to proceed here. Is there a way I can output the results of the include() into a variable and do something like:

$generatedErrorPage = include ( $this->errorPagePath );

if ( $this->sendErrorPageInJSON ) {
  exit(json_encode([ 'errorHtml' => $generatedErrorPage ]));
}
else
{
  echo $generatedErrorPage;
  exit();
}

Thanks for your help! Pat

1 Answer 1

1

You would have to start output buffering, include the file and end buffering to initialise the variable with it's contents

// Start output buffering
ob_start();

// Include the file
include ( $this->errorPagePath );

// End buffering and return its contents
$generatedErrorPage = ob_get_clean();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.