Tải bản đầy đủ - 0 (trang)
Chapter 12. Errors, Debugging, and Deployment

Chapter 12. Errors, Debugging, and Deployment

Tải bản đầy đủ - 0trang

12.1Errors

Ifyou'vewrittenPHPcodebeforeyou'vereadthischapter,

you'realreadyfamiliarwithPHPerrors.However,you've

probablynotthoughtmuchaboutthedifferenterrortypesand

thesituationsinwhichtheyoccur.Thissectiondiscusseserrors

indetail,andshowsyouhowtochangetheerrorreporting

levelsinPHPandmakethemostofdebugginginformation

duringdevelopment.

PHPproblemsbreakdownintofourtypesorlevels:errors,

parseerrors,warnings,andnotices.Theycanoccurinfour

differentsituations:internallywithinPHPitself(inthePHP

core),duringcompilationwhenyourscriptisfirstloaded,atrun

timewhenyourscriptisbeingexecuted,orwhenexplicitly

triggeredbyyouinyourcode.

Whileallthismightseemcomplicated,thevarietyleadstomore

informeddebugging,configurableerrorhandling,andflexibility

acrossallphasesofthedevelopmentofwebdatabase

applications.Inanycase,tosomeextentit'sunavoidable.A

missingbracketisalwaysdiscoveredduringcompilationand

abortstherunimmediately,whereasdivisionbyzeroorafailed

connectiontoadatabasemustwaittillthescripthasrunupto

thepointoftheerror.

Table12-1liststheproblemsandinwhatsituationstheyoccur;

forsimplicity,werefertoallofthepossibleproblemsand

situationcombinationsaserrors.Themostseriousoftheerror

typesaretheERRORandPARSEclasses:botharefatal,thatis,

bydefaulttheystopscriptexecutionandreportanerror

message.TheWARNINGclassisalsoseriousandstillreports

messages,butbydefaultdoesn'tstopscriptexecution.The

leastseriousoftheerrorsareintheNOTICEclass,whichby

defaultdon'treportmessagesorstopthescript.Wediscuss

howtoadjustthedefaultbehaviorslaterinthissection.



Table12-1.ErrorsinPHP

Constant

E_ERROR



E_WARNING



E_PARSE



E_NOTICE



E_CORE_ERROR



E_CORE_WARNING



E_COMPILE_ERROR



E_COMPILE_WARNING



E_USER_ERROR



E_USER_WARNING



U_USER_NOTICE



E_ALL



Description



Haltsscript?



Fatalruntimeerror



Yes



Non-fatalruntimeerror



No



Compile-timeparsererror



Yes



Runtimenotice



No



FatalPHPstartuperror



Yes



Non-fatalPHPstartuperror



No



Fatalcompile-timeerror



Yes



Non-fatalcompiletimeerror



No



Fatalprogrammer-generatederror



Programmer-defined



Non-fatalprogrammer-generatederror



Programmer-defined



Programmernotice



Programmer-defined



Alloftheabove



TheERRORclassincludeserrorssuchascallingundefined

functions,instantiatingobjectsofanon-existentclass,and

issuingastatementwhenitisn'tallowed(forexample,abreak

orcontinueoutsideofaloop).ThePARSEclassincludessyntax

errorsfrommissingsemicolons,missingquotesandbrackets,

andstatementswithincorrectnumbersofparameters.The

WARNINGclasscoverslessseriousproblemswhereascriptmay

beabletocontinuesuccessfullysuchastheMySQLconnection

problemsdiscussedinChapter6,dividebyzeroerrors,passing

thewrongnumberofparameterstoafunction,andincludinga

filethatdoesn'texist.TheNOTICEclasserrorsareusuallyminor

andinformationalandinclude,forexample,warningsabout

usingundefinedvariables.

TheWARNINGandERRORclasserrorscanbeproducedbythe

PHPcoreZendengine,thecompilationprocess,runtime

processing,ordeliberatetriggeringbytheprogrammer.Notices

