Tải bản đầy đủ (.pdf) (484 trang)

Premier press PHP essentials 2nd edition

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 (2.7 MB, 484 trang )

PHPEssentials,Second
Edition
ISBN:1931841349
byJulieC.
Meloni
PremierPress©2003(326pages)
Thistextservesasan
introductiontothePHP
scriptinglanguageand
providesreal-worldexamples
ofcommonuses--from
downloading,installingand
configuringaWebserver
withPHP,tocreating
dynamiccontentvia
databaseinterfacesand
more.
TableofContents BackCover
TableofContents
PHPEssentials,SecondEdition
Introduction
Chapter1 - GettingStartedwithPHP
Chapter2 - BasicPHPTechniques
Chapter3 - WorkingwithDatabases
CreatingandPopulating
Chapter4 DatabaseTables
Chapter5 - UserAuthentication
UserTrackingand
Chapter6 -



SessionManagement
AdvancedPHP
Chapter7 - Techniques:Web-Based
DatabaseAdministration
AdvancedPHP
Chapter8 - Techniques:Workingwith
Images
AdvancedPHP
Chapter9 - Techniques:Workingwith
XML
EssentialPHPLanguage
AppendixA Reference
AppendixB - GettingSupport
Index
ListofFigures
ListofTables



PHPEssentials,Second
Edition
ISBN:1931841349
byJulieC.
Meloni
PremierPress©2003(326pages)
Thistextservesasan
introductiontothePHP
scriptinglanguageand
providesreal-worldexamples
ofcommonuses--from

downloading,installingand
configuringaWebserver
withPHP,tocreating
dynamiccontentvia
databaseinterfacesand
more.
TableofContents

BackCover

BackCover
DiveintotheneweditionofthispopularguidetoPHP.
Withatruefocusontheessentials,thisbookgivesyou
thesolidfoundationinPHPprogrammingyou’re
lookingfor.Andyoudon’thavetobeacomputer
scientistorprogrammertolearnfromit!Thesimple,
learn-by-exampleformatofPHPEssentialswillallow
youtoquicklyusethepowerofPHPtodevelop
successful,dynamicWebsites.


LearnFaster
StartwithPHPbasicslikeparsing,workingwith
arrays,anddisplayingdynamiccontent
UsePHPtoplananddisplayane-commerce
productcatalogandtoensuresafeandsecure
shopping
MasteradvancedPHPgraphicstechniquessuchas
creatingnewimagesandscalingexistingimages
InstallaWebserver—forWindowsorLinux—and

adddatabasesupport
LearnMore
Learnhowtoestablishvariousdatabase
connectionswithPHP,includingMySQL,
PostgreSQL,andOracle
UsePHPtocreateadatabasetableandedityour
data
Masterusertrackingandsessionmanagement
techniques
UsethePHPLanguageReferencetoansweryour
questionsaboutsyntax,variables,built-in
functions,andmore!
AbouttheAuthor
JulieC.Meloniisthetechnicaldirectorfori2i
interactive—amultimediacompanylocatedinLos
Altos,California.Sheisalsotheauthorofseveral
booksandarticlesonWeb-basedprogramming
languagesanddatabasetopics,includingthefirst
editionofPHPEssentialsfromPremierPress.








PHPEssentials,SecondEdition
JulieMeloni


Copyright©2003byPremierPress,adivisionofCourseTechnology.
Allrightsreserved.Nopartofthisbookmaybereproducedortransmitted
inanyformorbyanymeans,electronicormechanical,including
photocopying,recording,orbyanyinformationstorageorretrieval
systemwithoutwrittenpermissionfromPremierPress,exceptforthe
inclusionofbriefquotationsinareview.
ThePremierPresslogoandrelatedtradedressaretrademarksof
PremierPressandmaynotbeusedwithoutwrittenpermission.
PHPwaswrittenbythePHPDevelopmentTeam,andreleasedunderthe
GNUGeneralPublicLicense(GPL).
Allothertrademarksarethepropertyoftheirrespectiveowners.
Important: PremierPresscannotprovidesoftwaresupport.Please
contacttheappropriatesoftwaremanufacturer'stechnical
supportlineorWebsiteforassistance.
PremierPressandtheauthorhaveattemptedthroughoutthisbookto
distinguishproprietarytrademarksfromdescriptivetermsbyfollowingthe
capitalizationstyleusedbythemanufacturer.
InformationcontainedinthisbookhasbeenobtainedbyPremierPress
fromsourcesbelievedtobereliable.However,becauseofthepossibility
ofhumanormechanicalerrorbyoursources,PremierPress,orothers,
thePublisherdoesnotguaranteetheaccuracy,adequacy,or
completenessofanyinformationandisnotresponsibleforanyerrorsor


