How can I get useful error messages in PHP?

2019-08-31 07:08发布

I find programming in PHP quite frustrating. Quite often I will try and run the script and just get a blank screen back. No error message, just empty screen. The cause might have been a simple syntax error (wrong bracket, missing semicolon), or a failed function call, or something else entirely.

It is very difficult to figure out what went wrong. I end up commenting out code, entering "echo" statements everywhere, etc. trying to narrow down the problem. But there surely must be a better way, right?.

So, is there a way to get PHP to produce a useful error message as Java does? Can anyone recommend good PHP debugging tips and techniques?

26条回答
Luminary・发光体
2楼-- · 2019-08-31 07:31

The following enables all errors:

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

Also see the following links

查看更多
虎瘦雄心在
3楼-- · 2019-08-31 07:31

There is a really useful extension called "xdebug" that will make your reports much nicer as well.

查看更多
做个烂人
4楼-- · 2019-08-31 07:31

You can enable full error reporting (including notices and strict messages). Some people find this too verbose, but it's worth a try. Set error_reporting to E_ALL | E_STRICT in your php.ini.

error_reporting = E_ALL | E_STRICT

E_STRICT will notify you about deprecated functions and give you recommendations about the best methods to do certain tasks.

If you don't want notices, but you find other message types helpful, try excluding notices:

error_reporting = (E_ALL | E_STRICT) & ~E_NOTICE

Also make sure that display_errors is enabled in php.ini. If your PHP version is older than 5.2.4, set it to On:

display_errors = "On"

If your version is 5.2.4 or newer, use:

display_errors = "stderr"
查看更多
Emotional °昔
5楼-- · 2019-08-31 07:32

You can register your own error handler in PHP. Dumping all errors to a file might help you in these obscure cases, for example. Note that your function will get called, no matter what your current error_reporting is set to. Very basic example:

function dump_error_to_file($errno, $errstr) {
    file_put_contents('/tmp/php-errors', date('Y-m-d H:i:s - ') . $errstr, FILE_APPEND);
}
set_error_handler('dump_error_to_file');
查看更多
Emotional °昔
6楼-- · 2019-08-31 07:34

To persist this and make it confortale, you can edit your php.ini file. It is usually stored in /etc/php.ini or /etc/php/php.ini, but more local php.ini's may overwrite it, depending on your hosting provider's setup guidelines. Check a phpinfo() file for Loaded Configuration File at the top, to be sure which one gets loaded last.

Search for display_errors in that file. There should be only 3 instances, of which 2 are commented.

Change the uncommented line to:

display_errors = stdout
查看更多
做自己的国王
7楼-- · 2019-08-31 07:34

You might also want to try PHPStorm as your code editor. It will find many PHP and other syntax errors right as you are typing in the editor.

查看更多
登录 后发表回答