Monday, 10 September 2018

PHP is not showing any error messages

Help! There are errors in my PHP code and there are no error messages being displayed. I've even set error_reporting to E_ALL and still PHP is not displaying the errors. How do I debug it? How do I show the errors? This post looks at the very simple answer to these questions.

display_errors configuration variable

If your PHP script is halting (or not executing code like you expect) and not displaying any error messages even though you know there's an error happening, it's likely that the 'display_errors' configuration setting is switched off.

Check the php.ini file

You can check if display_errors is off by checking the php.ini file. This is located at various different places depending on your operating system or distribution, but is commonly at /etc/php.ini or similar. Open up the file and look for "display_errors" and you'll find something along these lines:
; Print out errors (as a part of the output).  For production web sites,
; you're strongly encouraged to turn this feature off, and use error logging
; instead (see below).  Keeping display_errors enabled on a production web site
; may reveal security information to end users, such as file paths on your Web
; server, your database schema or other information.
display_errors = Off
As the comments state, it's a good idea to switch off displaying errors on a production site but you'd normally want them on on a development server so you can see the reason for the error.

Use ini_get or get_cfg_var

Another way to check the status of the display_errors configuration variable is with the ini_get or get_cfg_var functions as shown in the following example:
echo (integer)ini_get('display_errors')
The reason I've added the (integer) part is to typecast the result as an integer which means either a 0 or 1 will be displayed. Without the type casting nothing will be echoed if display_errors is switched off.

Switching display_errors on

So the reason the errors aren't being displayed is because they're switched off. So how do you switch them back on again? You can either modify the php.ini file and reload the webserver to apply the changes, or modify it in your script for that script only. Obviously you can't change the php.ini file if it's not a webserver you have control over, and it's not a good idea on a production server anyway. So in these cases you'll want to change the value in code.
The ini_set() function allow you to change some of the PHP configuration directives at run time. To switch display errors on for the rest of your script (or until you change the value again), you would do this:
ini_set('display_errors', 1);
Your error messages should now be displayed. Note that setting it this way won't have any affect if the script has fatal errors. This is because the desired runtime action does not get executed.

Related posts:

0 comments:

Post a Comment