#native_company# #native_desc#
#native_cta#

Using PHP Error Handling Page 2

By Mattias Nilsson
on July 30, 2000

Throwing errors from PHP pages

Throwing errors from a PHP page is quite the same as emulating Apache’s behaviour for ErrorDocument
directives, you simply redirect the user using a query-string that specifies variables that
Apache usually sets as environment variables. This makes it possible to use the same error page
for all kinds of errors. An example:

<?php

function throw_error($message) {

  
$error_page "/err/error.php";

  $error_url $error_page;

  
$error_url .= "?REDIRECT_ERROR_NOTES=$message";

  
$error_url .= "&REDIRECT_URL=" $GLOBALS["PHP_SELF"];

  
$error_url .= "&REDIRECT_REQUEST_METHOD=$REQUEST_METHOD";

  
$error_url .= "&REDIRECT_STATUS=501";

  
Header("Status: 501");

  
Header("Location: $error_url");

  exit;

}

ob_start();  // Use output buffering to be able to throw errors anywhere on this page.

if(!condition) {

    
throw_error("the condition failed");

}

ob_end_flush(); // Page rendered, flush the output buffer.

?>



Using the PHP4 feature called output buffering also helps creating generic error reporting
functionality. By not flushing the output buffer until you are sure the whole page has rendered
error-free, you are able to make Header calls anywhere in your code to redirect the user.
I’ll leave up to the reader to design and implement his/her own error.php page to suit his/her site.
Don’t forget that you can include a form with email submission possibilities for the users to send
you comments.