PHP错误处理的函数和相关信息

来源:百度文库 编辑:神马文学网 时间:2024/05/01 16:56:06
配置说明:
 出错处理和日志
error_reporting  =  E_ALL & ~E_NOTICE & ~E_STRICT
[recommended]->error_reporting  =  E_ALL
 显示所有的错误,除了提醒和编码标准化警告。
 错误报告是位字段。可以将数字加起来得到想要的错误报告等级。
 E_ALL             - 所有的错误和警告(不包括 E_STRICT)
 E_ERROR           - 致命性的运行时错误
 E_WARNING         - 运行时警告(非致命性错误)
 E_PARSE           - 编译时解析错误
 E_NOTICE          - 运行时提醒(这些经常是你代码中的bug引起的,也可能是有意的行为造成的。)
 E_STRICT     - 编码标准化警告,允许PHP建议如何修改代码以确保最佳的互操作性向前兼容性。
 E_CORE_ERROR      - PHP启动时初始化过程中的致命错误
 E_CORE_WARNING    - PHP启动时初始化过程中的警告(非致命性错)
 E_COMPILE_ERROR   - 编译时致命性错
 E_COMPILE_WARNING - 编译时警告(非致命性错)
 E_USER_ERROR      - 用户自定义的错误消息
 E_USER_WARNING    - 用户自定义的警告消息
 E_USER_NOTICE     - 用户自定义的提醒消息

以上的值(不管是数字还是符号)被用来建立指定要报告的错误的位掩码(bitmask)。您可以使用位操作符来叠加或者掩去某一种类型的错误。请注意 php.ini 仅能识别“|”、“~”、“!”和“&”四种符号,而 php3.ini 无法识别任何位操作符。

在 PHP 4 中,error_reporting 默认的值为 E_ALL & ~E_NOTICE,表示显示除 E_NOTICE-level 以外所有错误的警告信息。在 PHP 3 中,其默认值为 (E_ERROR | E_WARNING | E_PARSE),表示的内容和 PHP 4 相同。注意,由于 php3.ini 不支持常量,error_reporting 的设置应该用数字来表示,因此,其值应该为 7

这项设置的初始设定可以通过更改 ini 文件中的 error_reporting 选项来改变,也可以在 Apache 系统中设置 httpd.conf 中的 php_error_reporting(PHP 3 为 php3_error_reporting)来改变。另外,脚本的运行过程中,也可以通过 error_reporting() 函数来更改该设置。

警告

在将服务端的代码从 PHP 3 升级到 PHP 4 时,您需要检查这些设置,或者调用 error_reporting(),否则您可能会屏蔽新类型的错误报告,尤其是 E_COMPILE_ERROR。这将有可能导致没有任何反馈信息的空文档,使得您不知道发生了什么,也不知道到哪里检查发生的问题。

所有的 PHP 表达式都可以使用“@”前缀,该前缀将屏蔽该表达式所有的错误信息。如果在该语句运行过程中出现了错误并且 track_errors 选项开启,则您可以在全局变量 $php_errormsg 中找到错误信息。

注: @ 错误信息控制符前缀不会屏蔽解析错误信息。

警告

目前 @ 错误信息控制符前缀有可能会屏蔽导致脚本停止运行的关键错误的信息。这也就是说,如果您在不可用的,或者未正确定义的函数前面使用 @ 符号来抑制错误,脚本程序会在该处停止运行,并且不会给出任何关于为什么停止的提示信息。



 例子:
error_reporting = E_ALL & ~E_NOTICE              显示所有的错误,除了提醒
error_reporting = E_COMPILE_ERROR|E_ERROR|E_CORE_ERROR   仅显示错误display_errors = On
[recommended]->display_errors = Off
 作为输出的一部分显示出错误信息
 在最终发布的web站点上,强烈建议你关掉这个特性,并使用错误日志代替(参看下面)。
 在最终发布的web站点打开这个特性可能暴露一些安全信息,
 例如你的web服务上的文件路径、数据库规划或别的信息。display_startup_errors = Off
 即使"display_errors"特性被打开,关闭此参数也将不显示PHP启动时的错误。
 强烈建议你关掉这个特性,除非你必须要用于调试中。log_errors = Off
