search
HomeBackend DevelopmentPHP Tutorial用PHP即时捕捉PHP中的错误并发送email通知的实现代码_php技巧

开发PHP的朋友都知道,其实最担心的就是程序中出现一些异常或错误,这些状况如果输出到用户的萤幕会把用户给吓坏,甚至为此丢了工作,如果不输出到萤幕就得想办法记录到日志中,但是似乎不是每个人都有查看错误日志的习惯,爲了解决这个尴尬的问题,所以我写了这段代码,其用意就是当我们写的php程式出错的时候把错误内容捕捉出来然后发到我们的email内.

先看效果:
用PHP即时捕捉PHP中的错误并发送email通知的实现代码_php技巧

复制代码 代码如下:

Define('SYS_DEBUG',false);
IF(SYS_DEBUG) {
ini_set('display_errors','on');
Error_reporting(E_ALL);//上线后使用该设定Error_reporting(E_ERROR | E_WARNING | E_PARSE);
}Else{
ini_set('display_errors','off');
Error_reporting(0);
}

//错误捕捉
Register_shutdown_function('Fun::Error');

Class Fun{

/**
通用出错处理
参数:
要输出的内容,是否终止执行程序
说明:
有传值时该函式可以用来输出自定义的错误内容
另外还可以配合Register_shutdown_function实现自动抓取错误内容,并将抓取的错误内容发送到Email内
Register_shutdown_function的机制是程序执行完毕或中途出错时调用函数
如果是自动抓取错误时被调用,则会取得最后一次出错的内容,如果发现没有错误内容则跳出
返回:
内容会被直接输出至萤幕或Email内
用法:
Fun::Error('错误内容');
Fun::Error('错误内容',False);
/**/
Public Static Function Error($M='',$E=True){
$ErrTpl='
{$M}
';

$M=Trim($M);
IF($M!='') {//手工调用
$M=' 注意: '.$M;
Echo Strtr($ErrTpl,Array('{$M}'=>$M));unSet($ErrTpl);
IF($E===True) {Die();}
Return ;
}Else{//程式执行完毕自动抓取错误时调用
$M=error_get_last();//取得最后产生的错误
IF(!Is_array($M) Or Count($M)IF(!File_Exists($M['file'])) {Unset($M);Return ;}

//取得5行出错关键代码,如果取不到内容,说明出错档桉不存在
$E=Array_slice(File($M['file']),($M['line']-4),5);
IF(!Is_array($E)) {Unset($M,$E);Return ;}

$E['M']='';
For($i=0;$i$E[$i]=isSet($E[$i]) ? $E[$i] : '';
$E['M'].='  ';
$E['M'].=($i==3) ? ''.(($M['line']-3)+($i+1)).'' : (($M['line']-3)+($i+1));
$E['M'].=': '.Htmlspecialchars($E[$i],ENT_QUOTES,'UTF-8').'
';
}
$E=&$E['M'];

$M='自动捕捉到有错误产生!

错误描述:
  '.$M['file'].'的第'.$M['line'].'行出现了类型为'.$M['type'].'的错误:
  '.$M['message'].'

关键代码:
'.$E.'
'.self::now('Y-m-d H:i:s',time()).'
';

$M=Strtr($ErrTpl,Array('{$M}'=>$M));unSet($ErrTpl);

$G=seft::getG('SYS','config');
IF(!self::Mail2($G['Spe'],'警告: '.$G['Tit'].' 出现 PHP 程式错误!',$M) And SYS_DEBUG===True){
throw new Exception('警告: '.$G['Tit'].' 出现 PHP 程式错误!

'.$M);
}
IF(SYS_DEBUG) {Echo $M;}
unSet($E,$M,$G);
Die();
}
}
/**
发送电邮
参数:
收件人,邮件标题(不可有换行符),邮件内容(行与行之间必须用\n分隔,每行不可超过70个字符)
说明:
调用PHP内置函式Mail发送电邮
返回:
返回布尔值
用法:
$IsSend=Fun::Mail2($email,$tit,$msg);
/**/
Public Static Function Mail2($to,$tit,$msg) {
IF(Filter_var($to,FILTER_VALIDATE_EMAIL)==''){
throw new Exception('电邮地址错误!');
}

$tit='=?UTF-8?B?'.Base64_Encode($tit).'?=';
$msg = str_replace("\n.","\n..",$msg); //Windows如果在一行开头发现一个句号则会被删掉,要避免此问题将单个句号替换成两个句号

Return Mail($to,$tit,$msg,'From:'.seft::getG('config/SYS/Mal')."\n".'Content-Type:text/html;charset=utf-8');
}
}
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
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

See all articles

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 Article

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.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

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.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools