PHP Error Handling


At Elevated Third, it’s no secret that we develop the majority of our projects using the Drupal CMS. Occasionally though, a project comes our way that requires more of a home-cooked solution. Given our experience with the technologies that comprise Drupal, it’s only natural that we turn to PHP and MySQL for custom web application development.

In my time as a PHP developer, one of the greatest favors I ever did for myself was implement a simple error handling mechanism into my framework. To give credit where credit is due, I found an error handling (not to be confused with Exception handling, another topic for another post...) solution from while studying PHP MVC frameworks and tutorials, and I’ve used a slightly modified version ever since.

My favorite part about this particular setup is that the DEV_ENV constant declared in config.php provides a single point-of-contact for switching the application’s state between development and production. This cuts down on the amount of prep work needed to get a code base “production-ready” and greatly increases my efficiency as a developer since all requests will be run through these two files before hitting a Controller.

The code below is pretty self explanatory, so instead of inundating readers with trivial explanations (good code IS self-documenting, right?), I’ll check the comment section to answer any questions that may arise.


  2. define('ROOT', dirname(__FILE__));
  3. define('DEV_ENV', False);
  4. define('ERROR_LOG', ROOT . DS . 'error_log');


  1. require ‘config.php’;
  3. function setErrorReporting()
  4. {
  6. if (DEV_ENV === True) {
  7. // In development, so display errors instead of logging them.
  8. ini_set(‘display_errors’, ‘On’);
  9. } else {
  10. // In production, so log errors instead of displaying them.
  11. ini_set(‘display_errors’, ‘Off’);
  12. ini_set(‘log_errors’, ‘On’);
  13. }
  14. }
  16. // Router implementation
  17. // __autoload() implementation
  19. setErrorReporting();