[recommended]->log_errors = On
 在日志文件里记录错误(服务器指定的日志,stderr标准错误输出,或error_log(下面的))
 正如上面说明的那样,强烈建议你在最终发布的web站点时用日志记录错误而不是直接输出。log_errors_max_len = 1024
 设置错误日志文件的最大长度。
 设为 0 可以允许无限长度。ignore_repeated_errors = Off
 忽略重复的错误信息
 如果关闭这个参数,错误信息必须出现在同一个文件的同一行才被忽略。
 如果打开这个参数,则没有这个限制。ignore_repeated_source = Off
 忽略重复的错误源
 忽略重复的错误信息时忽略重复的错误源
 如果打开这个参数,将不会记录不同的出错文件和对应行的错误信息。report_memleaks = On
 报告内存泄漏
 如果关闭该参数,将不记录或者显示内存泄漏
 这个参数只在调试编译中起作用,并且必须在错误报告中包含 E_WARNINGtrack_errors = Off
 保存最近一个错误/警告消息于变量$php_errormsg (boolean)中html_errors = Off
 禁用出错信息中的HTML标记
 注意: 不要在发布的程序中使用这个特性。docref_root = "/phpmanual/"
docref_ext = .html
 如果打开了html_errors参数,PHP将会在出错信息上显示超连接,
 直接链接到一个说明这个错误或者导致这个错误的函数的页面。
 你可以从http://www.php.net/docs.php下载php手册,并设置docref_root参数,将他指向你本地的手册所在目录。
 你还必须设置"docref_ext"来指定文件的扩展名。
 注意: 不要在发布的程序中使用这个特性。error_prepend_string = ""
 用于错误信息前输出的字符串error_append_string = "
"
 用于错误信息后输出的字符串error_log = filename
 将错误日志记录到哪个文件中。
 如果设为"syslog", 错误日志将被记录到系统日志中(NT下的事件日志, Unix下的syslog(3))

相关函数:
debug_backtrace -- Generates a backtrace 创建一个跟踪调用传递的路线 (PHP5)(PEAR 上PHP4的实现)
error_log -- Send an error message somewhere 把错误信息写入日志
error_reporting -- Sets which PHP errors are reported 设置错误报告等级
restore_error_handler -- Restores the previous error handler function 恢复上一个错误处理函数
restore_exception_handler --  Restores the previously defined exception handler function 恢复上一个异常处理函数 (PHP 5)
set_error_handler --  Sets a user-defined error handler function 设置用户自定义的错误处理函数
set_exception_handler --  Sets a user-defined exception handler function 设置用户自定义的异常处理函数
trigger_error -- Generates a user-level error/warning/notice message 创建一个用户级别(E_USER开头)的错误信息
user_error -- Alias of trigger_error() trigger_error() 的别名 函数用法:

error_log

送出一个错误信息。

语法: int error_log(string message, int message_type, string [destination], string [extra_headers]);

返回值: 整数

函数种类: PHP 系统功能

内容说明

此函数会送出错误信息到 Web 服务器的错误 log 文件,TCP Port,或到指定文件。第一个参数 message 即为要送出的错误信息。第二个参数 message_type 为整数值:0 表示送到操作系统的 log (UNIX 在 syslog、Windows NT 记录到事件记录);1 则使用 PHP 的 Mail() 函数,送信息到某 E-Mail 处,第四个参数 extra_headers 亦会用到;2 则将错误信息送到 TCP 埠,此时第三个参数 destination 表示目的地 IP 及 Port;3 则将信息存到文件 destination 中。

使用范例

本例为登入 Oracle 数据库出现问题的处理。

