Table of Contents
常见错误处理类型
常见错误级别
PHP配置文件和错误相关选项
使用triggerr_error进行错误抛出
记录错误
error_log函数使用
如何使用Set_error_handler()
自定义一个错误处理器
register_shutdown_function()函数
错误抑制符
错误级别
Home Backend Development PHP Tutorial php的异常和处理

php的异常和处理

Jun 20, 2016 pm 12:45 PM

常见错误处理类型

  • 语法错误

  • 环境错误

  • 逻辑错误

常见错误级别

  • Deprecated 最低级别的错误

    • 不推荐,不建议,使用一些过期函数的时候会出现,程序继续执行

  • Notice 通知级别的错误

    • 使用一些未定义变量、常量或者数组key没有加引号的时候会出现,程序继续执行

  • Waning 警告级别的错误

    • 程序出问题了,需要修改代码!!!程序继续执行

  • Fatal Error 错误级别的错误

    • 程序直接报错,需要修改代码!!!中断程序执行

  • parse error 语法解析错误

    • 语法检查阶段报错,需要修改代码!!!中断程序执行

  • E_USER_相关的错误

    • 用户定义的错误,用户手动抛出错误,进行自定义错误处理

PHP配置文件和错误相关选项

设置错误级别
1、通过修改php.ini文件设置错误级别,静态设置,需要重启apache
// error_reporting = E_ALL&~E_NOTICE; //显示所有错误,除了E_NOTICE级别
// display_errors = 1; //线下开启,先上关闭

2、通过error_reporting()函数设置,动态设置
// error_reporting(E_ALL&~E_NOTICE); //显示所有错误,除了E_NOTICE级别
// error_reporting(0); //屏蔽所有错误,只会显示语法解析错误
// erorr_reporting(-1); //显示所有错误

3、通过ini_set()函数进行运行时设置,动态设置
// ini_set('error_reporting',0);
// ini_set('error_reporting',-1);
// ini_set('display_errors',0);

使用triggerr_error进行错误抛出