canbeproducedbythelattertwo.Whilethissounds

complicatedtodealwith,mostofthetimetheonlyproblems

thatyourcodeneedstohandleafterit'sdeployedarethe

runtimeE_WARNINGerrors;theE_USER_ERROR,E_USER_WARNING,

andE_USER_NOTICEerrorsmayalsobehandledinyourcode,

andwediscussthislaterinSection12.3.We'vedeliberately

omittedE_PARSE,E_ERROR,andE_NOTICEfromthelistoferrors

yourcodeneedstoworryabout:theseareusuallyfixedbythe

programmerduringdevelopment.

Bydefault,errormessagesaredisplayedtotheuseragent

(usuallyawebbrowser),alongwithwhateveroutputhasbeen

produceduptothepointtheerroroccurred;theexceptionis

E_NOTICEerrors,whichareignoredwiththedefaultsettings.

Forexample,considerthefollowingscriptthatcontainsan

E_WARNINGerrorthat'sdetectedatruntime:




"-//W3C//DTDHTML4.01Transitional//EN"

"http://www.w3.org/TR/html401/loose.dtd">








Error



Twotimes!




functiondouble($number)

{

return$number*2;

}



print"Twotimestenis:".double();

print"
Twotimesfiveis:".double(5);

?>









Thefunctiondouble()iscalledwithoutitsparameterinthefirst

printstatement,andsoawarningisproducedasshowninthe

MozillabrowserinFigure12-1.ThePHP-generatedwarning

occursaftertheHTML

texthasbeenoutput,butbefore

theoutputoftheprintstatementthatcontainstheerror.

Becauseit'sawarning,thescriptcontinues,andbothprint

statementsproduceoutput.Theerroritselfisusefulfor

debugging:itcontainsadescriptionofwhatcausedtheerror,

andthesourcefileandlinenumber.Wediscussthecommon

sourcesoferrorsandhowtofindthemlaterinthissection.



Figure12-1.Scriptoutputthatcontainsan

E_WARNINGerror



Whenyouusetemplates,you'llfindthattheerrorsareusually

outputbeforetheoutputofthescript.Thisisbecausetemplate

outputisbuffereduntilyoucalltheshow()method,whileerror

outputissentdirectlytotheuseragent.Thiscanmake



debuggingalittleharder,butitdoeshelppreventerror

messagesfrombeingconfusedamidstthescriptoutput.

TheE_ERRORruntimeerrorsstopscriptexecution,sothescript

producesoutputonlyuptothepointwheretheerroroccurred.

Inthecaseoftemplates,it'stypicalthatnooutputexceptthe

errorwillbeproduced.Similarly,E_PARSEerrorspreventany

scriptoutput,astheproblemsaredetectedbeforeruntime.



12.1.1AccessingthePHPManual

Duringdevelopment,theerrorsproducedbyPHPareuseful

toolsfordebuggingyourcode.Forexample,supposeyou

attempttoestablishamysql_connect()connectionbutmisspell

localhost.Thisproducestheerror:

Warning:mysql_connect()[function.mysql-connect.html]:

UnknownMySQLServerHost'localhos'(1)in

/usr/local/apache2/htdocs/examples/buggy.phponline18



Bydefault,becausealibraryfunctionisinvolved,PHPproduces

alinktothePHPmanualfunctionreferenceformysql_connect(

),whichisshownsurroundedbysquarebraces.Youcanclickon

thislinkandvisitthemanual.However,asdiscussedinChapter

6,ifyouprefixyourfunctioncallswith@thentheseerror

messagesaresuppressed.

Tosupportdevelopment,it'susefultohaveacopyofthePHP

manualinthedocumenttreeofyourdevelopmentenvironment.

Todothis,downloadacopyoftheManyFilesHTMLversion

fromhttp://www.php.net/download-docs.php.Thencreatea

directorybelowyourhtdocsdirectoryanduncompressthefile



intothatdirectory.Forexample,ifyou'vefollowedourUnix

