Summary of usage of set_error_handler in php
The set_error_handler() function sets a user-defined error handling function. This function is used to create the user's own error handling method during runtime. This function returns the old error handler, or null on failure. Let’s look at some examples.
set_error_handler()
PHP has provided a custom error handling handle function set_error_handler() since 4.1.0, but few script writers know it. The set_error_handler function can prevent error paths from being leaked, and of course it has other functions.
1. Can be used to block errors. If an error occurs, some information will be exposed to users, and it is very likely to become a tool for hackers to attack your website. Second, it makes users feel that your level is very low.
2. You can write down error information and discover some problems in the production environment in a timely manner.
3. Corresponding processing can be done. When an error occurs, a jump to a predefined error page can be displayed to provide a better user experience.
4. It can be used as a debugging tool. Sometimes you have to debug something in the production environment, but you don’t want to affect the users who are using it.
5. . . .
The usage of set_error_handler is as follows:
view sourceprint?1 string set_error_handler ( callback error_handler [, int error_types])
The error message we see using error_reporting(); includes three parts, the error message, the absolute address of the error file, and the number of lines where the error occurred. In fact, there is another type of error. Array ( [type] => 1 [message] => Call to undefined method SomeClass::somemedthod() [file] => /home/zhangy/www/aaaa/stasdf.php [line] => 67 ), it is best not to expose the absolute path of the page to others, otherwise it will give some people an opportunity to complain. In order to prevent this, many people will use ini_set("display_errors",0); to directly block the error message. This is inconvenient. What if we want to read the information? Do I need to change the code every time I check it, or change the configuration of apache and restart it?
PHP has the function set_error_handler to solve this problem
Usage is as follows:
mixed set_error_handler ( callback $error_handler [, int $error_types = E_ALL | E_STRICT ] )
The php function register_shutdown_function can also solve this problem
Usage is as follows:
int register_shutdown_function ( string $func )
Personally, I feel that defining the error reporting function by yourself has at least three advantages,
1. The absolute path of the file will not be displayed, which is safer
2. Even if an error message does appear, we can process the error message so that users cannot see such things as fatal errors. Better user experience
3. After the project goes online, sometimes you still have to help users solve problems. At this time, it is inevitable to modify the code, but we also want the error message to be reported and not allowed to be seen by users. At this time, use set_error_handler like this The function is very cool.
I did a small test
error_reporting(0);
register_shutdown_function('error_alert');
function error_alert()
{
if(is_null($e = error_get_last()) === false)
{
set_error_handler('errorHandler');
if($e['type'] == 1){
trigger_error("fatal error", E_USER_ERROR);
}elseif($e['type'] == 8){
trigger_error("notice", E_USER_NOTICE);
}elseif($e['type'] == 2){
trigger_error("warning", E_USER_WARNING);
}else{
trigger_error("other", E_USER_OTHER);
}
}else{
echo "no error";
}
}
set_error_handler('errorHandler');
function errorHandler($errno, $errstr, $errfile, $errline,$errcontext)
{
switch ($errno) {
case E_USER_ERROR:
echo "My ERROR [$errno] $errstr
n";
echo " Fatal error on line $errline in file $errfile";
echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")
n";
break;
case E_USER_WARNING:
echo "My WARNING [$errno] $errstr
n";
echo " warning on line $errline in file $errfile";
echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")
n";
break;
case E_USER_NOTICE:
echo "My NOTICE [$errno] $errstr
n";
echo " notice on line $errline in file $errfile";
echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")
n";
break;
default:
echo "Unknown error type: [$errno] $errstr
n";
echo " warning on line $errline in file $errfile";
echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")
n";
break;
}
return true;
}
class SomeClass {
public function someMethod() {
}
}
SomeClass::someMedthod();
$a="asdf";
foreach($a as $d){
echo $d;
}
?>
Now we use custom error handling to filter out the actual paths. Suppose there is a variable $admin, which we use to determine whether the visitor is an administrator (this determination can be made by IP or logged in user ID)
//Admin is the identity determination of the administrator, true is the administrator.
//The custom error handling function must have these four input variables $errno, $errstr, $errfile, $errline, otherwise it will be invalid.
function my_error_handler($errno,$errstr,$errfile,$errline)
{
//If you are not an administrator, filter the actual path
If(!admin)
{
$errfile=str_replace(getcwd(),"",$errfile);
$errstr=str_replace(getcwd(),"",$errstr);
}
switch($errno)
{
case E_ERROR:
echo "ERROR: [ID $errno] $errstr (Line: $errline of $errfile) n";
echo "The program has stopped running, please contact the administrator.";
//Exit the script when encountering an Error level error
exit;
break;
case E_WARNING:
echo "WARNING: [ID $errno] $errstr (Line: $errline of $errfile) n";
break;
default:
//Do not display Notice level errors
break;
}
}
In this way, an error handling function is customized, so how to hand over error handling to this custom function?
// Apply to class
set_error_handler(array(&$this,"appError"));
//Example method
set_error_handler("my_error_handler");
So easy, in this way, the contradiction between security and debugging convenience can be well solved. And you can also put some thought into making the error message more beautiful to match the style of the website.
In the above example, I turned off the error message and used my own function to handle the error. The page above will report a fatal error. We can use errorHandler to control and handle the reported error message.
Okay, to summarize, here are three uses of set_error_handler:
Php code
class CallbackClass {
function CallbackFunction() {
// refers to $this
}
function StaticFunction() {
// doesn’t refer to $this
}
}
function NonClassFunction($errno, $errstr, $errfile, $errline) {
}
//The three methods are as follows:
1: set_error_handler(‘NonClassFunction’); // Go directly to a normal function NonClassFunction
2: set_error_handler(array(‘CallbackClass’, ‘StaticFunction’)); // Go to the static method StaticFunction
under the CallbackClass class
3: $o =& new CallbackClass();
set_error_handler(array($o, ‘CallbackFunction’)); // Go to the constructor of the class, which is essentially the same as the fourth item below.
4. $o = new CallbackClass();
// The following may also prove useful:
class CallbackClass {
function CallbackClass() {
set_error_handler(array(&$this, ‘CallbackFunction’)); // the & is important
}
function CallbackFunction() {
// refers to $this
}
}

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\ \;||\xc2\xa0)/","其他字符",$str)”语句。

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

在PHP中,可以利用implode()函数的第一个参数来设置没有分隔符,该函数的第一个参数用于规定数组元素之间放置的内容,默认是空字符串,也可将第一个参数设置为空,语法为“implode(数组)”或者“implode("",数组)”。


Hot AI Tools

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

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

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

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

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1
Powerful PHP integrated development environment
