How to get useful error messages in PHP?

2019-01-29 02:47发布

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 useful error message like Java does? Can anyone recommend good PHP debugging tips, tools and techniques?

29条回答
老娘就宠你
2楼-- · 2019-01-29 03:36

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.

查看更多
太酷不给撩
3楼-- · 2019-01-29 03:36

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"
查看更多
smile是对你的礼貌
4楼-- · 2019-01-29 03:37

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
查看更多
戒情不戒烟
5楼-- · 2019-01-29 03:37
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
查看更多
一纸荒年 Trace。
6楼-- · 2019-01-29 03:37

Use Kint. It is combination of debugging commands on steroids. https://kint-php.github.io/kint/ It is very similar to Nette Tracy

查看更多
家丑人穷心不美
7楼-- · 2019-01-29 03:38

You can include the following lines in the file you want to debug:

error_reporting(E_ALL);
ini_set('display_errors', '1');

This overrides the default settings in php.ini, which just make PHP report the errors to the log.

查看更多
登录 后发表回答