


Use PHP to instantly capture errors in PHP source code and send email notifications, javaemail sending_PHP tutorial
Jul 12, 2016 am 08:51 AMUse PHP to instantly capture errors in the PHP source code and send email notifications, javaemail sent
Friends who develop PHP know that in fact, the most worrying thing is the error in the program Some exceptions or errors. If these conditions are output to the user's screen, the user will be frightened and even lose their job. If they are not output to the screen, they have to find a way to record them in the log, but it seems that not everyone has the ability to check the errors. In order to solve this embarrassing problem, I wrote this code. Its purpose is to capture the error content when the php program we wrote makes an error and send it to our email.
Let’s take a look at the effect first:
<span>Define</span>('SYS_DEBUG',<span>false</span><span>); </span><span>IF</span><span>(SYS_DEBUG) { </span><span>ini_set</span>('display_errors','on'<span>); </span><span>Error_reporting</span>(<span>E_ALL</span>);<span>//</span><span>上線后使用該設(shè)定Error_reporting(E_ERROR | E_WARNING | E_PARSE);</span> }<span>Else</span><span>{ </span><span>ini_set</span>('display_errors','off'<span>); </span><span>Error_reporting</span>(0<span>); } </span><span>//</span><span>錯誤捕捉</span> <span>Register_shutdown_function</span>('Fun::Error'<span>); </span><span>Class</span><span> Fun{ </span><span>/*</span><span>* 通用出錯處理 參數(shù): 要輸出的內(nèi)容,是否終止執(zhí)行程序 說明: 有傳值時該函式可以用來輸出自定義的錯誤內(nèi)容 另外還可以配合Register_shutdown_function實現(xiàn)自動抓取錯誤內(nèi)容,並將抓取的錯誤內(nèi)容發(fā)送到Email內(nèi) Register_shutdown_function的機(jī)制是程序執(zhí)行完畢或中途出錯時調(diào)用函數(shù) 如果是自動抓取錯誤時被調(diào)用,則會取得最後一次出錯的內(nèi)容,如果發(fā)現(xiàn)沒有錯誤內(nèi)容則跳出 返回: 內(nèi)容會被直接輸出至螢?zāi)换駿mail內(nèi) 用法: Fun::Error('錯誤內(nèi)容'); Fun::Error('錯誤內(nèi)容',False); /*</span><span>*/</span> <span>Public</span> <span>Static</span> <span>Function</span> Error(<span>$M</span>='',<span>$E</span>=<span>True</span><span>){ </span><span>$ErrTpl</span>='<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head><body><table cellspacing="0" cellpadding="0" border="0"><tr><td>; </span><span>$M</span>=<span>Trim</span>(<span>$M</span><span>); </span><span>IF</span>(<span>$M</span>!='') {<span>//</span><span>手工調(diào)用</span> <span>$M</span>=' <b>注意:</b> '.<span>$M</span><span>; </span><span>Echo</span> <span>Strtr</span>(<span>$ErrTpl</span>,<span>Array</span>('{$M}'=><span>$M</span>));<span>unSet</span>(<span>$ErrTpl</span><span>); </span><span>IF</span>(<span>$E</span>===<span>True</span>) {<span>Die</span><span>();} </span><span>Return</span><span> ; }</span><span>Else</span>{<span>//</span><span>程式執(zhí)行完畢自動抓取錯誤時調(diào)用</span> <span>$M</span>=error_get_last();<span>//</span><span>取得最後產(chǎn)生的錯誤</span> <span>IF</span>(!<span>Is_array</span>(<span>$M</span>) Or <span>Count</span>(<span>$M</span>)<4) {<span>Unset</span>(<span>$M</span>);<span>Return</span><span> ;} </span><span>IF</span>(!<span>File_Exists</span>(<span>$M</span>['file'])) {<span>Unset</span>(<span>$M</span>);<span>Return</span><span> ;} </span><span>//</span><span>取得5行出錯關(guān)鍵代碼,如果取不到內(nèi)容,說明出錯檔案不存在</span> <span>$E</span>=<span>Array_slice</span>(<span>File</span>(<span>$M</span>['file']),(<span>$M</span>['line']-4),5<span>); </span><span>IF</span>(!<span>Is_array</span>(<span>$E</span>)) {<span>Unset</span>(<span>$M</span>,<span>$E</span>);<span>Return</span><span> ;} </span><span>$E</span>['M']=''<span>; </span><span>For</span>(<span>$i</span>=0;<span>$i</span><5;<span>$i</span>++<span>) { </span><span>$E</span>[<span>$i</span>]=<span>isSet</span>(<span>$E</span>[<span>$i</span>]) ? <span>$E</span>[<span>$i</span>] : ''<span>; </span><span>$E</span>['M'].=' '<span>; </span><span>$E</span>['M'].=(<span>$i</span>==3) ? '<b>'.((<span>$M</span>['line']-3)+(<span>$i</span>+1)).'</b>' : ((<span>$M</span>['line']-3)+(<span>$i</span>+1<span>)); </span><span>$E</span>['M'].=': '.<span>Htmlspecialchars</span>(<span>$E</span>[<span>$i</span>],ENT_QUOTES,'UTF-8').'<br>'<span>; } </span><span>$E</span>=&<span>$E</span>['M'<span>]; </span><span>$M</span>='<b>自動捕捉到有錯誤產(chǎn)生!</b><br><br><b>錯誤描述:</b><br> <b>'.<span>$M</span>['file'].'</b>的第<b>'.<span>$M</span>['line'].'</b>行出現(xiàn)了類型為<b>'.<span>$M</span>['type'].'</b>的錯誤:<br> '.<span>$M</span>['message'].'<br><br><b>關(guān)鍵代碼:</b><br>'.<span>$E</span>.'<br>'.self::now('Y-m-d H:i:s',<span>time</span>()).'<br>'<span>; </span><span>$M</span>=<span>Strtr</span>(<span>$ErrTpl</span>,<span>Array</span>('{$M}'=><span>$M</span>));<span>unSet</span>(<span>$ErrTpl</span><span>); </span><span>$G</span>=seft::getG('SYS','config'<span>); </span><span>IF</span>(!self::Mail2(<span>$G</span>['Spe'],'警告: '.<span>$G</span>['Tit'].' 出現(xiàn) PHP 程式錯誤!',<span>$M</span>) And SYS_DEBUG===<span>True</span><span>){ </span><span>throw</span> <span>new</span> <span>Exception</span>('警告: '.<span>$G</span>['Tit'].' 出現(xiàn) PHP 程式錯誤!<br><br>'.<span>$M</span><span>); } </span><span>IF</span>(SYS_DEBUG) {<span>Echo</span> <span>$M</span><span>;} </span><span>unSet</span>(<span>$E</span>,<span>$M</span>,<span>$G</span><span>); </span><span>Die</span><span>(); } } </span><span>/*</span><span>* 發(fā)送電郵 參數(shù): 收件人,郵件標(biāo)題(不可有換行符),郵件內(nèi)容(行與行之間必須用\n分隔,每行不可超過70個字符) 說明: 調(diào)用PHP內(nèi)置函式Mail發(fā)送電郵 返回: 返回布爾值 用法: $IsSend=Fun::Mail2($email,$tit,$msg); /*</span><span>*/</span> <span>Public</span> <span>Static</span> <span>Function</span> Mail2(<span>$to</span>,<span>$tit</span>,<span>$msg</span><span>) { </span><span>IF</span>(Filter_var(<span>$to</span>,FILTER_VALIDATE_EMAIL)==''<span>){ </span><span>throw</span> <span>new</span> <span>Exception</span>('電郵地址錯誤!'<span>); } </span><span>$tit</span>='=?UTF-8?B?'.<span>Base64_Encode</span>(<span>$tit</span>).'?='<span>; </span><span>$msg</span> = <span>str_replace</span>("\n.","\n..",<span>$msg</span>); <span>//</span><span>Windows如果在一行開頭發(fā)現(xiàn)一個句號則會被刪掉,要避免此問題將單個句號替換成兩個句號</span> <span>Return</span> <span>Mail</span>(<span>$to</span>,<span>$tit</span>,<span>$msg</span>,'From:'.seft::getG('config/SYS/Mal')."\n".'Content-Type:text/html;charset=utf-8'<span>); } }</span>

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

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

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez

TovalidateuserinputinPHP,usebuilt-invalidationfunctionslikefilter_var()andfilter_input(),applyregularexpressionsforcustomformatssuchasusernamesorphonenumbers,checkdatatypesfornumericvalueslikeageorprice,setlengthlimitsandtrimwhitespacetopreventlayout

ThePhpfunctionSerialize () andunserialize () AreusedtoconvertcomplexdaTastructdestoresintostoraSandaBackagain.1.Serialize () c OnvertsdatalikecarraysorobjectsraystringcontainingTypeandstructureinformation.2.unserialize () Reconstruct theoriginalatataprom

You can embed PHP code into HTML files, but make sure that the file has an extension of .php so that the server can parse it correctly. Use standard tags to wrap PHP code, insert dynamic content anywhere in HTML. In addition, you can switch PHP and HTML multiple times in the same file to realize dynamic functions such as conditional rendering. Be sure to pay attention to the server configuration and syntax correctness to avoid problems caused by short labels, quotation mark errors or omitted end labels.

The key to writing clean and easy-to-maintain PHP code lies in clear naming, following standards, reasonable structure, making good use of comments and testability. 1. Use clear variables, functions and class names, such as $userData and calculateTotalPrice(); 2. Follow the PSR-12 standard unified code style; 3. Split the code structure according to responsibilities, and organize it using MVC or Laravel-style catalogs; 4. Avoid noodles-style code and split the logic into small functions with a single responsibility; 5. Add comments at key points and write interface documents to clarify parameters, return values ??and exceptions; 6. Improve testability, adopt dependency injection, reduce global state and static methods. These practices improve code quality, collaboration efficiency and post-maintenance ease.

Yes,youcanrunSQLqueriesusingPHP,andtheprocessinvolveschoosingadatabaseextension,connectingtothedatabase,executingqueriessafely,andclosingconnectionswhendone.Todothis,firstchoosebetweenMySQLiorPDO,withPDObeingmoreflexibleduetosupportingmultipledatabas