installationinstructionsinAppendixAthroughAppendixC,you

couldusemkdir/usr/local/apache2/htdocs/php-manualto

createthedirectory,movethefilethere,andthenuncompress

itwithbunzip2.Ifyou'vefollowedourEasyPHPinstallation

instructionsforMicrosoftWindows,createthefolder

C:\ProgramFiles\EasyPHP1-7\www\php-manualandputthefile

there.OnMacOSX,use/Library/WebServer/Documents/phpmanual.ThePHPsitehasausefulFAQentryforMicrosoft

Windowsuserswhoaren'tfamiliarwiththebzip2compressed

fileformat:

http://au.php.net/manual/en/faq.misc.php#faq.misc.bz2.

Afterdownloadingthefile,youneedtoconfigureyourPHPto

linktoyourlocalmanual.Todothis,openyourphp.inifileinan

editorandlocatethelinebeginningdocref_root=.Changethe

linetopointtoyournewdirectorybelowyourdocumentroot

(forexample,docref_root=/php-manual),ensurethatthe

immediatelyfollowinglinereadsdoc_ref=.html,andthatthe

line;html_errors=hasasemicolonatthebeginning.Save

thefile,andrestartyourApachewebserverusingthe

instructionsinAppendixAthroughAppendixC.



12.1.2ConfiguringErrorReporting

Errorsprovideusefulinformationwhenyou'redebuggingyour

application.However,whenit'sdeployed,displayingPHPerrors

amongtheapplicationoutputismessy,confusingforusers,and

uninformativeforthosewhoneedtobealertedtorectifythe

problems.Mostimportantly,it'salsoasecurityproblem:

programinternalsaredisplayedaspartoferrormessagesand

theseshouldn'tbedisplayedtoendusers.

ErrorreportingisconfiguredinPHPintwocommonways.First,

bysettingaglobaldefaultinthephp.inifile;and,second,by

settingerrorreportingonascript-by-scriptbasis.Bydefault,in



thephp.inifile,you'llfindthaterrorreportingisgloballysetto:

error_reporting=E_ALL&~E_NOTICE



Thismeansthatallerrortypesarereported,exceptE_NOTICE

errors;the&operatoristhebitwiseANDdiscussedinChapter2,

andthe~isthebitwiseNOTusedtonegateE_NOTICE.Thelist

ofpossibleconstantsthatcanbeusedinshowninTable12-1.

Youcanadjustthisconfigurationtosuityourrequirementsby

modifyingtheglobaldefaultforallscriptsorbysettinga

specificvalueinascriptthat'susedonlyinthatscript.For

example,tochangetheglobalvaluetodetectonlytheERROR

andPARSEclasses,youcanuse:



error_reporting=E_COMPILE_ERROR|E_ERROR|E_CORE_ERROR|E_PARS



Bydefault,allwarningsandnoticesarethenignored;the|

operatoristhebitwiseOR.Asbefore,aftermakinganychange

tophp.ini,youneedtorestartyourApachewebserver.

Tosetanerror-reportinglevelforonescript,youcanusethe

error_reporting()libraryfunction.Forexample,todetectall

errortypes,youcanadd:


error_reporting(E_ALL);



tothebeginningofthescript.Thefunctionalsotakesa

constantfromTable12-1astheparameter,andyoucanusethe



bitwise&,|,and~tocombinetheconstantvalues.Aswe

discussedinChapter6,youcanalsosuppresserrorreporting

foraspecificfunctionusingthe@operator.Forexample,to

preventerrorsfromacalltomysql_connect(),youcanuse:

$connection=@mysql_connect("localhost","fred","shhh");



Werecommendthatduringdevelopmentyouturnonallerror

reportingusingtheglobalphp.inisetting.Changeitto:

error_reporting=E_ALL



However,wedon'trecommendthissettingfordeploymentfor

thereasonswediscussedpreviously.Whenyoudeployyour

application,youcanfollowtwoapproachestohandlingerrors:

turnthemoffaveryoptimisticapproach!orwriteahandlerthat

triestodealwiththemgracefullyduringtheapplication'srun.

Turningthemoffiseasy(setthephp.inisetting

error_reporting=0)butitisn'trecommendedbecauseit'll

preventanyproblemswithyourapplicationbeingdetected.

Addingaprofessionalerrorhandlertoyourapplicationis

discussedlaterinSection12.3.



12.2CommonProgrammingErrors

Nowthatwe'vediscussedwhaterrorsPHPcanproduce,let's

discusshowtofixthem.Inthissection,wefocusonsituations

whereerrormessagesaren'tproducedorarelessusefulin

helpingtofindthebug.Inparticular,wefocusonthecommon

mistakesthatevenexperiencedprogrammersmake.



12.2.1APageThatProducesPartialorNo

Output

OneofthemostcommonproblemsindebuggingPHPscriptsis

seeing:

Nothingrenderedbythewebbrowser

Apop-updialogboxstatingthatthe"DocumentContains

NoData"

Apartialdocumentwhenmoreisexpected

Mostoftheseproblemsarecausednotbyabuginascript,but

byabugintheHTMLproducedbythescriptortemplate.For

example,if,,orclosingtagsare

omitted,adocumentmaynotberenderedinsomebrowsers.

AnHTMLproblemcanoftenbeidentifiedbyviewingtheHTML

pagesourceusingthewebbrowser.Forexample,onaLinux

platformrunningMozillaorNetscape,thepagesourcecanbe

accessedwitharight-mouseclickanywhereoverthedocument

andbythenselectingViewPageSourcefromthepop-upmenu.

Forcompoundorhard-to-identifyHTMLbugs,theW3Cvalidator



athttp://validator.w3.org/analyzesthecorrectnessoftheHTML

andissuesareport.It'sanexcellentassistantfordebugging

andfinalcompliancechecksbeforedeliveryofanapplication.

YoucanentertheURLofyourresourceintotheW3Cvalidator,

oryoucanuploadtheHTMLoutputandhaveitchecked.The

formeriseasiest,butthelatterissometimestheonlyoptionif

yourpagecan'tberetrievedfrombehindafirewallorbecausea

PHPsessionorauthenticationisneededtoaccessit.

Ifyouwanttouploadapagetothevalidator,theeasiest

methodistousetheSavePageAs...menuoptioninyour

browsertosavethedocument.Then,uploadthesavedfileby

clickingonBrowsenexttotheLocalFileboxat

http://validator.w3.org.Rememberwhenusingthevalidator

thatyouneedtovalidatethescriptunderallitsdifferentoutput

conditions:forexample,ifyourpagecanproduceaformor

displaytheresultsofaqueryinatable,youneedtocheckboth

scenarios.

IfanHTMLproblemstillproveshardtofind,anditdoesn'tuse

templates,consideraddingcallstotheflush()functionafter

printorprintfstatements.Theflush()functionemptiesthe

outputbuffermaintainedbythePHPengine,sendingall

currentlybufferedoutputtothewebserver;withoutflush(),

bufferedoutputusuallyisn'tsenttothebrowserwhenanerror

occursandthescriptstops.Thefunctionhasnoeffecton

bufferingatthewebserverorthewebbrowser,butitdoes

ensurethatalldataoutputbythescriptisavailabletotheweb

servertobetransmittedandrenderedbyabrowser.Remember

toremovetheflush()functioncallsafterdebugging,because

unnecessaryflushingmaypreventefficientbufferingofoutput

bythePHPscriptingengine.Bufferinganditsuseinerror

reportingisdiscussedinmoredetailinSection12.3.

Acommonproblemthatshouldn'tbeconfusedwiththose

describedhereisnotreceivingaresponsefromthewebserver

andgettinga"noresponse"errormessage.Thisproblemisa



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 12. Errors, Debugging, and Deployment

Tải bản đầy đủ ngay(0 tr)

×