search
Homephp教程php手册PHP set_error_handler()函数使用详解(示例)

我们写程序,难免会有问题(是经常会遇到问题 ),而PHP遇到错误时,就会给出出错脚本的位置、行数和原因。有很多人说,这并没有什么大不了。确实,在调试程序阶段,这确实是没啥的,而且我认为给出错误路径是必要的。
但泄露了实际路径的后果是不堪设想的,对于某些入侵者,这个信息可是非常重要,而事实上现在有很多的服务器都存在这个问题。有些网管干脆把PHP配置文件中的display_errors设置为Off来解决(貌似我们就是这样做的),但本人认为这个方法过于消极。
有些时候,我们的确需要PHP返回错误的信息以便调试。而且在出错时也可能需要给用户一个交待,甚至导航到另一页面。那么,有啥解决办法呢?
set_error_handler()
PHP从4.1.0开始提供了自定义错误处理句柄的功能函数set_error_handler(),但很少数脚本编写者知道。set_error_handler这个函数可以很好地防止错误路径泄露,当然还有其它更多的作用。
可以用来屏蔽错误。 出现错误一来会把一些信息暴漏给用户,极有可能成为黑客攻击你网站的工具。 二来让用户觉得你的水平很挫。
可以记下错误的信息, 及时发现一些生产环境的出现的问题。
可以做相应的处理, 出错的时候可以显示跳转到预先定义好的出错页面,提供更好的用户体验。
可以作为调试工具, 一些时候必须在生产环境调试一些东西, 但又不想影响正在使用的用户。
set_error_handler的使用方法如下:

复制代码 代码如下:


string set_error_handler ( callback error_handler [, int error_types])


现在我们就用自定义的错误处理把实际路径过滤掉。假设有一个变量$admin,我们是用来判断访问者是否是管理员的(可以通过IP或者登录的用户id来做这个判断)

复制代码 代码如下:


//admin为管理员的身份判定,true为管理员。 
//自定义的错误处理函数一定要有这4个输入变量$errno,$errstr,$errfile,$errline,否则无效。 
function my_error_handler($errno,$errstr,$errfile,$errline) 

    //如果不是管理员就过滤实际路径 
    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 "程序已经停止运行,请联系管理员。"; 
        //遇到Error级错误时退出脚本 
        exit; 
        break; 

        case E_WARNING: 
        echo "WARNING: [ID $errno] $errstr (Line: $errline of $errfile) \n"; 
        break; 

        default: 
        //不显示Notice级的错误 
        break; 
    } 


这样就自定义了一个错误处理函数,那么怎么把错误的处理交给这个自定义函数呢?

复制代码 代码如下:


// 应用到类 
set_error_handler(array(&$this,"appError")); 

//示例的做法 
set_error_handler("my_error_handler"); 


so easy,这样,就可以很好地解决安全和调试方便的矛盾了。而且你还可以花点心思,使错误提示更加美观以配合网站的风格。
原作者给出了两点需要注意的地方,我也放出来吧,希望引起广大同胞们的注意:
1、E_ERROR、E_PARSE、E_CORE_ERROR、E_CORE_WARNING、 E_COMPILE_ERROR、E_COMPILE_WARNING是不会被这个句柄处理的,也就是会用最原始的方式显示出来。不过出现这些错误都是编 译或PHP内核出错,在通常情况下不会发生。
2、使用set_error_handler()后,error_reporting ()将会失效。也就是所有的错误(除上述的错误)都会交给自定义的函数处理。
最后,出一个示例

复制代码 代码如下:


//先定义一个函数,也可以定义在其他的文件中,再用require()调用 
function myErrorHandler($errno, $errstr, $errfile, $errline) 

     //为了安全起见,不暴露出真实物理路径,下面两行过滤实际路径 
    $errfile=str_replace(getcwd(),"",$errfile); 
    $errstr=str_replace(getcwd(),"",$errstr); 

    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"; 
        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 "Unknown error type: [$errno] $errstr
\n"; 
        break; 
    } 

    /* Don't execute PHP internal error handler */ 
    return true; 


//下面开始连接MYSQL服务器,我们故意指定MYSQL端口为3333,实际为3306。 
$link_id=@mysql_pconnect("localhost:3333","root","password"); 
set_error_handler(myErrorHandler); 
if (!$link_id) { 
    trigger_error("出错了", E_USER_ERROR); 

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser

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.