How to get useful error messages in PHP
P粉590929392
2023-08-20 14:30:17
<p>Many times, I will try to run a PHP script and only get a blank screen. No error message, just a blank screen. The cause could be a simple syntax error (wrong parentheses, missing semicolon), or a failed function call, or something else entirely. </p>
<p>It's hard to figure out what's going wrong. I ended up commenting out the code, adding "echo" statements here and there, etc. to try to narrow down the scope of the problem. But there has to be a better way, right? </p>
<p>Is there a way to make PHP generate a useful error message like Java does? </p>
The following code enables all errors:
You can also refer to the following links:
By default, display errors is turned off because you don't want "customers" to see error messages.
Check out this page in the PHP documentation for information on two directives:
error_reporting
anddisplay_errors
. What you might want to change isdisplay_errors
.So you have 3 options:
(1) You can check the error log file as it will contain all errors (unless logging is disabled). To enable error logging, ensure that the
log_errors
configuration directive is set toOn
. Logs are also helpful when the error is not caused by PHP but by the web server.(2) You can add the following 2 lines of code to help you debug non-syntax errors that occur in the same file:
Note that on a production server, the latter should be set to
Off
(but only the latter, as you still need to know from the log file all errors that occurred).However, for syntax errors that occur in the same file, the above commands will not work and you need to enable them in php.ini. If you can't modify the php.ini file, you can also try adding the following lines to the .htaccess file, although this is rarely supported these days:
(3) Another option is to use an editor that checks for errors as you type, such as PhpEd, VSCode, or PHPStorm. They all come with debuggers that provide more detailed information. (The PhpEd debugger is very similar to xdebug and integrated directly into the editor, so you can do it all with one program.)