omissionsortheresultsobtainedfromuseofsuchinformation.Readers
shouldbeparticularlyawareofthefactthattheInternetisaneverchangingentity.Somefactsmayhavechangedsincethisbookwentto
press.
ISBN:1-931841-34-9
LibraryofCongressCatalogCardNumber:2003101207
PrintedintheUnitedStatesofAmerica

0304050607BH10987654321
PremierPress,adivisionofCourseTechnology
25ThomsonPlace
Boston,MA02210
Publisher
StacyL.Hiquet
SeniorMarketingManager
MartineEdwards
MarketingManager
HeatherHurley
ManagerofEditorialServices
HeatherTalbot
AcquisitionsEditor
ToddJenson
ProjectEditor
EstelleManticas
TechnicalReviewer
MichelleJones
CopyEditor
EstelleManticas


InteriorLayout
MarianHartsough
CoverDesigner
MikeTanamachi
Indexer
SharonShock
Proofreader
SeanMedlock

Acknowledgments
ThanksasalwaystothePHPGroup,ZendTechnologies,theApache
SoftwareFoundationandMySQLABforcreatingandmaintainingsuch
wonderfulandaccessibleproductsforallusers.
ThankstoeverysinglePHPuseranddeveloper,becausewithoutyou,I
wouldn'thaveanythingtowriteabout.
Enormousthankstoeveryoneati2iInteractive,fortheirnever-ending
supportandencouragement.
AbouttheAuthor
JULIEMELONIisthetechnicaldirectorfori2iInteractive,amultimedia
companylocatedinLosAltos,California.She'sbeendevelopingWebbasedapplicationssincetheWebfirstsawthelightofdayand
rememberstheexcitementsurroundingthefirstGUIWebbrowser.Sheis
theauthorofseveralbooksandarticlesonWeb-basedprogramming
languagesanddatabasetopics,andyoucanfindtranslationsofherwork
inmanydifferentlanguages,includingChinese,Danish,Finnish,Italian,
Portuguese,PolishandevenSerbian.







Introduction
IfyoucomparethisbooktomostoftheotherbooksonPHP,you'llquickly
noticethatthisbookismuchsmallerthanthosethousand-page
behemoths.Therelativesmallnessofthisbookisintentional-I'vefound
it'seasiertolearnfromabookyoucanactuallyhold!
Thatbeingsaid,plentyoftopicsthatarecoveredinthoselengthierbooks
arenotcoveredinthisbook.Thisbookoffers,asitstitle,saysthe

essentialinformation.Inotherwords,informationthatwillprovideasolid
foundationfortheadditionaltopicsyouwillfindinlonger,moreadvanced
books.
Amaincharacteristicofthisbook,besidesteachingthefundamentals,is
thatyoudon'thavetobeacomputerscientistorprogrammertolearn
fromit.Ifyouareacomputerscientistorprogrammeralready,youmay
notliketheratherprosaicnatureoftheexplanationsandinstructionsin
thisbook.Ultimately,Iwantedtowriteabookthatsomeonecouldtakeoff
theshelf,skimthrough,andsay,"Hey,thisPHPthinglookslikeaneat
language,andever-so-easytolearn!"Becauseitis!
Ifyou'vebeenprogrammingwithPHPsincethebeginningoftime,there's
probablynotmuchyoucangetoutofthisbook,excepttohandittoyour
bossandsay,"Look!Anotherbookonwhatawonderfullanguagethisis.
CanwepleasestopusingASP/ColdFusion/Java/Perl/C++andmigrate
toPHP?"Butifyou'vejustdabbledwithPHPorhaveneverseenaPHP
script,Iamcertainthisbookwillbeofsomeusetoyou.