<?phpheader('content-type:text/html;charset=utf-8');$num1=1;$num2='xxx';if ( (!is_numeric($num1) || !is_numeric($num2)) ) {    //通知级别,代码继续执行    //echo trigger_error('数值必须为整型!',E_USER_NOTICE);         //警告级别,代码继续执行    //echo trigger_error('数值必须为整型!',E_USER_WARNING);         //错误级别,代码中断    echo trigger_error('数值必须为整型!',E_USER_ERROR); }else{    echo $num1+$num2;}echo '<br />代码继续执行';
Copy after login

记录错误

配置php.ini脚本设置记录错误
log_errors = On //是否将产生错误信息记录到日志或者error_log中
;error_log = syslog //设置脚本错误将记录到系统日志中
log_errors_max_len = 1024 //设置错误报错最大值,单位字节
ignore_repeated_errors = Off //是否忽略重复的错误信息
ignore_repeated_source = Off //是否忽略重复错误消息的来源
track_errors = On //如果开启,最后一个错误将永远保存在$php_errormsg中

将错误记录到指定的文件中

<?php//运行时设置错误处理ini_set('display_errors','off');ini_set('error_log','D:\logs\error.log');//设置错误输出error_reporting(-1);echo $test; //NOTICEecho '<hr />';settype($var,'king'); //Warningecho '<hr />';test(); //Fatal error
Copy after login

将日志文件保存到系统日志中

<?phperror_reporting(-1);ini_set('display_errors',0);ini_set('log_errors',1);ini_set('error_log','syslog');//该记录方式,在windows中需要去,计算机管理-》事件查看器-》自定义视图中查找php5.4.0的log日志openlog('PHP5.4.0',LOG_PID,LOG_SYSLOG);syslog(LOG_ERR,'this is syslog !!!daye:'.date('Y/m/d H:i:s'));closelog();
Copy after login

将错误以邮件形式发送
1、首先需要配置邮件服务器!
2、去php.ini中配置邮件参数
3、写代码

error_log('当前系统被人攻击!产生错误!',1,'87399497@qq.com');
Copy after login

error_log函数使用

error_log($msg); //传入错误记录,需要与error_log配置使用
Copy after login

如何使用Set_error_handler()

<?phpheader('content-type:text/html;charset=utf-8');//-1代表显示所有的错误警告error_reporting(-1);/** * 自定义一个错误处理 * @param  [type] $errno  [错误级别] * @param  [type] $errmsg [错误信息] * @param  [type] $file   [错误文件] * @param  [type] $line   [错误行号] * @return [type]         [description] */function customer_error($errno,$errmsg,$file,$line){    echo "<b>错误代码:</b>[{$errno}] {$errmsg} <br/>".PHP_EOL;    echo "<b>错误行号:</b>{$file}文件中的第 {$line} <br/>".PHP_EOL;    echo "<b>PHP版本:</b>".PHP_VERSION."(".PHP_OS.") <br/>".PHP_EOL;    //注意:如果自定义错误处理捕获了,代码还是会执行,如果不想被执行,需要die掉!!!    //die;}//设置自定义错误处理set_error_handler('customer_error');//输出一个未定义变量的警告echo $test;echo '<hr/>';//原生出错//Notice: Undefined variable: test in D:\phpStudy\WWW\example\index.php on line 26//自定义出错//错误代码:[8] Undefined variable: test //错误行号:D:\phpStudy\WWW\example\index.php文件中的第 26 //PHP版本:5.3.29(WINNT) //无法捕获一个致命错误Fatal error,会切换到原生出错//test();//手动抛出一个错误,被自定义的错误处理捕获trigger_error('this is a test of error',E_USER_ERROR);echo 'contiune';echo '<hr/>';//错误代码:[256] this is a test of error //错误行号:D:\phpStudy\WWW\example\index.php文件中的第 43 //PHP版本:5.3.29(WINNT) //contiune//取消自定义错误处理,将会重新适应PHP原生的错误处理restore_error_handler();echo $tt;echo '<hr />';//Notice: Undefined variable: tt in D:\phpStudy\WWW\example\index.php on line 49//重新挂载自定义错误处理//除了NOTICE级别的交给系统处理,剩下的全部使用customer_error自定义的错误处理set_error_handler('customer_error',E_ALL&~E_NOTICE);echo $asc; //E_NOTICE级别,系统的错误处理settype($var,'king'); //E_WARNING级别,使用自定义的错误处理//Notice: Undefined variable: asc in D:\phpStudy\WWW\example\index.php on line 65//错误代码:[2] settype() [function.settype]: Invalid type //错误行号:D:\phpStudy\WWW\example\index.php文件中的第 66 //PHP版本:5.3.29(WINNT) 
Copy after login

自定义一个错误处理器

<?phpclass MyErrorHandler{        public $msg='';    public $filename='';    public $line=0;    public $vars=array();    public function __construct($msg,$filename,$line,$vars){        $this->msg = $msg;        $this->filename = $filename;        $this->line = $line;        $this->vars = $vars;    }    public static function deal($errno,$errmsg,$filename,$line,$vars){                $self = new self($errmsg,$filename,$line,$vars);        switch ($errno) {            case E_USER_ERROR :                return $self->dealError();                break;            case E_USER_WARNING :            case E_WARNING :                return $self->dealWarning();                break;            case E_NOTICE :            case E_USER_NOTICE :                return $self->dealNotice();                break;            default:                return false;                break;        }    }    /**     * 处理致命错误     * @return [type] [description]     */    public function dealError(){        ob_start();        debug_print_backtrace();        $backtrace = ob_get_flush();        $errmsg = <<<EOF出现了致命错误,如下:产生错误的文件:{$this->filename}产生错误的信息:{$this->msg}产生错误的行号:{$this->line}追踪信息:{$backtrace}EOF;        //发送邮件的错误日志        //error_log($errmsg,1,'87399497@qq.com');        //记录到错误日志        error_log($errmsg,3,'D:/logs/customer_error.log');        exit(1);    }    /**     * 处理警告错误     * @return [type] [description]     */    public function dealWarning(){        $errmsg = <<<EOF出现了警告错误,如下:产生警告的文件:{$this->filename}产生警告的信息:{$this->msg}产生警告的行号:{$this->line}EOF;        error_log($errmsg,3,'D:/logs/customer_warning.log');    }    /**     * 处理通知级别的错误     * @return [type] [description]     */    public function dealNotice(){        $date = date('Y-m-d H:i:s',time());        $errmsg = <<<EOF出现了通知错误,如下:产生错误的文件:{$this->filename}产生错误的信息:{$this->msg}产生错误的行号:{$this->line}产生通知的时间:{$date}EOF;        error_log($errmsg,3,'D:/logs/customer_notice.log');    }}//显示所有错误error_reporting(-1);//设置自定义错误,使用传入类和方法的方式set_error_handler(array('MyErrorHandler','deal'));//触发NOTICE级别错误,会保存到log日志中echo $tt;//手动触发一个错误trigger_error('手动抛出一个错误',E_USER_ERROR);
Copy after login

register_shutdown_function()函数

<?php //register_shutdown_function该函数将会在PHP执行关闭时调用//使用场景//1、页面强制停止//2、代码意外终止class Showdown{    public static function endScript(){        if (error_get_last()){            echo '<pre class="brush:php;toolbar:false">';            error_get_last();            echo '
Copy after login
'; //因为register_shutdown_function调用该函数的时候,是代码终止,脱离当前PHP上下文环境了 //所以$filename的路径要写决定路径!!! file_put_contents('D:\logs\register_shutdown_function.log', error_get_last()); die('endScript'); } }}//特别声明!如果有die或exit在注册错误处理之前,那么将不会注册错误处理register_shutdown_function(array('Showdown','endScript'));echo md6();

错误抑制符

@settype($var,'longjq'); //无变量$var,使用@符号进行抑制错误输出
Copy after login

错误级别

http://www.w3school.com.cn/php/php_ref_error.asp

Statement of this Website
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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1263
29
C# Tutorial
1237
24
Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Apr 08, 2025 am 12:03 AM

There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? Apr 09, 2025 am 12:09 AM

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Explain the difference between self::, parent::, and static:: in PHP OOP. Explain the difference between self::, parent::, and static:: in PHP OOP. Apr 09, 2025 am 12:04 AM

In PHPOOP, self:: refers to the current class, parent:: refers to the parent class, static:: is used for late static binding. 1.self:: is used for static method and constant calls, but does not support late static binding. 2.parent:: is used for subclasses to call parent class methods, and private methods cannot be accessed. 3.static:: supports late static binding, suitable for inheritance and polymorphism, but may affect the readability of the code.

How does PHP handle file uploads securely? How does PHP handle file uploads securely? Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

See all articles