[php]PHP错误处理
在创建脚本和 web 应用程序时,错误处理是一个重要的部分。如果您的代码缺少错误检测编码,那么程序看上去很不专业,也为安全风险敞开了大门。 本教程介绍了 PHP 中一些最为重要的错误检测方法。 我们将为您讲解不同的错误处理方法: 简单的 "die()" 语句 自定义错误和错误触发器 错误报告基本的错误处理:使用 die() 函数 第一个例子展示了一个打开文本文件的简单脚本:
$file=fopen("welcome.txt","r"); ?> 如果文件不存在,您会获得类似这样的错误: Warning: fopen(welcome.txt) [function.fopen]: failed to open stream: No such file or directory in C:\webfolder\test.php on line 2 为了避免用户获得类似上面的错误消息,我们在访问文件之前检测该文件是否存在:
if(!file_exists("welcome.txt")) { die("File not found"); } else { $file=fopen("welcome.txt","r"); } ?> 现在,假如文件不存在,您会得到类似这样的错误消息: File not found 比起之前的代码,上面的代码更有效,这是由于它采用了一个简单的错误处理机制在错误之后终止了脚本。 不过,简单地终止脚本并不总是恰当的方式。让我们研究一下用于处理错误的备选的 PHP 函数。 创建自定义错误处理器 创建一个自定义的错误处理器非常简单。我们很简单地创建了一个专用函数,可以在 PHP 中发生错误时调用该函数。 该函数必须有能力处理至少两个参数 (error level 和 error message),但是可以接受最多五个参数(可选的:file, line-number 以及 error context): 语法 error_function(error_level,error_message, error_file,error_line,error_context)
错误报告级别 这些错误报告级别是错误处理程序旨在处理的错误的不同的类型:
现在,让我们创建一个处理错误的函数:
function customError($errno, $errstr) { echo "Error: [$errno] $errstr echo "Ending Script"; die(); } 上面的代码是一个简单的错误处理函数。当它被触发时,它会取得错误级别和错误消息。然后它会输出错误级别和消息,并终止脚本。 现在,我们已经创建了一个错误处理函数,我们需要确定在何时触发该函数。 Set Error Handler PHP 的默认错误处理程序是内建的错误处理程序。我们打算把上面的函数改造为脚本运行期间的默认错误处理程序。 可以修改错误处理程序,使其仅应用到某些错误,这样脚本就可以不同的方式来处理不同的错误。不过,在本例中,我们打算针对所有错误来使用我们的自定义错误处理程序: set_error_handler("customError"); 由于我们希望我们的自定义函数来处理所有错误,set_error_handler() 仅需要一个参数,可以添加第二个参数来规定错误级别。 实例 通过尝试输出不存在的变量,来测试这个错误处理程序:
//error handler function function customError($errno, $errstr) { echo "Error: [$errno] $errstr"; } //set error handler set_error_handler("customError"); //trigger error echo($test); ?> 以上代码的输出应该类似这样: Custom error: [8] Undefined variable: test 触发错误 在脚本中用户输入数据的位置,当用户的输入无效时触发错误的很有用的。在 PHP 中,这个任务由 trigger_error() 完成。 例子 在本例中,如果 "test" 变量大于 "1",就会发生错误:
$test=2; if ($test>1) { trigger_error("Value must be 1 or below"); } ?> 以上代码的输出应该类似这样: Notice: Value must be 1 or below in C:\webfolder\test.php on line 6 您可以在脚本中任何位置触发错误,通过添加的第二个参数,您能够规定所触发的错误级别。 可能的错误类型: E_USER_ERROR - 致命的用户生成的 run-time 错误。错误无法恢复。脚本执行被中断。 E_USER_WARNING - 非致命的用户生成的 run-time 警告。脚本执行不被中断。 E_USER_NOTICE - 默认。用户生成的 run-time 通知。脚本发现了可能的错误,也有可能在脚本运行正常时发生。例子 在本例中,如果 "test" 变量大于 "1",则发生 E_USER_WARNING 错误。如果发生了 E_USER_WARNING,我们将使用我们的自定义错误处理程序并结束脚本:
//error handler function function customError($errno, $errstr) { echo "Error: [$errno] $errstr echo "Ending Script"; die(); } //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 Ending Script 现在,我们已经学习了如何创建自己的 error,以及如何处罚它们,现在我们研究一下错误记录。 错误记录 默认地,根据在 php.ini 中的 error_log 配置,PHP 向服务器的错误记录系统或文件发送错误记录。通过使用 error_log() 函数,您可以向指定的文件或远程目的地发送错误记录。 通过电子邮件向您自己发送错误消息,是一种获得指定错误的通知的好办法。 通过 E-Mail 发送错误消息 在下面的例子中,如果特定的错误发生,我们将发送带有错误消息的电子邮件,并结束脚本:
//error handler function function customError($errno, $errstr) { echo "Error: [$errno] $errstr 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 这个方法不适合所有的错误。常规错误应当通过使用默认的 PHP 记录系统在服务器上进行记录。 |

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

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

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio
