Show PHP errors in 4 lines


Introduction

Have there been moments for you when

  • you seem to be racing against time
  • there is an error you cannot seem to get the head or tail of
  • there is a deliverable that is a little bit out of reach

When moments like the above come, then you need a short code piece of code to help you out of a tight spot. Here is a short code snippet you could use to help you debug in those moments. This is especially helpfully when you need to see exactly why the bug occurred.

Snippet

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
die("hello world");

The above is a summary of all you need to know in quickly pick up on PHP errors. I would like to concern you with only the most important lines that you may need.

Report errors

error_reporting(E_ALL);

When the code is being run, the above code helps you show the bug. And it shows directly on the web page. There are predefined constants that come with reporting the errors. The following would be of interest to you.

  • E_ERROR
  • E_ALL
  • E_WARNING

The others you might be interesting in using are shown at this web page

Over-ride the configuration file

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

You could have done setup your code to show errors in the php.ini file. However, this would have applied to all pages in your PHP environment. Another disadvantage in doing it at a global level ( that is in your php.ini file ) is that it would impact all pages on that PHP server.

With this in mind, it may seem simplier to override just the one page you are interested in. Show the error for the specific page that is troubling you. Normally, I might use the two lines above. After I see the error then I am wiser for later.

Halting execution of page

die(var_dump("hello world"));

Other times, you have been able to pinpoint the source of the problem. And you may not want to see the contents of a specific variable. Simply use the code snippet below. Replace the string “hello world” with your own variable or array.

Conclusion

That is it. I went as brief as possible in this post. However, I must stress that nothing beats a good IDE editor. This can help you in picking errors as soon as you are type.

Whenever you do ran into those moments when you must get into the root of the issue like yesterday, then feel free to copy and paste the snippets above.

Hopefully I have spared a coder somewhere the inconveniences in troubleshooting the errors in his PHP code. And with that, I wish you happy coding.

Take care and cheers.

Anthony Eli Agbenu would love to get in touch
© 2022 Eli's blog. All rights reserved.