PHP error handling function, php error function_PHP tutorial
Jul 12, 2016 am 08:55 AMPHP error handling function, php error function
In PHP, the default error handling is very simple. An error message is sent to the browser with the file name, line number, and a message describing the error.
PHP error handling
Error handling is an important part when creating scripts and web applications. If your code lacks error detection coding, the program will look unprofessional and open the door to security risks.
This tutorial covers some of the most important error detection methods in PHP.
We will explain different error handling methods for you:
Simple "die()" statement
Custom errors and error triggers
Bug Report
Basic error handling: use die() function
The first example shows a simple script to open a text file:
<?php $file=fopen("welcome.txt","r"); ?>
If the file does not exist, you will get an error like this:
Warning: fopen(welcome.txt) [function.fopen]: failed to open stream:
No such file or directory in C:webfoldertest.php on line 2
To avoid users getting error messages like the one above, we check whether the file exists before accessing it:
<?php if(!file_exists("welcome.txt")) { die("File not found"); } else { $file=fopen("welcome.txt","r"); } ?>
Now, if the file does not exist, you will get an error message like this:
File not found
The above code is more efficient than the previous code because it uses a simple error handling mechanism to terminate the script after an error.
However, simply terminating the script is not always the appropriate approach. Let's examine alternative PHP functions for handling errors.
Create a custom error handler
Creating a custom error handler is very easy. We simply created a dedicated function that can be called when an error occurs in PHP.
The function must be able to handle at least two parameters (error level and error message), but can accept up to five parameters (optional: file, line-number and error context):
Grammar
error_function(error_level,error_message,error_file,error_line,error_context)
Parameters | Description |
---|---|
error_level | Required. Specifies the error reporting level for user-defined errors. Must be a number. See the table below: Error reporting levels. |
error_message | Required. Specifies error messages for user-defined errors. |
error_file | Optional. Specifies the file name where the error occurred. |
error_line | Optional. Specifies the line number where the error occurred. |
error_context | Optional.Specifies an array containing each variable in use when the error occurred and their values. |
錯(cuò)誤報(bào)告級(jí)別
這些錯(cuò)誤報(bào)告級(jí)別是用戶自定義的錯(cuò)誤處理程序處理的不同類型的錯(cuò)誤:
現(xiàn)在,讓我們創(chuàng)建一個(gè)處理錯(cuò)誤的函數(shù):
function customError($errno, $errstr) { echo "<b>Error:</b> [$errno] $errstr<br>"; echo "Ending Script"; die(); }
上面的代碼是一個(gè)簡(jiǎn)單的錯(cuò)誤處理函數(shù)。當(dāng)它被觸發(fā)時(shí),它會(huì)取得錯(cuò)誤級(jí)別和錯(cuò)誤消息。然后它會(huì)輸出錯(cuò)誤級(jí)別和消息,并終止腳本。
現(xiàn)在,我們已經(jīng)創(chuàng)建了一個(gè)錯(cuò)誤處理函數(shù),我們需要確定在何時(shí)觸發(fā)該函數(shù)。
Value | Constant | Description |
---|---|---|
2 | E_WARNING | Non-fatal run-time error. Do not pause script execution. |
8 | E_NOTICE | run-time notification. Occurs when the script finds a possible error, but can also occur when the script is running normally. |
256 | E_USER_ERROR | Fatal user-generated error. This is similar to E_ERROR set by the programmer using the PHP function trigger_error(). |
512 | E_USER_WARNING | Non-fatal user-generated warning. This is similar to the E_WARNING set by the programmer using the PHP function trigger_error(). |
1024 | E_USER_NOTICE | User generated notifications. This is similar to E_NOTICE set by the programmer using the PHP function trigger_error(). |
4096 | E_RECOVERABLE_ERROR | Catchable fatal errors. Like E_ERROR, but can be caught by a user-defined handler. (see set_error_handler()) |
8191 | E_ALL | All errors and warnings. (E_STRICT becomes part of E_ALL in PHP 5.4) |
設(shè)置錯(cuò)誤處理程序
PHP 的默認(rèn)錯(cuò)誤處理程序是內(nèi)建的錯(cuò)誤處理程序。我們打算把上面的函數(shù)改造為腳本運(yùn)行期間的默認(rèn)錯(cuò)誤處理程序。
可以修改錯(cuò)誤處理程序,使其僅應(yīng)用到某些錯(cuò)誤,這樣腳本就能以不同的方式來(lái)處理不同的錯(cuò)誤。然而,在本例中,我們打算針對(duì)所有錯(cuò)誤來(lái)使用我們自定義的錯(cuò)誤處理程序:
set_error_handler("customError");
由于我們希望我們的自定義函數(shù)能處理所有錯(cuò)誤,set_error_handler() 僅需要一個(gè)參數(shù),可以添加第二個(gè)參數(shù)來(lái)規(guī)定錯(cuò)誤級(jí)別。
實(shí)例
通過(guò)嘗試輸出不存在的變量,來(lái)測(cè)試這個(gè)錯(cuò)誤處理程序:
<?php //error handler function function customError($errno, $errstr) { echo "Error: [$errno] $errstr"; } //set error handler set_error_handler("customError"); //trigger error echo($test); ?>
以上代碼的輸出如下所示:
Error: [8] Undefined variable: test
觸發(fā)錯(cuò)誤
在腳本中用戶輸入數(shù)據(jù)的位置,當(dāng)用戶的輸入無(wú)效時(shí)觸發(fā)錯(cuò)誤是很有用的。在 PHP 中,這個(gè)任務(wù)由 trigger_error() 函數(shù)完成。
實(shí)例
在本例中,如果 "test" 變量大于 "1",就會(huì)發(fā)生錯(cuò)誤:
<?php $test=2; if ($test>1) { trigger_error("Value must be 1 or below"); } ?>
以上代碼的輸出如下所示:
Notice: Value must be 1 or below
in C:webfoldertest.php on line 6
您可以在腳本中任何位置觸發(fā)錯(cuò)誤,通過(guò)添加的第二個(gè)參數(shù),您能夠規(guī)定所觸發(fā)的錯(cuò)誤級(jí)別。
可能的錯(cuò)誤類型:
E_USER_ERROR - 致命的用戶生成的 run-time 錯(cuò)誤。錯(cuò)誤無(wú)法恢復(fù)。腳本執(zhí)行被中斷。
E_USER_WARNING - 非致命的用戶生成的 run-time 警告。腳本執(zhí)行不被中斷。
E_USER_NOTICE - 默認(rèn)。用戶生成的 run-time 通知。在腳本發(fā)現(xiàn)可能有錯(cuò)誤時(shí)發(fā)生,但也可能在腳本正常運(yùn)行時(shí)發(fā)生。
在本例中,如果 "test" 變量大于 "1",則發(fā)生 E_USER_WARNING 錯(cuò)誤。如果發(fā)生了 E_USER_WARNING,我們將使用我們自定義的錯(cuò)誤處理程序并結(jié)束腳本:
<?php //error handler function function customError($errno, $errstr) { echo "<b>Error:</b> [$errno] $errstr<br>"; echo "Ending Script"; die(); } //set error handler set_error_handler("customError",E_USER_WARNING); //trigger error $test=2; if ($test>1) { trigger_error("Value must be 1 or below",E_USER_WARNING); } ?>
以上代碼的輸出如下所示:
Error: [512] Value must be 1 or below
Ending Script
現(xiàn)在,我們已經(jīng)學(xué)習(xí)了如何創(chuàng)建自己的 error,以及如何觸發(fā)它們,接下來(lái)我們研究一下錯(cuò)誤記錄。
錯(cuò)誤記錄
在默認(rèn)的情況下,根據(jù)在 php.ini 中的 error_log 配置,PHP 向服務(wù)器的記錄系統(tǒng)或文件發(fā)送錯(cuò)誤記錄。通過(guò)使用 error_log() 函數(shù),您可以向指定的文件或遠(yuǎn)程目的地發(fā)送錯(cuò)誤記錄。
通過(guò)電子郵件向您自己發(fā)送錯(cuò)誤消息,是一種獲得指定錯(cuò)誤的通知的好辦法。
通過(guò) E-Mail 發(fā)送錯(cuò)誤消息
在下面的例子中,如果特定的錯(cuò)誤發(fā)生,我們將發(fā)送帶有錯(cuò)誤消息的電子郵件,并結(jié)束腳本:
<?php //error handler function function customError($errno, $errstr) { echo "<b>Error:</b> [$errno] $errstr<br>"; echo "Webmaster has been notified"; error_log("Error: [$errno] $errstr",1, "someone@example.com","From: webmaster@example.com"); } //set error handler set_error_handler("customError",E_USER_WARNING); //trigger error $test=2; if ($test>1) { trigger_error("Value must be 1 or below",E_USER_WARNING); } ?>
以上代碼的輸出如下所示:
Error: [512] Value must be 1 or below
Webmaster has been notified
接收自以上代碼的郵件如下所示:
Error: [512] Value must be 1 or below
這個(gè)方法不適合所有的錯(cuò)誤。常規(guī)錯(cuò)誤應(yīng)當(dāng)通過(guò)使用默認(rèn)的 PHP 記錄系統(tǒng)在服務(wù)器上進(jìn)行記錄。
以上內(nèi)容是小編給大家介紹的PHP錯(cuò)誤處理函數(shù),希望對(duì)大家以上幫助!
您可能感興趣的文章:
- PHP 自定義錯(cuò)誤處理函數(shù)的使用詳解
- PHP 自定義錯(cuò)誤處理函數(shù)trigger_error()
- php一些錯(cuò)誤處理的方法與技巧總結(jié)
- PHP 的異常處理、錯(cuò)誤的拋出及回調(diào)函數(shù)等面向?qū)ο蟮腻e(cuò)誤處理方法
- PHP中的錯(cuò)誤處理、異常處理機(jī)制分析
- php 錯(cuò)誤處理經(jīng)驗(yàn)分享
- PHP中PDO的錯(cuò)誤處理
- 使用PHP的錯(cuò)誤處理

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The method to get the current session ID in PHP is to use the session_id() function, but you must call session_start() to successfully obtain it. 1. Call session_start() to start the session; 2. Use session_id() to read the session ID and output a string similar to abc123def456ghi789; 3. If the return is empty, check whether session_start() is missing, whether the user accesses for the first time, or whether the session is destroyed; 4. The session ID can be used for logging, security verification and cross-request communication, but security needs to be paid attention to. Make sure that the session is correctly enabled and the ID can be obtained successfully.

