Tải bản đầy đủ (.pdf) (1,022 trang)

OReilly programming PHP 2nd edition apr 2006 ISBN 0596006810

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (4.39 MB, 1,022 trang )

ProgrammingPHP,2ndEdition
ByRasmusLerdorf,PeterMacIntyre,KevinTatroe
...............................................
Publisher:O'Reilly
PubDate:April2006
PrintISBN-10:0-596-00681-0
PrintISBN-13:978-0-59-600681-5
Pages:540

TableofContents|Index

ProgrammingPHP,SecondEditionistheauthoritativeguidetoPHP5andisfilledwiththe
uniqueknowledgeofthecreatorofPHP(RasmusLerdorf)andotherPHPexperts.Whenit
comestocreatingwebsites,thePHPscriptinglanguageistrulyared-hotproperty.Infact,
PHPiscurrentlyusedonmorethan19millionwebsites,surpassingMicrosoft'sASP.NET
technologyinpopularity.Programmersloveitsflexibilityandspeed;designersloveits
accessibilityandconvenience.

AstheindustrystandardbookonPHP,alloftheessentialsarecoveredinaclearand
concisemanner.Languagesyntaxandprogrammingtechniquesarecoupledwith
numerousexamplesthatillustratebothcorrectusageandcommonidioms.Withstyletips
andpracticalprogrammingadvice,thisbookwillhelpyoubecomenotjustaPHP
programmer,butalsoagoodPHPprogrammer.ProgrammingPHP,SecondEditioncovers
everythingyouneedtoknowtocreateeffectivewebapplicationswithPHP.Contents
include:
--DetailedinformationonthebasicsofthePHPlanguage,
includingdatatypes,variables,operators,andflowcontrolstatements
--Chaptersoutliningthebasicsoffunctions,strings,
arrays,andobjects
--CoverageofcommonPHPwebapplicationtechniques,such
asformprocessingandvalidation,sessiontracking,andcookies


--Materialoninteractingwithrelationaldatabases,such
asMySQLandOracle,usingthedatabase-independentPEARDBlibraryandthenew
PDOLibrary
--Chaptersthatshowyouhowtogeneratedynamicimages,createPDFfiles,and
parseXMLfileswithPHP


--Advancedtopics,suchascreatingsecurescripts,errorhandling,performance
tuning,andwritingyourownClanguageextensionstoPHP
--AhandyquickreferencetoallthecorefunctionsinPHP
andallthestandardextensionsthatshipwithPHP

Praiseforthefirstedition:

"IfyouarejustgettingintothedynamicWebdevelopmentworldoryou
areconsideringmigratingfromanotherdynamicwebproducttoPHP,ProgrammingPHPis
thebookofchoicetogetyouup,runningandproductiveinashorttime."

--PeterMacIntrye,eWeek

"Ithinkthisisagreatbookforprogrammerswhowanttostartdevelopingdynamicweb
siteswithPHP.ItgivesadetailedoverviewofPHP,lotsofvaluabletips,andagoodsense
ofPHP'sstrengths."

--DavidDooling,Slashdot.org


ProgrammingPHP,2ndEdition
ByRasmusLerdorf,PeterMacIntyre,KevinTatroe
...............................................

Publisher:O'Reilly
PubDate:April2006
PrintISBN-10:0-596-00681-0
PrintISBN-13:978-0-59-600681-5
Pages:540

TableofContents|Index















































ProgrammingPHP,SecondEdition
Foreword
Preface
Audience
AssumptionsThisBookMakes
ContentsofThisBook
ConventionsUsedinThisBook

UsingCodeExamples
CommentsandQuestions
Safari®Enabled
Acknowledgments
Chapter1.IntroductiontoPHP
Section1.1.WhatDoesPHPDo?
Section1.2.ABriefHistoryofPHP
Section1.3.InstallingPHP
Section1.4.AWalkThroughPHP
Chapter2.LanguageBasics
Section2.1.LexicalStructure
Section2.2.DataTypes
Section2.3.Variables
Section2.4.ExpressionsandOperators
Section2.5.Flow-ControlStatements
Section2.6.IncludingCode
Section2.7.EmbeddingPHPinWebPages
















































































Chapter3.Functions
Section3.1.CallingaFunction
Section3.2.DefiningaFunction
Section3.3.VariableScope
Section3.4.FunctionParameters
Section3.5.ReturnValues
Section3.6.VariableFunctions
Section3.7.AnonymousFunctions
Chapter4.Strings
Section4.1.QuotingStringConstants
Section4.2.PrintingStrings
Section4.3.AccessingIndividualCharacters
Section4.4.CleaningStrings
Section4.5.EncodingandEscaping
Section4.6.ComparingStrings
Section4.7.ManipulatingandSearchingStrings
Section4.8.RegularExpressions
Section4.9.POSIX-StyleRegularExpressions
Section4.10.Perl-CompatibleRegularExpressions
Chapter5.Arrays
Section5.1.IndexedVersusAssociativeArrays
Section5.2.IdentifyingElementsofanArray
Section5.3.StoringDatainArrays
Section5.4.MultidimensionalArrays
Section5.5.ExtractingMultipleValues
Section5.6.ConvertingBetweenArraysandVariables

Section5.7.TraversingArrays
Section5.8.Sorting
Section5.9.ActingonEntireArrays
Section5.10.UsingArrays
Chapter6.Objects
Section6.1.Terminology
Section6.2.CreatinganObject
Section6.3.AccessingPropertiesandMethods
Section6.4.DeclaringaClass
Section6.5.Introspection
Section6.6.Serialization
Chapter7.WebTechniques
Section7.1.HTTPBasics
















































































Section7.2.Variables
Section7.3.ServerInformation
Section7.4.ProcessingForms
Section7.5.SettingResponseHeaders
Section7.6.MaintainingState
Section7.7.SSL
Chapter8.Databases
Section8.1.UsingPHPtoAccessaDatabase
Section8.2.RelationalDatabasesandSQL
Section8.3.PEARDBBasics
Section8.4.AdvancedDatabaseTechniques
Section8.5.SampleApplication
Chapter9.Graphics
Section9.1.EmbeddinganImageinaPage
Section9.2.TheGDExtension
Section9.3.BasicGraphicsConcepts
Section9.4.CreatingandDrawingImages
Section9.5.ImageswithText
Section9.6.DynamicallyGeneratedButtons
Section9.7.ScalingImages
Section9.8.ColorHandling
Chapter10.PDF
Section10.1.PDFExtensions
Section10.2.DocumentsandPages
Section10.3.Text
Chapter11.XML
Section11.1.LightningGuidetoXML
Section11.2.GeneratingXML
Section11.3.ParsingXML
Section11.4.ParsingXMLwithDOM

Section11.5.ParsingXMLwithSimpleXML
Section11.6.TransformingXMLwithXSLT
Section11.7.WebServices
Chapter12.Security
Section12.1.FilterInput
Section12.2.EscapeOutput
Section12.3.Cross-SiteScripting
Section12.4.SessionFixation
Section12.5.FileUploads












































































Section12.6.FileAccess
Section12.7.PHPCode
Section12.8.ShellCommands
Section12.9.MoreInformation
Section12.10.SecurityRecap
Chapter13.ApplicationTechniques
Section13.1.CodeLibraries

Section13.2.TemplatingSystems
Section13.3.HandlingOutput
Section13.4.ErrorHandling
Section13.5.PerformanceTuning
Chapter14.ExtendingPHP
Section14.1.ArchitecturalOverview
Section14.2.WhatYou'llNeed
Section14.3.BuildingYourFirstExtensions
Section14.4.Theconfig.m4File
Section14.5.MemoryManagement
Section14.6.Thepval/zvalDataType
Section14.7.ParameterHandling
Section14.8.ReturningValues
Section14.9.References
Section14.10.GlobalVariables
Section14.11.CreatingVariables
Section14.12.ExtensionINIEntries
Section14.13.Resources
Section14.14.WheretoGofromHere
Chapter15.PHPonWindows
Section15.1.InstallingandConfiguringPHPonWindows
Section15.2.WritingPortableCodeforWindowsandUnix
Section15.3.InterfacingwithCOM
Section15.4.InteractingwithODBCDataSources
AppendixA.FunctionReference
SectionA.1.PHPFunctionsbyCategory
SectionA.2.AlphabeticalListingofPHPFunctions
AppendixB.ExtensionOverview
SectionB.1.OptionalExtensionsListing
AbouttheAuthor

Colophon
Index


ProgrammingPHP,SecondEdition
byRasmusLerdorf,KevinTatroe,andPeterMacIntyre
Copyright©2006,2002O'ReillyMedia,Inc.Allrightsreserved.
PrintedintheUnitedStatesofAmerica.
PublishedbyO'ReillyMedia,Inc.,1005GravensteinHighway
North,Sebastopol,CA95472.
O'Reillybooksmaybepurchasedforeducational,business,or
salespromotionaluse.Onlineeditionsarealsoavailablefor
mosttitles(safari.oreilly.com).Formoreinformation,contact
ourcorporate/institutionalsalesdepartment:(800)998-9938or

Editor:

TatianaApandiandAllisonRandal

ProductionEditor:

MattHutchinson

ProductionServices:

GEX,Inc.

CoverDesigner:

EllieVolckhausen


InteriorDesigner:

DavidFutato

Illustrators:

RobertRomano,JessamynRead,andLesleyBorash

PrintingHistory:



March2002:

FirstEdition.


April2006:

SecondEdition.

NutshellHandbook,theNutshellHandbooklogo,andthe
O'ReillylogoareregisteredtrademarksofO'ReillyMedia,Inc.
ProgrammingPHP,theimageofacuckoo,andrelatedtrade
dressaretrademarksofO'ReillyMedia,Inc.
Manyofthedesignationsusedbymanufacturersandsellersto
distinguishtheirproductsareclaimedastrademarks.Where
thosedesignationsappearinthisbook,andO'ReillyMedia,Inc.
wasawareofatrademarkclaim,thedesignationshavebeen

printedincapsorinitialcaps.
Whileeveryprecautionhasbeentakeninthepreparationofthis
book,thepublisherandauthorsassumenoresponsibilityfor
errorsoromissions,orfordamagesresultingfromtheuseof
theinformationcontainedherein.
ISBN:0-596-00681-0
[M]


Foreword
Today,PHPisthemostwidelyusedprogramminglanguageon
theWeb,withover40percentofallwebapplicationswrittenin
PHP.Itisinstalledonover22milliondomainservers(source:
Netcraft),asshowninFigureF-1.Thenumberofdevelopers
usingPHPhasnowreachedover2.5million.Thecommunity
developingPHPisveryimpressive,withover450CVS
committerswhowroteatotalof1millionlinesofcode.ThePHP
communityisoneofthemostdynamic,withthousandsof
peoplesharingcode,evangelizingaboutPHP,supportingeach
other,andcreatingmanyprojectssuchasWikipedia,Mambo,
PHP-Nuke,FUDforum,SugarCRM,andHorde,justtomentiona
few.

FigureF-1.PHPdevelopmenttimelinewithusage

ItssimplicityiswhatmadePHPsosuccessful.Simplicityequals
lesscode.Developersandcompanieshavebeendeveloping


projectswithPHPinafractionofthetimeitwouldtakeanother

language.
Thereisanunacknowledgedwarthatgoesoneveryday
intheworldofprogramming.Itisawarbetweenthe
humansandthecomputerscientists.Itisawarbetween
thosewhowantsimple,sloppy,flexible,humanwaysto
writecodeandthosewhowantclean,crisp,clear,correct
waystowritecode.ItisthewarbetweenPHPand
C++/Java.
AdamBosworth
Google
ThefutureofPHPlooksverybright.Leadingplatformvendors
suchasIBM,Oracle,MySQL,Intel,and,mostrecently,RedHat
haveallendorsedit.ThenewCollaborationProjectinitiatedby
ZendTechnologiesralliesmanyleadingcompaniesand
communitymembersaroundnewopensourceinitiativesaimed
attakingPHPtothenextlevelbycreatinganindustrial-grade,
defactostandardPHPwebapplicationdevelopmentand
deploymentenvironment.TheProject'sfirsttwoopeninitiatives
are:

ZendPHPFramework
Thisisawebapplicationframeworkthatwillaccelerateand
improvethedevelopmentanddeploymentofmissioncriticalPHPwebapplications.

SupportfortheEclipseDevelopmentplatform
ZendisjoiningtheEclipseFoundationasaStrategic
Developer.Itwilldevelop,incollaborationwithpartners,a


PHPIDEbasedontheEclipseplatform.

RasmusLerdorf,theinitialcreatorofthefirstversionofPHP
(thencalledPHP/FI),andKevinTatroeprovidedtheguidelines
forthisbook.ThenewestauthorontherevisionprojectisPeter
MacIntyre,aZendCertifiedEngineerwithmorethanfiveyears
experienceinPHP.WezFurlongandChrisShifletthavealso
contributedtothisbook.Wezmodernizedthe"ExtendingPHP"
chapter,andChrisbroughthisrenownedexpertiseinupdating
the"Security"chapter.
Thisbookisamust-haveforanybodyworkingwithPHP.Some
ofthemostrecognizablenamesinthePHPcommunityhave
contributedtoit.Soyouknowthatyouaregettingquality
information.ItcoversalloftheimportantPHPtopics,plus
uniqueissuessuchasextendingandsecuringPHP,and
discussesnewerfeaturesofXMLandObjectsandPDO.
MichelGerin
VicePresident,Marketing
ZendTechnologies,Inc.,thePHPCompany




Preface
Nowmorethanever,theWebisamajorvehicleforcorporate
andpersonalcommunications.Websitescarrysatelliteimages
ofEarthinitsentirety,searchforlifeinouterspace,andhouse
personalphotoalbums,businessshoppingcarts,andproduct
lists.ManyofthosewebsitesaredrivenbyPHP,anopensource
scriptinglanguageprimarilydesignedforgeneratingHTML
content.
Sinceitsinceptionin1994,PHPhasswepttheWeband

continuesitsphenomenalgrowthwithrecentendorsementsby
IBMandORACLEcorporations(tonameafew).Also,the
millionsofwebsitespoweredbyPHParetestamenttoits
popularityandeaseofuse.Itliesinthesweetspotbetween
Perl/CGI,ActiveServerPages(ASP),andHTML.Everyday
peoplecanlearnPHPandcanbuildpowerfuldynamicwebsites
withit.MarcAndreessen,chairmanofOpswareInc.and
founderofNetscapeCommunications,recentlydescribedPHPas
havingreplacedJavaastheidealprogramminglanguageforthe
Web.
ThecorePHPlanguage(Version5+)featurespowerfulstringandarray-handlingfacilities,aswellasgreatlyimproved
supportforobject-orientedprogramming.Withtheuseof
standardandoptionalextensionmodules,aPHPapplicationcan
interactwithadatabasesuchasMySQLorOracle,drawgraphs,
createPDFfiles,andparseXMLfiles.Youcanwriteyourown
PHPextensionmodulesinCforexample,toprovideaPHP
interfacetothefunctionsinanexistingcodelibrary.Youcan
evenrunPHPonWindows,whichletsyoucontrolother
WindowsapplicationssuchasWordandExcelwithCOMor
interactwithdatabasesusingODBC.
ThisbookisaguidetothePHPlanguage.Whenyoufinishit,
youwillknowhowthePHPlanguageworks,howtousethe


manypowerfulextensionsthatcomestandardwithPHP,and
howtodesignandbuildyourownPHPwebapplications.


Audience
PHPisameltingpotofcultures.Webdesignersappreciateits

accessibilityandconvenience,whileprogrammersappreciateits
flexibility,power,diversity,andspeed.Bothculturesneeda
clearandaccuratereferencetothelanguage.Ifyouarea
programmer,thenthisbookisforyou.Weshowthebigpicture
ofthePHPlanguage,andthendiscussthedetailswithout
wastingyourtime.Themanyexamplesclarifytheexplanations,
andthepracticalprogrammingadviceandmanystyletipswill
helpyoubecomenotjustaPHPprogrammer,butagoodPHP
programmer.
Ifyou'reawebdesigner,youwillappreciatetheclearand
usefulguidestospecifictechnologies,suchasXML,sessions,
PDFgeneration,andgraphics.Andyou'llbeabletoquicklyget
theinformationyouneedfromthelanguagechapters,which
explainbasicprogrammingconceptsinsimpleterms.
Thisbookhasbeenfullyrevisedtocoverthelatestfeaturesof
PHPVersion5.Wehaveendeavoredtoeventalkaboutsomeof
thefeaturesthatwerestillonthedrawingboardwhilewewere
writingthisedition.OnefeatureinparticularisthenewPDO
databaseinterfacethatwasstillindevelopmentduringour
writing,butwefeltitimportantenoughtocoverinthe
discussionondatabases(Chapter8).




