Useful error pages with PHP

While it would be nice never to have an error on your site, things happen. A page may be moved, mispellings occur, and as the site becomes more complex (XML, AJAX, flash, etc.), the odds of errors increase. Having an error page that mails diagnostic information to the web master helps stamp out problems quickly. You may get a shower of emails at first, but those should decrease as you fix the problems.

The following code is intended to be placed at the very top of the error page, before any HTML. This will do two things: first, send the correct error headers back to the user, and second, compose an email message that includes diagnostic information, including the user’s IP address and host name, and a dump of all the defined PHP variables (including much more information if you need to dive deeper.) You can also automate the web page’s title by inserting <title><?php echo $desc; ?></title> in the head section.

  1. <?php
  2. ob_start("ob_gzhandler"); #enables compression if the user’s client allows
  3. #the following four constants are the only things you need to edit
  4. $head = '403 Forbidden' ; #replace this with the standard text for the particular error message, e.g., '404 Not Found', '410 Gone'
  5. $desc = 'Error 403 (Forbidden)'; #this is the friendlier version, for the email message
  6. $fr = $_SERVER['SERVER_ADMIN']; #email address representing your site: if SERVER_ADMIN isn't defined, insert the correct email address instead
  7. $to = 'webmastersmailaddress@whatever.com'; #recipient of the error messages
  8. header("HTTP/1.1 $head"); #send error header to HTTP/1.1 user agents
  9. header("Status: $head"); #send error header to HTTP/1.0 user agents
  10. $heading = '<p>The following error has been received on ' . date('D M j G:i:s T Y') . ': ' . $desc . '.</p>' ;
  11. $requrl = '<p><strong>Requested URL</strong>: ' . $_SERVER['REQUEST_URI'] . '</p>' ;
  12. $refurl = '<p><strong>Referring URL</strong>: ' . $_SERVER['HTTP_REFERER'] . '</p>' ;
  13. $ipaddr = '<p><strong>IP Address</strong>: ' . $_SERVER['REMOTE_ADDR'] . '</p>' ;
  14. $hostname = '<p><strong>Host name</strong>: ' . gethostbyaddr($_SERVER['REMOTE_ADDR']) . '</p>' ;
  15. $useragent = '<p><strong>User agent</strong>: ' . $_SERVER['HTTP_USER_AGENT'] . '.</p>' ;
  16. $variabledump = '<p><pre>' . print_r(get_defined_vars(),true) . '</pre></p>' ;
  17. $mailcontents = $heading . $requrl . $refurl . $ipaddr . $hostname . $useragent . $variabledump;
  18. $subject = $desc . ' reported from '.$_SERVER['SERVER_NAME'] . '. Remote server ' . gethostbyaddr($_SERVER['REMOTE_ADDR']);
  19. $headers = "From: $fr\nContent-type: text/html\nX-Mailer: PHP/" . phpversion();
  20. mail($to, $subject, $mailcontents, $headers);
  21. ?>

This software is licensed under the CC-GNU GPL. CC-GNU GPL