SupplementalWebSite
Additionalinformationforthisbook(andforotherbooksI'vewritten)can
befoundatAtthissiteyoucandownloadall
thecodesamplesinthisbook,aswelladditionaltutorialsand
notificationsofanyerrorsinthebook.Youcanalsousethesitetoget
helpwithanyproblemsyoumayhavewiththeexamples.








GettingStartedwithPHP
Whetheryou'reafirst-timeprogrammeroryouhaveafewyearsofWeb
applicationdevelopmentunderyourbelt,you'llfindsomethingusefulin
thisbook.Hopefully,whatyou'llfindisasimple"learn-by-example"path
todevelopingsuccessfuldynamicWebsites.
UnliketheWebitself,thisbookisfairlylinear.You'llstartbyinstallingthe
softwareneededtousePHP,andthenyou'llgraduallymoveinto"Hello
World!"scriptsandeventuallycreateshoppingcartsandotherdatabasedrivenapplications.
IfyouhaveanaccountwithanInternetServiceProviderwhohas
enabledtheuseofPHPforallusersontheserver,youcanskipaheadto
Chapter2.ButasyoucaninstallfreelyavailableWebservers,PHP,and
adatabsseortwoonyourownmachine-withalittlepokingandproddingIrecommendyoudoso.It'sagreatwaytolearnthe"guts"ofthetools
you'llbeusing.







WhatIsPHP?
PHPisaserver-sidescriptinglanguage.WhenyourWebbrowser
accessesaURL,itismakingarequesttoaWebserver.Ifyouare
requestingaPHPpage,somethinglike
theWebserverwakesupthe
PHPparsingengineandsays,"Hey!You'vegottodosomethingbeforeI
sendaresultbacktothisperson'sWebbrowser."ThePHPparsing
enginerunsthroughthePHPcodefoundinthehome.phpfileandreturns
theresultingoutput.ThisoutputispassedbacktotheWebserverasthe

HTMLcodeinthedocument,whichinturnispassedontoyourbrowser,
whichdisplaysittoyou.

ABriefHistoryofPHP
In1994,anincrediblyforward-thinkingmannamedRasmusLerdorf
developedasetoftoolsthatusedaparsingenginetointerpretafew
macroshereandthere.Theywerenotextravagant:aguestbook,a
counter,andsomeother"homepage"elementsthatwerecoolwhenthe
Webwasinitsinfancy.Heeventuallycombinedthesetoolswithaform
interpretation(FI)packagehehadwritten,addedsomedatabase
support,andreleasedwhatwasknownasPHP/FI.
Then,inthespiritofOpenSourcesoftwaredevelopment,developersall
overtheworldbegancontributingtoPHP/FI.By1997,morethan50,000
WebsiteswereusingPHP/FItoaccomplishdifferenttasks-connectingto
adatabase,displayingdynamiccontent,andsoon.
Atthatpoint,thedevelopmentprocessreallystartedbecomingateam
effort.WithprimaryassistancefromdevelopersZeevSuraskiandAndi
Gutmans,theversion3.0parserwascreated.ThefinalreleaseofPHP3
occurredinJuneof1998,whenitwasupgradedtoincludesupportfor
multipleplatforms(it'snotjustforLinuxanymore!)andWebservers,
numerousdatabases,andSNMP(SimpleNetworkManagement
Protocol)andIMAP(InternetMessageAccessProtocol).
AfterPHP3.0wasreleased,theaforementionedSuraskiandGutmans
begantodevelopasuper-fastenginetoreplacethecoreelementsof


PHP,andinmid-1999theZendEnginewasborn.PHP4.0wasbasedon
thisengine,andwasreleasedintheSpringof2000.Thisreleasewasa
watershedforPHP-thevastamountofnewfeatuesandincresed
performanceresultsnowfoundinPHP4.0madeitaviabletoolfor

advancedWebapplicationdevelopment.ThecurrentversionisPHP4.3,
whichyou'lllearntoinstallinChapter1,"GettingStartedwithPHP."
Inthethreeyearsbetweentheappearance,inearly2000,ofthefirst
editionofthisbookandthisnewestedition,PHPusagehasexploded.
CompanieslikeAmazon.comandYahoo!usePHPinvariousareasof
theirWebsites.That'sdefinitelyhighpraise!Themostrecentsurveyfrom
Netcraft(showPHPisinstalledonover9.5
milliondomains.ItiscommonplaceforInternetServiceProviderstooffer
PHPandMySQLineventhemostbasic(orfree!)hostingpackages,and
PHPsourcecodeisshippedwithmostLinuxdistributions.
Additionally,therearehundredsofbookswhichaddressPHP
developmentinsomeway-amarkedincreasefromthefiveorsowhich
wereavailablewhenthefirsteditionofthisbookwaspublished.Thetens
ofthousandsofdeveloperswhouseandcontributetoPHPhavemade
thissimplelanguagenear-revolutionary,andthosenumberscontinueto
grow.

WhatDoesPHPDo?
PHPdoesanythingyouwant,exceptsitonitsheadandspin.Actually,
withalittleon-the-flyimagemanipulationandDynamicHTML,itcan
probablydothat,too.
AccordingtothePHPManual,"ThegoalofthelanguageistoallowWeb
developerstowritedynamicallygeneratedpagesquickly."
ThelistbelowshowsomecommonusesofPHP.Thisisbynomeansa
completelist,anddoesn'tindicateanyofthemoreadvancedfunctionality
thatdevelopersuseinlargeapplications;it'sjustanideaoftheitemsthat
youraveragedevelopermayuseonadailybasis.
Performsystemfunctions:create,open,readfrom,writeto,and



closefilesonyoursystem,executesystemcommands,create
directories,andmodifypermissions.
Gatherdatafromforms:savethedatatoafile,senddataviaemail,returnmanipulateddatatotheuser.
Accessdatabasesandgeneratecontenton-the-fly,orcreatea
Webinterfaceforadding,deleting,andmodifyingelementswithin
yourdatabase.
Setcookiesandaccesscookievariables.
UsePHPuserauthenticationtorestrictaccesstosectionsofyour
Website.
Createimageson-the-fly.
Encryptdata.

ANoteRegardingOpenSourceDevelopment
OpenSourcesoftwaremustfollowthesecriteria(theyareavailablein
detailat />Freeredistribution.
Theprogrammustincludesourcecodeandmustallow
distributioninsourcecodeaswellascompiledform.
Thelicensemustallowmodificationsandderivedworks.
Integrityoftheauthor'ssourcecode.
Nodiscriminationagainstpersonsorgroups.
Nodiscriminationagainstfieldsofendeavor.
Distributionoflicense.
Licensemustnotbespecifictoaproduct.


Licensemustnotcontaminateothersoftware.
PHPisafineexampleofOpenSourcedevelopmentanddistribution.
Otherexamplesincludethefollowing:
Apache.TheWebServerofchoiceformorethan4.8millionWeb
sites.

Linux.Theoperatingsystemofchoiceformorepeoplethan
Microsoftwouldhaveyouthink.
BIND.ThesoftwareprovidingDomainNameServicestothe
Internet-allofit.
Sendmail.Themostwidely-usedsoftwarefortransportinge-mail
fromsendertorecipient.
Synonymouswith"OpenSource"is"volunteerism."Developers
contributingtoOpenSourcesoftwaredon'tdirectlymakemoneyfrom
doingso.Whereverpossible,contributetoyourfavoriteOpenSource
organization,beitthePHPGrouporsomeoneelse.Givebacksometime
byansweringquestions,helpingwithdocumentation,contributingcode
wherepossible,orevenmakingamonetarydonation.Thecostof
equipment,connectivity,tools,and,mostimportantly,brainpoweris
absorbeddirectlybythevolunteerdeveloper,sothatyouandIhavea
freely(andwidely)availablepieceofsoftware.







IsPHPRightforMe?
OnlyyoucandecideifPHPshouldbeyourlanguageofchoice,whether
you'redevelopingsitesforpersonalorcommercialuseonasmallor
largescale.Icanonlytellyouthatinthecommercialrealm,I'veworked
withallthepopularserver-sidescriptinglanguages-ActiveServerPages
(ASP),ColdFusion,JavaServerPages(JSP),Perl,andPHP-on
numerousplatformsandvariousWebservers,withvariousdegreesof
success.PHPistherightchoiceforme:it'sflexible,fast,andsimplisticin

itsrequirementsyetpowerfulinitsoutput.
BeforedecidingwhethertousePHPinalarge-scaleorcommercial
environment,consideryouranswerstothefollowingquestions:
WillyoualwaysusethesameWebserverhardwareand
software?Ifnot,lookforsomethingcross-platformandavailable
formultipleWebservers:PHP.
Willyoualwayshavetheexactsamedevelopmentteam,
comprisedentirelyofASP(orColdFusion)developers?Orwill
youusewhoeverisavailable,thusnecessitatingalanguagethat
iseasytolearnandsyntacticallysimilartoCandPerl?Ifyou
havereasontobelievethatyourASPorColdFusiondevelopers
mightdropoffthefaceoftheearth,don'tusethosetools;use
PHP.
Arememoryandserverloadanissue?Ifso,don'tusebloated
third-partysoftwarethatleakspreciousmemory;usePHP.
Thereareplentyofotherquestionstoaskyourselfwhenmakinga
decisionregardingadevelopmentlanguage,andinshortIcanonlysay
"Tryit,you'lllikeit!"







Chapter1:GettingStartedwithPHP
ThischapterwillwalkyouthroughthebasicsofgettingPHPandaWeb
serverupandrunningonyoursystem,andwillshowyouhowtoadd
databasesupportaswell.Youmayormaynotneedtoreadthisentire
chapter-ifyoudon'tplantoinstallMicrosoftIIS,then,don'tworryabout

readingthatsection.
Nomatterwhatsectionorsectionsyouchoosetoread,pleasepayclose
attentiontotheinstructionsgiven.Theinstallationisnotdifficult,butitis
importanttofollowthestepsclosely.Missingoneinstructionwillresultin
frustrationonyourpartandangrye-mailsinmyinbox,bothofwhichI'd
liketoavoid!


InstallingaWebServer
Inthissection,you'lllearntoinstallApacheonLinux/UNIXorWindows,
andyou'llalsolearnthebasicsofgettingandinstallingotherWeb
servers,suchasMicrosoftIIS.Personally,Ineverinstallanythingother
thanApache,evenifit'sonmypersonalWindowsmachines.Butifyou
wanttoinstallMicrosoftIISoranotherWebserver,feelfree!Someother
Webserverswillbediscussedattheendofthissection.
ThroughouttheApacheinstallationsections,theinstructionsassumeyou
knowthebasicsofadministeringeitherLinux/UNIXorWindows.Ifyou
don'tknowanythingaboutthecommandline,orhaveneverloggedonas
AdministratortoaWindowsmachine,youshouldtakeastepbackand
brushuponyoursystemadministratorskillsbeforecontinuing.

WorkingwithApache
TheApacheWebserverisanopen-sourceprojectproducedand
maintainedbytheApacheSoftwareFoundation.Since1996,Apachehas
beenthemostpopularWebserverinuseontheInternet-quitearun!
Apachecurrentlyholdsover60percentoftheWebservermarketshare,
andtherearenosignsofitrelinquishingitsstronghold.
ThecurrentversionoftheApacheserveris2.0.44,whichistheversion
usedasthebasisfortheinstallationinstructionsinthischapter.Should
youpurchasethisbookandfindthecurrentversionisdifferent,firsttry

theinstructionsaswrittenhere,andthencheckforupdatedinstructions
atthisbook'sWebsite,Unlesssomething
drastichashappenedtotheApachesourcecode(orthisbookisyears
outofdate),theinstallationinstructionsinthisbookwillworkdespite
minorversionchanges.
WhenworkingwithApache,youhavetwooptionsforinstallation:building
fromsourceorinstallingfromapre-compiledbinary.Buildingfromsource
givesyouthegreatestflexibility,asitenablesyoutoremovemodulesyou
don'tneedandextendtheserverwiththird-partymodules.Additionally,


buildingfromsourceenablesyoutoeasilyupgradetothelatestversions
andquicklyapplysecuritypatches,whereasupdatedversionsfrom
vendorscantakedaysorweekstoappear.
Pre-compiledbinaryinstallationsareavailablefromthird-partyvendors
andcanalsobedownloadedfromtheApacheSoftwareFoundationWeb
site.ThisinstallationmethodprovidesasimplewaytoinstallApachefor
userswithlimitedsystemadministrationknowledgeorwithnospecial
configurationneeds.
Inthefollowingsections,you'llusethebuild-from-sourcemethodfor
installationonLinux/UNIXandthepre-compiledinstallationmethod(in
thiscase,usinganInstaller)forWindowssystems.

InstallingandConfiguringApacheonLinux/UNIX
Inthissection,you'llinstallafreshbuildofApache2.0onLinux/UNIX.
TheofficialApachedownloadpageislocatedat
anditwillalwaysclearlyindicate
themostrecentversionofApacheforyourplatform.
TheApachesourcedistributionfilesarefirstpackedwiththetarutility
andthencompressed,eitherwiththegziptoolorthecompressutility.

Downloadthe.tar.gzversionifyouhavethegunziputilityinstalledin
yoursystem,anddownloadthetar.Zfileifgunzipisnotpresentinyour
system.
Thefileyouwanttodownloadwillbenamedsomethinglikehttpd2.0.version.tar.gzorhttpd-2.0.version.tar.Z,whereversionisthemost
recentreleaseversionofApache.Forexample,Apacheversion2.0.44is
downloadedasafilenamedhttpd-2.0.44.tar.gzorhttpd-2.0.44.tar.Z.
Whicheverfileyoudownload,putitindirectoryreservedforsourcefiles,
suchas/usr/src/or/usr/local/src/.
Now,let'sgetonwiththeinstalling.Ifyoudownloadedthetarball
compressedwithgzip,uncompressandunpackthesoftwarebytyping
thefollowingcommandattheprompt(#):
#gunzip

×