AssumptionsThisBookMakes
ThisbookassumesyouhaveaworkingknowledgeofHTML.If
youdon'tknowHTML,youshouldgainsomeexperiencewith
simplewebpagesbeforeyoutrytotacklePHP.Formore
informationonHTML,werecommendHTML&XHTML:The

DefinitiveGuidebyChuckMuscianoandBillKennedy(O'Reilly).


ContentsofThisBook
We'vearrangedthematerialinthisbooksothatyoucaneither
readitfromstarttofinishorjumparoundtohitjustthetopics
thatinterestyou.Thebookisdividedinto15chaptersand2
appendixes,asfollows:

Chapter1,IntroductiontoPHP
TalksaboutthehistoryofPHPandgivesalightning-fast
overviewofwhatispossiblewithPHPprograms.

Chapter2,LanguageBasics
IsaconciseguidetoPHPprogramelementssuchas
identifiers,datatypes,operators,andflow-control
statements.

Chapter3,Functions
Discussesuser-definedfunctions,includingscope,variablelengthparameterlists,andvariableandanonymous
functions.

Chapter4,Strings
Coversthefunctionsyou'llusewhenbuilding,dissecting,
searching,andmodifyingstringsinyourPHPcode.


Chapter5,Arrays
Detailsthenotationandfunctionsforconstructing,
processing,andsortingarraysinyourPHPcode.


Chapter6,Objects
CoversPHP'supdatedobject-orientedfeatures.Inthis
chapter,you'lllearnaboutclasses,objects,inheritance,and
introspection.

Chapter7,WebTechniques
Discusseswebbasicssuchasformparametersand
validation,cookies,andsessions.

Chapter8,Databases
DiscussesPHP'smodulesandfunctionsforworkingwith
databases,usingthePEARDBlibraryandtheMySQL
databaseasexamples.Also,thenewSQLitedatabase
engineandthenewPDOdatabaseinterfacearecovered.

Chapter9,Graphics
Demonstrateshowtocreateandmodifyimagefilesina
varietyofformatsfromwithinPHP.


Chapter10,PDF
ExplainshowtocreatedynamicPDFfilesfromaPHP
application.

Chapter11,XML
IntroducesPHP'supdatedextensionsforgeneratingand
parsingXMLdata.

Chapter12,Security

Providesvaluableadviceandguidanceforprogrammers
creatingsecurescripts.You'lllearnbestpractices
programmingtechniquesherethatwillhelpyouavoid
mistakesthatcanleadtodisaster.

Chapter13,ApplicationTechniques
TalksabouttheadvancedtechniquesthatmostPHP
programmerseventuallywanttouse,includingerror
handlingandperformancetuning.

Chapter14,ExtendingPHP
Anadvancedchapterthatpresentseasy-to-follow
instructionsforbuildingaPHPextensioninC.

Chapter15,PHPonWindows


DiscussesthetricksandtrapsoftheWindowsportofPHP.
ItalsodiscussesthefeaturesuniquetoWindows,suchas
COMandODBC.

AppendixA,FunctionReference
AhandyquickreferencetoallthecorefunctionsinPHP.

AppendixB,ExtensionOverview
DescribesthestandardextensionsthatshipwithPHP.





ConventionsUsedinThisBook
Thefollowingtypographicalconventionsareusedinthisbook:

Plaintext
Indicatesmenutitles,menuoptions,menubuttons,and
keyboardaccelerators(suchasAltandCtrl).

Italic
Indicatesnewterms,URLs,emailaddresses,filenames,file
extensions,pathnames,directories,andUnixutilities.

Constantwidth
Indicatescommands,options,switches,variables,
attributes,keys,functions,types,classes,namespaces,
methods,modules,properties,parameters,values,objects,
events,eventhandlers,XMLtags,HTMLtags,macros,the
contentsoffiles,ortheoutputfromcommands.

Constantwidthbold
Showscommandsorothertextthatshouldbetyped
literallybytheuser.

Constantwidthitalic


Showstextthatshouldbereplacedwithuser-supplied
values.

Thisiconsignifiesatip,suggestion,orgeneralnote.


Thisiconindicatesawarningorcaution.




UsingCodeExamples
Thisbookisheretohelpyougetyourjobdone.Ingeneral,you
mayusethecodeinthisbookinyourprogramsand
documentation.Youdonotneedtocontactusforpermission
unlessyou'rereproducingasignificantportionofthecode.For
example,writingaprogramthatusesseveralchunksofcode
fromthisbookdoesnotrequirepermission.Sellingor
distributingaCD-ROMofexamplesfromO'Reillybooksdoes
requirepermission.Answeringaquestionbycitingthisbook
andquotingexamplecodedoesnotrequirepermission.
Incorporatingasignificantamountofexamplecodefromthis
bookintoyourproduct'sdocumentationdoesrequire
permission.
Weappreciate,butdonotrequire,attribution.Anattribution
usuallyincludesthetitle,author,publisher,andISBN.For
example:"ProgrammingPHP,SecondEdition,byRasmus
Lerdorf,KevinTatroe,andPeterMacIntyre.Copyright2006
O'ReillyMedia,Inc.,0-596-00681-0."
Ifyoufeelyouruseofcodeexamplesfallsoutsidefairuseor
thepermissionprovided,feelfreetocontactusat






CommentsandQuestions
Pleaseaddresscommentsandquestionsconcerningthisbookto
thepublisher:
O'ReillyMedia,Inc.
1005GravensteinHighwayNorth
Sebastopol,CA95472
(800)998-9938(intheUnitedStatesorCanada)
(707)829-0515(internationalorlocal)
(707)829-0104(fax)
Wehaveawebpageforthisbook,wherewelisterrata,
examples,andanyadditionalinformation.Youcanaccessthis
pageat:
/>Tocommentorasktechnicalquestionsaboutthisbook,send
emailto:

Formoreinformationaboutourbooks,conferences,Resource
Centers,andtheO'ReillyNetwork,seeourwebsiteat:





Safari®Enabled

WhenyouseeaSafari®Enabledicononthecoverof
yourfavoritetechnologybook,thatmeansthebookisavailable
onlinethroughtheO'ReillyNetworkSafariBookshelf.
Safarioffersasolutionthat'sbetterthane-books.It'savirtual
librarythatletsyoueasilysearchthousandsoftoptechbooks,
cutandpastecodesamples,downloadchapters,andfindquick

answerswhenyouneedthemostaccurate,currentinformation.
Tryitforfreeat.




Acknowledgments
RasmusLerdorf
Iwouldliketoacknowledgethelargeandwonderfully
boisterousPHPcommunity,withoutwhichtherewouldbeno
PHPtoday.

KevinTatroe
ThankstoeveryindividualwhoevercommittedcodetoPHPor
whowrotealineofcodeinPHPyouallmadePHPwhatitis
today.
Tomyparents,whooncepurchasedasmallLEGOsetforalong
andfrighteningplanetrip,beginninganobsessionwith
creativityandorganizationthatcontinuestorelaxandinspire.
Finally,aheapingsecondspoonfulofgratitudetoJenniferand
Hadden,whocontinuetoinspireandencouragemeevenasI
poundoutwordsandcodeeveryday.

PeterMacIntyre
IwouldfirstliketopraisetheLordofHostswhogivesmethe
strengthtofaceeachday.HecreatedelectricitythroughwhichI
makemylivelihood;thanksandpraisetoHimforthistotally
uniqueandfascinatingportionofHiscreation.
Closertohome,IwouldliketothankRasmusfortheinitial(and
continuing)effortsbehindthisgreatlanguagecalledPHP.Ihave



×