


Errors and exceptions encountered by PHP programmers Part 1 Errors
The content of this article is about the errors and exceptions encountered by PHP programmers. Now I share it with you. Friends in need can refer to it
1. Introduction to the error module in PHP
PHP errors and exceptions are two different concepts
1.1 Error type
Syntactic errors, such as missing semicolons
Environmental errors, such as permissions, failure to open files, and database server unavailability
Logical errors, such as a==b written as a=b
1.2 PHP common error levels
#Depracated
The lowest level error (deprecated is not recommended, not recommended, such as the old version of regular expressionsereg()
The function can be replaced and it will not affect the execution of PHP)Notice
Notification level error (caused by improper syntax, not Affect the normal operation of PHP, such as printing an undefined variable, so we must develop good writing practices from the beginning)Warning
Warning level errors (The code must be modified)Fatal error
Fatal level error,the program will stop
Parse error
Syntax parsing error, check before running the code,will not be able to execute the code
##E_USER_related errors
Errors defined by the user, used when manually throwing errors
error_reporting=E_ALL & ~E_NOTICE # 显示所有但不显示提醒错误
display_errors = Off|On # 是否显示错误,线上后关闭提高用户体验
1.3.2 Dynamic settingserror_reporting() # 专业php错误处理设置函数,动态设置错误级别
error_reporting(0) # 不显示所有错误,但是解析parse语法错误会显示
error_reporting(-1) # 显示所有错误
Error_reporting(E_ALL|~E_WARING) # 除了警告错误以外的错误级别都报告
1.3.3 Set the value of configuration options at runtimeini_set(option,value)
ini_set(error_reporting,0)
ini_set(error_reporting,-1)
ini_set(error_reporting,E_ALL)
ini_set(display_errors,0)
ini_set(display_errors,OFF/0)
error_reporting(-1);
14. trigger_error is triggered manually Wrong transmission of @ Error suppressor, placed at the beginning of the line does not display the error of the line
trigger_error('Error prompt Content',E_USER_NOTICE)
E_USER_NOTICE # 继续执行(通知级别)
E_USER_WARNING # 继续执行(警告错误)
E_USER_ERROR # 程序不再执行(致命错误)
2. Processing in PHP Error
2.1 Save the error log in the specified file
ini_set('display_errors','off') # 不显示错误给用户 ini_set("error_log","c:\error.log"); error_reporting(-1); # 显示所有错误
2.2 Save the error log in the system log
ini_set("error_log", 'syslog')
2.3 Send the error log to the email
error_log("this is a errormsg",1,xxxxx@qq.com);
3. Custom Error Handler
3.1 set_error_handler Custom Error Handler
set_error_handler("自定义函数名",'错误级别(选填)') # 设置一个用户定义的错误处理函数 restore_error_handler(); # 回收(取消自定义错误函数接管php系统错误)
##3.2 Custom Error Handler
class MyErrorHandler{ //错误信息 public $message = ''; //错误文件 public $filename = ''; //错误行号 public $line = 0; //额外信息 public $vars = array(); protected $_noticelog = 'G:\notice\noticeLog.log'; public function __construct($message, $filename, $line, $vars) { $this->message = $message; $this->filename = $filename; $this->line = $line; $this->vars = $vars; } //根据不同错误级别对应不同操作 //遵循handler错误处理原则,errno:错误代码,line:错误行号 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; } } /** * 如何处理致命错误 */ public function dealError() { //开启内存缓冲 ob_start(); //回溯上一条信息 debug_print_backtrace(); $backtrace = ob_get_flush(); $errorMsg = <<<EOF 出现了致命错误,如下: 产生错误的文件:{$this->filename} 产生错误的信息:{$this->message} 产生错误的行号:{$this->line} 追踪信息:{$backtrace} EOF; // error_log($errorMsg,1,'xxxx@qq.com'); error_log($errorMsg,3,$this->_noticelog); exit(1); } /** * 如何处理警告错误 */ public function dealWarning() { $errorMsg = <<<EOF 出现了警告错误,如下: 产生警告的文件:{$this->filename} 产生警告的信息:{$this->message} 产生警告的行号:{$this->line} EOF; // return error_log($errorMsg,1,'xxx@qq.com'); return error_log($errorMsg,3,$this->_noticelog); } /** * 如何处理通知错误 */ public function dealNotice() { $datetime = date('Y-m-d H:i:s',time()); $errorMsg = <<<EOF 出现了通知错误,如下: 产生通知的文件:{$this->filename} 产生通知的信息:{$this->message} 产生通知的行号:{$this->line} 产生通知的时间:{$datetime} EOF; return error_log($errorMsg,3,$this->_noticelog); } }3.3 Error handler test
require_once 'MyErrorHandler.php';
error_reporting(-1);
//使用MyErrorHandler类直接调用deal方法
/**
* set_error_handler(array(类名/new 类名,方法名));
* set_error_handler(函数名);
*/
set_error_handler(array('MyErrorHandler','deal'));
//通知级别错误
echo $test;
//警告级别错误
settype($var,'king');
//致命错误
//test();
//总结:手动抛出的信息会被显示在浏览器
trigger_error('我是手动抛出的致命错误',E_USER_ERROR);
echo 'this is a test ';
3.4 Register_shutdown_function function usage
Usage scenarios:
The page was forced to stop
The program code unexpectedly terminated or timed out
## register_shutdown_function()The function is
from memory, that is, after the PHP statement is executed (The page no longer exists) Call this function again, so when writing the path, you have already separated from the script, so
file_put_contents()The path must use an absolute path
error_get_last # 得到最后产生的错误
Note:
If there is die/exit before register_shutdown_function(), it will not be executed不finished! To be continued in the next article:
Errors and exceptions encountered by PHPer in those years: Exceptions in the next article
Reference course video: Errors and exceptions you encountered in those years abnormal
The above is the detailed content of Errors and exceptions encountered by PHP programmers Part 1 Errors. For more information, please follow other related articles on the PHP Chinese website!

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

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.

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

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 is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.


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

SublimeText3 Chinese version
Chinese version, very easy to use

Atom editor mac version download
The most popular open source editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1
Powerful PHP integrated development environment

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