为什么要压制PHP错误?

Mat*_*att 3 php error-handling

我想知道为什么你会"抑制"PHP错误.我明显看到错误产生的额外警告线的区别,但抑制它是否有好处?

 Access denied for user 'user'@'localhost' (using password: YES) 
Run Code Online (Sandbox Code Playgroud)

VS

Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'user'@'localhost'       (using password: YES) in (deleted) on line 8
Access denied for user 'user'@'localhost' (using password: YES)
Run Code Online (Sandbox Code Playgroud)

如果是这样,我应该养成@在我的PHP程序中在MySQL查询开始时输入的习惯吗?

Mic*_*ski 7

你应该积极进入抑制错误的习惯.错误是有原因的.相反,在代码中正确和防御地处理它们,并不断完善代码,直到错误消失.

你应该做的事情如下:

$conn = mysql_connect($host, $user, $pass);

// Always test to see if your action/connection/whatever was successful
if (!$conn) {
  // something went wrong.  handle the error
  // Display a message for the user, write a message to `error_log()`, whatever's appropriate
}
else mysql_select_db($dbname);
Run Code Online (Sandbox Code Playgroud)

在生产系统上,您永远不应该显示错误,因为它可能会泄露您的代码和数据库的详细信息.相反,display_errors在php.ini或运行时关闭:

// In development and production, make sure all errors are reported
error_reporting(E_ALL & E_STRICT);

// In development show all errors on screen so you handle them as they occur
ini_set('display_errors', 1);

// In production turn them off
ini_set('display_errors', 0);
Run Code Online (Sandbox Code Playgroud)

事实上,在这个经典问题中,错误抑制@是PHP错误练习的第二大投票.