To extract substrings from PHP strings, you can use the substr() function, which is syntax substr(string$string,int$start,?int$length=null), and if the length is not specified, it will be intercepted to the end; when processing multi-byte characters such as Chinese, you should use the mb_substr() function to avoid garbled code; if you need to intercept the string according to a specific separator, you can use exploit() or combine strpos() and substr() to implement it, such as extracting file name extensions or domain names.

UnittestinginPHPinvolvesverifyingindividualcodeunitslikefunctionsormethodstocatchbugsearlyandensurereliablerefactoring.1)SetupPHPUnitviaComposer,createatestdirectory,andconfigureautoloadandphpunit.xml.2)Writetestcasesfollowingthearrange-act-assertpat

In PHP, the most common method is to split the string into an array using the exploit() function. This function divides the string into multiple parts through the specified delimiter and returns an array. The syntax is exploit(separator, string, limit), where separator is the separator, string is the original string, and limit is an optional parameter to control the maximum number of segments. For example $str="apple,banana,orange";$arr=explode(",",$str); The result is ["apple","bana

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

In PHP, to pass a session variable to another page, the key is to start the session correctly and use the same $_SESSION key name. 1. Before using session variables for each page, it must be called session_start() and placed in the front of the script; 2. Set session variables such as $_SESSION['username']='JohnDoe' on the first page; 3. After calling session_start() on another page, access the variables through the same key name; 4. Make sure that session_start() is called on each page, avoid outputting content in advance, and check that the session storage path on the server is writable; 5. Use ses

When encountering the problem that header('Location:...') does not work, the common reasons and solutions are as follows: 1. There is output in advance, causing the header to fail. The solution is to ensure that there is no output before the jump, including spaces, HTML or echo; 2. There is excess output or UTF-8 BOM characters in the include or require file. The file encoding should be checked and saved as "UTF-8 BOM-free"; 3. It is recommended to use ob_start() to turn on the output buffer before the jump, and cooperate with ob_end_flush() to delay the output; 4. After the jump, be sure to add exit to prevent subsequent code execution; 5. Make sure that the header() function call is before all outputs.
