As with any programming language, when you code in PHP, it helps immensely if you set up your applications to handle errors gracefully. This article explores some of the most common error checking methods available in PHP, and provides hands-on examples that use different error handling methods.
Getting started with PHP is quite easy. Armed with a good PHP editor, any beginner can create a simple database-driven web application with minor hassles. Moreover, given a little more time, an average developer can pick up a good understanding of object-oriented programming and start working with classes and objects. Definitely, this sounds like a good and exciting thing -- except for when, during the development of an application, one has to write error handling code.
Let’s be honest. For novice (and not so novice) programmers, coding error handling routines is boring stuff. Even when it’s something that you can’t hide from very often, error manipulation usually is limited to writing a few “die()/exit()” statements when connecting to a database server, and some additional checking lines for handling potential errors within program execution. From a realistic point of view, the things about error handling is that if you’re developing a web application which lacks decent error checking code (due to ignorance or laziness), sooner or later your application will fail ungracefully. The result of this will be possibly the occurrence of potentially harmful errors -- particularly in the area of security -- and the display of ugly messages, making the whole program look very unprofessional.
Since error handling is something that you should introduce (at least progressively) into your applications, in this article I’ll explore some of the most common error checking methods available in PHP, in order to make web applications much more robust and reliable. The end result of this experience will be an illustrative list of hands-on examples that utilize different error handling methods, ranging in from using simple “die()” statements, to manipulating errors within an object-oriented context, by utilizing exceptions.
Having drawn the general guidelines for this tutorial, it’s time to dive into the topic and turn error handling into an instructive journey. Let’s get started.