php error handling, php error_PHP tutorial
Jul 12, 2016 am 08:52 AMphp error handling, php errors
In PHP, the default error handling is 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 the 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)
參數(shù) | 描述 |
---|---|
error_level | 必需。為用戶定義的錯誤規(guī)定錯誤報(bào)告級別。必須是一個數(shù)字。參見下面的表格:錯誤報(bào)告級別。 |
error_message | 必需。為用戶定義的錯誤規(guī)定錯誤消息。 |
error_file | 可選。規(guī)定錯誤發(fā)生的文件名。 |
error_line | 可選。規(guī)定錯誤發(fā)生的行號。 |
error_context | 可選。規(guī)定一個數(shù)組,包含了當(dāng)錯誤發(fā)生時在用的每個變量以及它們的值。 |
Error reporting level
These error reporting levels are different types of errors handled by user-defined error handlers:
值 | 常量 | 描述 |
---|---|---|
2 | E_WARNING | 非致命的 run-time 錯誤。不暫停腳本執(zhí)行。 |
8 | E_NOTICE | run-time 通知。在腳本發(fā)現(xiàn)可能有錯誤時發(fā)生,但也可能在腳本正常運(yùn)行時發(fā)生。 |
256 | E_USER_ERROR | 致命的用戶生成的錯誤。這類似于程序員使用 PHP 函數(shù) trigger_error() 設(shè)置的 E_ERROR。 |
512 | E_USER_WARNING | 非致命的用戶生成的警告。這類似于程序員使用 PHP 函數(shù) trigger_error() 設(shè)置的 E_WARNING。 |
1024 | E_USER_NOTICE | 用戶生成的通知。這類似于程序員使用 PHP 函數(shù) trigger_error() 設(shè)置的 E_NOTICE。 |
4096 | E_RECOVERABLE_ERROR | 可捕獲的致命錯誤。類似 E_ERROR,但可被用戶定義的處理程序捕獲。(參見 set_error_handler()) |
8191 | E_ALL | 所有錯誤和警告。(在 PHP 5.4 中,E_STRICT 成為 E_ALL 的一部分) |
現(xiàn)在,讓我們創(chuàng)建一個處理錯誤的函數(shù):
function customError($errno, $errstr) { echo "<b>Error:</b> [$errno] $errstr<br>"; echo "Ending Script"; die(); }
上面的代碼是一個簡單的錯誤處理函數(shù)。當(dāng)它被觸發(fā)時,它會取得錯誤級別和錯誤消息。然后它會輸出錯誤級別和消息,并終止腳本。
現(xiàn)在,我們已經(jīng)創(chuàng)建了一個錯誤處理函數(shù),我們需要確定在何時觸發(fā)該函數(shù)。
設(shè)置錯誤處理程序
PHP 的默認(rèn)錯誤處理程序是內(nèi)建的錯誤處理程序。我們打算把上面的函數(shù)改造為腳本運(yùn)行期間的默認(rèn)錯誤處理程序。
可以修改錯誤處理程序,使其僅應(yīng)用到某些錯誤,這樣腳本就能以不同的方式來處理不同的錯誤。然而,在本例中,我們打算針對所有錯誤來使用我們自定義的錯誤處理程序:
set_error_handler("customError");
由于我們希望我們的自定義函數(shù)能處理所有錯誤,set_error_handler() 僅需要一個參數(shù),可以添加第二個參數(shù)來規(guī)定錯誤級別。
實(shí)例
通過嘗試輸出不存在的變量,來測試這個錯誤處理程序:
Error: [$errno] $errstr"; } //set error handler set_error_handler("customError"); //trigger error echo($test); ?>
以上代碼的輸出如下所示:
Error: [8] Undefined variable: test
觸發(fā)錯誤
在腳本中用戶輸入數(shù)據(jù)的位置,當(dāng)用戶的輸入無效時觸發(fā)錯誤是很有用的。在 PHP 中,這個任務(wù)由 trigger_error() 函數(shù)完成。
實(shí)例
在本例中,如果 "test" 變量大于 "1",就會發(fā)生錯誤:
<?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ā)錯誤,通過添加的第二個參數(shù),您能夠規(guī)定所觸發(fā)的錯誤級別。
可能的錯誤類型:
- E_USER_ERROR - 致命的用戶生成的 run-time 錯誤。錯誤無法恢復(fù)。腳本執(zhí)行被中斷。
- E_USER_WARNING - 非致命的用戶生成的 run-time 警告。腳本執(zhí)行不被中斷。
- E_USER_NOTICE - 默認(rèn)。用戶生成的 run-time 通知。在腳本發(fā)現(xiàn)可能有錯誤時發(fā)生,但也可能在腳本正常運(yùn)行時發(fā)生。
在本例中,如果 "test" 變量大于 "1",則發(fā)生 E_USER_WARNING 錯誤。如果發(fā)生了 E_USER_WARNING,我們將使用我們自定義的錯誤處理程序并結(jié)束腳本:
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ā)它們,接下來我們研究一下錯誤記錄。
錯誤記錄
在默認(rèn)的情況下,根據(jù)在 php.ini 中的 error_log 配置,PHP 向服務(wù)器的記錄系統(tǒng)或文件發(fā)送錯誤記錄。通過使用 error_log() 函數(shù),您可以向指定的文件或遠(yuǎn)程目的地發(fā)送錯誤記錄。
通過電子郵件向您自己發(fā)送錯誤消息,是一種獲得指定錯誤的通知的好辦法。
通過 E-Mail 發(fā)送錯誤消息
在下面的例子中,如果特定的錯誤發(fā)生,我們將發(fā)送帶有錯誤消息的電子郵件,并結(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
這個方法不適合所有的錯誤。常規(guī)錯誤應(yīng)當(dāng)通過使用默認(rèn)的 PHP 記錄系統(tǒng)在服務(wù)器上進(jìn)行記錄。
?
原文地址:http://www.manongjc.com/php/php_error.html
php相關(guān)閱讀資料:

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

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

InPHP,variablesarepassedbyvaluebydefault,meaningfunctionsorassignmentsreceiveacopyofthedata,whilepassingbyreferenceallowsmodificationstoaffecttheoriginalvariable.1.Whenpassingbyvalue,changestothecopydonotimpacttheoriginal,asshownwhenassigning$b=$aorp

The reason why header('Location:...') in AJAX request is invalid is that the browser will not automatically perform page redirects. Because in the AJAX request, the 302 status code and Location header information returned by the server will be processed as response data, rather than triggering the jump behavior. Solutions are: 1. Return JSON data in PHP and include a jump URL; 2. Check the redirect field in the front-end AJAX callback and jump manually with window.location.href; 3. Ensure that the PHP output is only JSON to avoid parsing failure; 4. To deal with cross-domain problems, you need to set appropriate CORS headers; 5. To prevent cache interference, you can add a timestamp or set cache:f

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

The most direct way to find the last occurrence of a substring in PHP is to use the strrpos() function. 1. Use strrpos() function to directly obtain the index of the last occurrence of the substring in the main string. If it is not found, it returns false. The syntax is strrpos($haystack,$needle,$offset=0). 2. If you need to ignore case, you can use the strripos() function to implement case-insensitive search. 3. For multi-byte characters such as Chinese, the mb_strrpos() function in the mbstring extension should be used to ensure that the character position is returned instead of the byte position. 4. Note that strrpos() returns f

To prevent session hijacking in PHP, the following measures need to be taken: 1. Use HTTPS to encrypt the transmission and set session.cookie_secure=1 in php.ini; 2. Set the security cookie attributes, including httponly, secure and samesite; 3. Call session_regenerate_id(true) when the user logs in or permissions change to change to change the SessionID; 4. Limit the Session life cycle, reasonably configure gc_maxlifetime and record the user's activity time; 5. Prohibit exposing the SessionID to the URL, and set session.use_only

In PHP, you can use square brackets or curly braces to obtain string specific index characters, but square brackets are recommended; the index starts from 0, and the access outside the range returns a null value and cannot be assigned a value; mb_substr is required to handle multi-byte characters. For example: $str="hello";echo$str[0]; output h; and Chinese characters such as mb_substr($str,1,1) need to obtain the correct result; in actual applications, the length of the string should be checked before looping, dynamic strings need to be verified for validity, and multilingual projects recommend using multi-byte security functions uniformly.

You can use substr() or mb_substr() to get the first N characters in PHP. The specific steps are as follows: 1. Use substr($string,0,N) to intercept the first N characters, which is suitable for ASCII characters and is simple and efficient; 2. When processing multi-byte characters (such as Chinese), mb_substr($string,0,N,'UTF-8'), and ensure that mbstring extension is enabled; 3. If the string contains HTML or whitespace characters, you should first use strip_tags() to remove the tags and trim() to clean the spaces, and then intercept them to ensure the results are clean.
