Error message visibility in PHP

For a stable and relianble application on of the first things to set up is error tracking. You need to know when your app crashes and why, as a kind of feedback regarding your work. Your PHP app must tell you about what is happening in some form, otherwise it’s in a free flow and you don’t want that.

When I was building my first web pages, there were many errors on top of the page. As a self-taught developer I focused on the web site working, not endless warning messages. I was careful to swith all of the bad stuff off in the server configurations, leaving me with seemingly working product. My development was of very poor quality and my users instantly had issues with the app. Switching of error reporting was clearly a mistake.

As I found out later, the common approach to PHP development is leaving all the errors visible in the development envinroment (when you write the code), and then hiding error messages from the user in production (when the web site is launched).

So the quickest way to display every wrongdoing of your code is to add these lines into the beginning of it

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

The ini_set function allows you to change PHP runtime configurations for this particular scrip invocation. The display_errors and display_startup_errors configurations are responsible for switching on and off error reporting. The third line method error_reporting allows for control over which errors are processed (reported). The configuration is very flexible and multiple constants are available to configure what’s best for you. For example in case you want to see only WARNING messages, instead of E_ALL constant you can pass E_WARNING constant. That simple.

Though, even during development you might not want to see ALL of the errors. Unless you are very focused on the quality of your code, you might want to disable notices, as there can be indeed plenty of those (even in the open-source libraries / systems). The constants expression to do this –

This means to enable all of the error reporting with the exception of NOTICE level messages.

error_reporting(E_ALL & ~E_NOTICE);

When something goes wrong during your code execution, the PHP interpreter outputs your errors on the screen. With error reporting turned on you will not get empty screens or struggle with finding problems in your application. All of the errors will be seen right away in an appropriate manner, wheather you cannot connect to the database, use invalid data type for the operation or pass invalid arguments to a function.

With that said, good luck with your coding!