PHP 基础
PHP 简介
PHP 入门
PHP 语法
PHP 变量
PHP 常量
PHP 输出和打印
PHP 数据类型
PHP 字符串
PHP 运算符
PHP If…Else
PHP Switch…Case
PHP 数组
PHP 数组排序
PHP 循环
PHP 函数
PHP 数学运算
PHP GET 和 POST
PHP 高级
PHP 日期和时间
PHP 包含文件
PHP 文件系统
PHP 解析目录
PHP 文件上传
PHP 文件下载
PHP Cookies
PHP Sessions
PHP 发送邮件
PHP 表单处理
PHP 表单验证
PHP 过滤器
PHP 错误处理
PHP 类和对象
PHP 魔术常量
PHP JSON 解析
PHP 正则表达式
PHP 异常处理
PHP 和 MySQL 数据库
PHP MySQL 简介
PHP MySQL 连接
PHP MySQL Create Database
PHP MySQL Create Table
PHP MySQL Insert
PHP MySQL Prepared
PHP MySQL Last Inserted ID
PHP MySQL Select
PHP MySQL Where
PHP MySQL Limit
PHP MySQL Order By
PHP MySQL Update
PHP MySQL Delete
PHP MySQL CRUD 应用
PHP MySQL Ajax 搜索
PHP MySQL 登录系统
PHP参考
PHP String Functions
PHP Array Functions
PHP File System Functions
PHP Date/Time Functions
PHP Calendar Functions
PHP MySQLi Functions
PHP Filters
PHP Error Levels
PHP常见问题解答
如何在 PHP 中编写注释
如何在 PHP 中删除字符串中的空格
如何在 PHP 中查找字符串中的字符数
如何在 PHP 中查找字符串中的单词数
如何在 PHP 中删除字符串中的特殊字符
如何在 PHP 中替换字符串中的一个单词
如何在 PHP 中对字符串前面追加
如何在 PHP 中对字符串后面追加
如何在 PHP 中从字符串中提取子串
如何在 PHP 中比较两个字符串
如何在 PHP 中获取当前页面的 URL
如何在 PHP 中通过连接数组值创建字符串
如何在 PHP 中将字符串拆分为数组
如何在 PHP 中合并两个字符串
如何在 PHP 中把字符串转换成小写字母
如何在 PHP 中把字符串转换成大写字母
如何在 PHP 中把字符串的第一个字母转换成大写字母
如何在 PHP 中把特殊的 HTML 实体转换回字符
如何在 PHP 中删除字符串开头的空格
如何在 PHP 中删除字符串结尾的空格
如何在 PHP 中新建一行
如何在 PHP 中查找字符串长度
如何在 PHP 中检查变量是否已设置
如何在 PHP 中检查变量是否为空
如何在 PHP 中检查变量是否为NULL
如何在 PHP 中反转字符串
如何在 PHP 中用另一个字符串替换字符串的一部分
如何在 PHP 中计算子串在字符串中出现的次数
如何在 PHP 中计算数组中的所有元素
如何在 PHP 中打印或回显数组的所有值
如何在 PHP 中显示数组的结构和值
如何在 PHP 中颠倒数组的顺序
如何在 PHP 中检查数组中是否存在值
如何在 PHP 中检查数组中是否存在键
如何在 PHP 中删除数组中的最后一个元素
如何从 PHP 数组中删除第一个元素
如何在 PHP 中为数组的开头添加元素
如何在 PHP 中为数组的末尾添加元素
如何在 PHP 中把两个或多个数组合并成一个数组
如何在 PHP 中按字母顺序对数组值排序
如何在 PHP 中删除数组中的重复值
如何在 PHP 中随机调整数组的顺序
如何在 PHP 中比较两个数组的值
如何在 PHP 中计算数组中数值的总和
如何在 PHP 中删除数组中的空值
如何在 PHP 中用数组值填充下拉列表
如何在 PHP 中获取关联数组的所有键值
如何在 PHP 中获取关联数组的所有值
如何在 PHP 中按键对关联数组排序
如何在 PHP 中按值对关联数组排序
如何在 PHP 中从数组中获取单个值
如何在 PHP 中循环浏览多维数组
如何在 PHP 中从数组中删除元素
如何在 PHP 中检查字符串是否包含特定单词
如何在 PHP 中获取当前日期和时间
如何在 PHP 中进行重定向
如何在 PHP 中删除字符串中的所有空格
如何用 PHP 获取当前年份
如何在 PHP 中将日期从 yyyy-mm-dd 转换为 dd-mm-yyyy 格式
如何在 PHP 中将字符串转换为数字
如何在 PHP 中获取数组的第一个元素
如何在 PHP 中将日期转换为时间戳
如何在 PHP 中为空数组添加元素
如何在 PHP 中把整数转换成字符串
如何用值而不是键删除 PHP 数组元素
如何在 PHP 中将键和值同时推入数组
如何使用 PHP 定期刷新页面
如何从 PHP 字符串中删除最后一个字符
如何从 PHP 脚本返回 JSON
如何让 PHP 显示错误
PHP 错误处理 - php7基础教程 - 笔下光年
网站首页
PHP 错误处理
In this tutorial you will learn how to use the PHP's error handling functions to deal with the error conditions gracefully. ## Handling Errors Sometimes your application will not run as it supposed to do, resulting in an error. There are a number of reasons that may cause errors, for example: - The Web server might run out of disk space - A user might have entered an invalid value in a form field - The file or database record that you were trying to access may not exist - The application might not have permission to write to a file on the disk - A service that the application needs to access might be temporarily unavailable These types of errors are known as runtime errors, because they occur at the time the script runs. They are distinct from syntax errors that need to be fixed before the script will run. A professional application must have the capabilities to handle such runtime error gracefully. Usually this means informing the user about the problem more clearly and precisely. ## Understanding Error Levels Usually, when there's a problem that prevents a script from running properly, the PHP engine triggers an error. Each error is represented by an integer value and an associated constant. The following table list some of the common error levels: | Error Level | Value | Description | |----------------|-------|--------------------------------------| | E_ERROR | 1 | A fatal run-time error, that can't be recovered from. The execution of the script is stopped immediately. | | E_WARNING | 2 | A run-time warning. It is non-fatal and most errors tend to fall into this category. The execution of the script is not stopped. | | E_NOTICE | 8 | A run-time notice. Indicate that the script encountered something that could possibly an error, although the situation could also occur when running a script normally. | | E_USER_ERROR | 256 | A fatal user-generated error message. This is like an E_ERROR, except it is generated by the PHP script using the function trigger_error() rather than the PHP engine. | | E_USER_WARNING | 512 | A non-fatal user-generated warning message. This is like an E_WARNING, except it is generated by the PHP script using the function trigger_error() rather than the PHP. engine | | E_USER_NOTICE | 1024 | A user-generated notice message. This is like an E_NOTICE, except it is generated by the PHP script using the function trigger_error() rather than the PHP engine. | | E_STRICT | 2048 | Not strictly an error, but triggered whenever PHP encounters code that could lead to problems or forward incompatibilities | | E_ALL | 8191 | All errors and warnings, except of E_STRICT prior to PHP 5.4.0. | For more error levels, please check out the reference on [PHP Error Levels](http://www.bixiaguangnian.com/manual/php7/4024.html "PHP Error Levels"). The PHP engine triggers an error whenever it encounters a problem with your script, but you can also trigger errors yourself to generate more user friendly error messages. This way you can make your application more sofisticated. The following section describes some of common methods used for handling errors in PHP: ## Basic Error Handling Using the die() Function Consider the following example that simply tries to open a text file for reading only. ```php <?php // Try to open a non-existent file $file = fopen("sample.txt", "r"); ?> ``` If the file does not exist you might get an error like this: ``` Warning: fopen(sample.txt) [function.fopen]: failed to open stream: No such file or directory in C:\wamp\www\project\test.php on line 2 ``` If we follow some simple steps we can prevent the users from getting such error message. ```php <?php if(file_exists("sample.txt")){ $file = fopen("sample.txt", "r"); } else{ die("Error: The file you are trying to access doesn't exist."); } ?> ``` Now if you run the above script you will get the error message like this: ``` Error: The file you are trying to access doesn't exist. ``` As you can see by implementing a simple check whether the file exist or not before trying to access it, we can generate an error message that is more meaningful to the user. The `die()` function used above simply display the custom error message and terminate the current script if 'sample.txt' file is not found. ## Creating a Custom Error Handler You can create your own error handler function to deal with the run-time error generated by PHP engine. The custom error handler provides you greater flexibility and better control over the errors, it can inspect the error and decide what to do with the error, it might display a message to the user, log the error in a file or database or send by e-mail, attempt to fix the problem and carry on, exit the execution of the script or ignore the error altogether. The custom error handler function must be able to handle at least two parameters (errno and errstr), however it can optionally accept an additional three parameters (errfile, errline, and errcontext), as described below: <table><tbody><tr><th style="width: 90px;">Parameter</th><th>Description</th></tr><tr><td class="bg-dark"colspan="2"><strong>Required</strong>—The following parameters are required</td></tr><tr><td>errno</td><td>Specifies the level of the error,as an integer.This corresponds to the appropriate error level constant(<code>E_ERROR</code>,<code>E_WARNING</code>,and so on)</td></tr><tr><td>errstr</td><td>Specifies the error message as a string</td></tr><tr><td class="bg-dark"colspan="2"><strong>Optional</strong>—The following parameters are optional</td></tr><tr><td>errfile</td><td>Specifies the filename of the script file in which the error occurred,as a string</td></tr><tr><td>errline</td><td>Specifies the line number on which the error occurred,as a string</td></tr><tr><td>errcontext</td><td>Specifies an array containing all the variables and their values that existed at the time the error occurred.Useful for debugging</td></tr></tbody></table> Here's an example of a simple custom error handling function. This handler, `customError()` is triggered whenever an error occurred, no matter how trivial. It then outputs the details of the error to the browser and stops the execution of the script. ```php <?php // Error handler function function customError($errno, $errstr){ echo "<b>Error:</b> [$errno] $errstr"; } ?> ``` You need to tell the PHP to use your custom error handler function — just call the built-in `set_error_handler()` function, passing in the name of the function. ```php <?php // Error handler function function customError($errno, $errstr){ echo "<b>Error:</b> [$errno] $errstr"; } // Set error handler set_error_handler("customError"); // Trigger error echo($test); ?> ``` ## Error Logging ### Log Error Messages in a Text File You can also logs details of the error to the log file, like this: ```php <?php function calcDivision($dividend, $divisor){ if($divisor == 0){ trigger_error("calcDivision(): The divisor cannot be zero", E_USER_WARNING); return false; } else{ return($dividend / $divisor); } } function customError($errno, $errstr, $errfile, $errline, $errcontext){ $message = date("Y-m-d H:i:s - "); $message .= "Error: [" . $errno ."], " . "$errstr in $errfile on line $errline, "; $message .= "Variables:" . print_r($errcontext, true) . "\r\n"; error_log($message, 3, "logs/app_errors.log"); die("There was a problem, please try again."); } set_error_handler("customError"); echo calcDivision(10, 0); echo "This will never be printed."; ?> ``` ### Send Error Messages by E-Mail You can also send e-mail with the error details using the same `error_log()` function. ```php <?php function calcDivision($dividend, $divisor){ if ($divisor == 0){ trigger_error("calcDivision(): The divisor cannot be zero", E_USER_WARNING); return false; } else{ return($dividend / $divisor); } } function customError($errno, $errstr, $errfile, $errline, $errcontext){ $message = date("Y-m-d H:i:s - "); $message .= "Error: [" . $errno ."], " . "$errstr in $errfile on line $errline, "; $message .= "Variables:" . print_r($errcontext, true) . "\r\n"; error_log($message, 1, "webmaster@example.com"); die("There was a problem, please try again. Error report submitted to webmaster."); } set_error_handler("customError"); echo calcDivision(10, 0); echo "This will never be printed."; ?> ``` ## Trigger an Error Although the PHP engine triggers an error whenever it encounters a problem with your script, however you can also trigger errors yourself. This can help to make your application more robust, because it can flag potential problems before they turn into serious errors. To trigger an error from within your script, call the `trigger_error()` function, passing in the error message that you want to generate: ```php trigger_error("There was a problem."); ``` Consider the following function that calculates division of the two numbers. ```php <?php function calcDivision($dividend, $divisor){ return($dividend / $divisor); } // Calling the function echo calcDivision(10, 0); ?> ``` If a value of zero (0) is passed as the `$divisor` parameter, the error generated by the PHP engine will look something like this: ``` Warning: Division by zero in C:\wamp\www\project\test.php on line 3 ``` This message doesn't look very informative. Consider the following example that uses the `trigger_error()` function to generate the error. ```php <?php function calcDivision($dividend, $divisor){ if($divisor == 0){ trigger_error("The divisor cannot be zero", E_USER_WARNING); return false; } else{ return($dividend / $divisor); } } // Calling the function echo calcDivision(10, 0); ?> ``` Now the script generates this error message: ``` Warning: The divisor cannot be zero in C:\wamp\www\project\error.php on line 4 ``` As you can see the error message generated by the second example explains the problem more clearly as compared to the previous one.
上一篇:
PHP 过滤器
下一篇:
PHP 类和对象