if (!Ora_Logon($username$password)) {
  
error_log("Oracle 数据库不可用!"0);
}
if (!(
$foo allocate_new_foo()) {
  
error_log("出现大麻烦了!"1"webmaster@www.mydomain.com.tw");
}
error_log("搞砸了!"2"127.0.0.1:9700");
error_log("搞砸了!"2"loghost");
error_log("搞砸了!"3"/var/tmp/my-errors.log");
----------------------------------------------------------------------------------------------------------

error_reporting

设定错误讯息回报的等级。

语法: int error_reporting(int [level]);

传回值: 整数

函式种类: PHP 系统功能

内容说明

本函式用来设定错误讯息回报的等级,参数 level 是一个整数的位元遮罩 (bitmask),见下表。

遮罩值 表示名称 1 E_ERROR 2 E_WARNING 4 E_PARSE 8 E_NOTICE 16 E_CORE_ERROR 32 E_CORE_WARNING 0 关闭错误报告

  • E_NOTICE 表示一般情形不记录,只有程式有错误情形时才用到,例如企图存取一个不存在的变数,或是呼叫 stat() 函式检视不存在的档案。
  • E_WARNING 通常都会显示出来,但不会中断程式的执行。这对除错很有效。例如:用有问题的常规表示法呼叫 ereg()
  • E_ERROR 通常会显示出来,亦会中断程式执行。意即用这个遮罩无法追查到记忆体配置或其它的错误。
  • E_PARSE 从语法中剖析错误。
  • E_CORE_ERROR 类似 E_ERROR,但不包括 PHP 核心造成的错误。
  • E_CORE_WARNING 类似 E_WARNING,但不包括 PHP 核心错误警告。


范例

  例子 1. error_reporting() examples
// Turn off all error reporting 关闭错误报告
error_reporting(0);

// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting(E_ALL ^ E_NOTICE);

// Report all PHP errors (bitwise 63 may be used in PHP 3)
error_reporting(E_ALL);

// Same as error_reporting(E_ALL);
ini_set(‘error_reporting‘, E_ALL);

?>

set_error_handler自定义错误处理函数
mixed set_error_handler ( callback error_handler [, int error_types] )
注意:
  (1)E_ERROR、E_PARSE、E_CORE_ERROR、E_CORE_WARNING、E_COMPILE_ERROR、E_COMPILE_WARNING是不会被这个句柄处理的,也就是会用最原始的方式显示出来。不过出现这些错误都是编译或PHP内核出错,在通常情况下不会发生。

  (2)使用set_error_handler()后,error_reporting ()将会失效。也就是所有的错误(除上述的错误)都会交给自定义的函数处理。
其它有关于set_error_handler()的信息,大家可以参考PHP的官方手册。

参数:
error_handler 包括4个变量
errno

The first parameter, errno, contains the level of the error raised, as an integer. 错误代码(或E_ERROR等常量)

errstr

The second parameter, errstr, contains the error message, as a string. 错误信息

errfile

The third parameter is optional, errfile, which contains the filename that the error was raised in, as a string. 产生错误的文件

errline

The fourth parameter is optional, errline, which contains the line number the error was raised at, as an integer. 产生错误的行号

errcontext

The fifth parameter is optional, errcontext, which is an array that points to the active symbol table at the point the error occurred. In other words, errcontext will contain an array of every variable that existed in the scope the error was triggered in. 可选参数


error_types 错误类型
Can be used to mask the triggering of the error_handler function just like the error_reporting ini setting controls which errors are shown. Without this mask set the error_handler will be called for every error regardless to the setting of the error_reporting setting

  可用于定义对特定的错误类型使用,就像用error_reporting定义一样。如果缺省,那么每个错误(除了E_ERROR、E_PARSE、E_CORE_ERROR、E_CORE_WARNING、E_COMPILE_ERROR、E_COMPILE_WARNING之外的)都会调用这个函数。
   补充:
Given this code:

class CallbackClass {
   function CallbackFunction() {
       // refers to $this
   }

   function StaticFunction() {
       // doesn‘t refer to $this
   }
}

function NonClassFunction() {
}

there appear to be 3 ways to set a callback function in PHP (using set_error_handler() as an example):

1: set_error_handler(‘NonClassFunction‘);

2: set_error_handler(array(‘CallbackClass‘, ‘StaticFunction‘));

3: $o =& new CallbackClass();
   set_error_handler(array($o, ‘CallbackFunction‘));

The following may also prove useful:

class CallbackClass {
   function CallbackClass() {
       set_error_handler(array(&$this, ‘CallbackFunction‘)); // the & is important
   }
   
   function CallbackFunction() {
       // refers to $this
   }
}

The documentation is not clear in outlining these three examples.

范例

例子 1. Error handling with set_error_handler() and trigger_error()

The example below shows the handling of internal exceptions by triggering errors and handling them with a user defined function:

// set the error reporting level for this script
error_reporting(E_USER_ERROR | E_USER_WARNING | E_USER_NOTICE);

// error handler function
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
  switch (
$errno) {
  case
E_USER_ERROR:
    echo
"My ERROR [$errno] $errstr
\n";
    echo
"  Fatal error in line $errline of file $errfile";
    echo
", PHP " . PHP_VERSION . " (" . PHP_OS . ")
\n"
;
    echo
"Aborting...
\n"
;
    exit(
1);
    break;
  case
E_USER_WARNING:
    echo
"My WARNING [$errno] $errstr
\n";
    break;
  case
E_USER_NOTICE:
    echo
"My NOTICE [$errno] $errstr
\n";
    break;
  default:
    echo
"Unkown error type: [$errno] $errstr
\n";
    break;
  }
}

// function to test the error handling
function scale_by_log($vect, $scale)
{
  if (!
is_numeric($scale) || $scale <= 0) {
    
trigger_error("log(x) for x <= 0 is undefined, you used: scale = $scale", E_USER_ERROR);
  }

  if (!
is_array($vect)) {
    
trigger_error("Incorrect input vector, array of values expected", E_USER_WARNING);
    return
null;
  }

  for (
$i=0; $i<count($vect); $i++) {
    if (!
is_numeric($vect[$i]))
      
trigger_error("Value at position $i is not a number, using 0 (zero)", E_USER_NOTICE);
      
$temp[$i] = log($scale) * $vect[$i];
    }
    return
$temp;
  }

// set to the user defined error handler
$old_error_handler = set_error_handler("myErrorHandler");

// trigger some errors, first define a mixed array with a non-numeric item
echo "vector a\n";
$a = array(2,3, "foo", 5.5, 43.3, 21.11);
print_r($a);

// now generate second array, generating a warning
echo "----\nvector b - a warning (b = log(PI) * a)\n";
$b = scale_by_log($a, M_PI);
print_r($b);

// this is trouble, we pass a string instead of an array
echo "----\nvector c - an error\n";
$c = scale_by_log("not array", 2.3);
var_dump($c);

// this is a critical error, log of zero or negative number is undefined
echo "----\nvector d - fatal error\n";
$d = scale_by_log($a, -2.5);

?>

上例的输出类似于:

vector a                        Array                        (                        [0] => 2                        [1] => 3                        [2] => foo                        [3] => 5.5                        [4] => 43.3                        [5] => 21.11                        )                        ----                        vector b - a warning (b = log(PI) * a)                        WARNING [1024] Value at position 2 is not a number, using 0 (zero)
Array ( [0] => 2.2894597716988 [1] => 3.4341896575482 [2] => 0 [3] => 6.2960143721717 [4] => 49.566804057279 [5] => 24.165247890281 ) ---- vector c - an error ERROR [512] Incorrect input vector, array of values expected
NULL ---- vector d - fatal error FATAL [256] log(x) for x <= 0 is undefined, you used: scale = -2.5
Fatal error in line 36 of file trigger_error.php, PHP 4.0.2 (Linux)
Aborting...