Plug In PHP 100 Power Solutions
Plug-in PHP About the Author RobinNixon hasworkedwithandwrittenabout
computerssincetheearly1980s(hisfirstcomputer wasaTandyTRS80Model1withamassive4KB ofRAM!).Duringthistimehehaswritteninexcess of500articlesformanyoftheUK’stopcomputer magazines.Plug-inPHPishisfourthbook.
RobinlivesonthesoutheastcoastofEngland withhiswife,Julie,atrainednurse,andfivechildren, wherehealsofindstimetofosterthreedisabled children,aswellasworkingfulltimefromhome asatechnicalauthor.
About the Technical Editor ToddMeister hasbeendevelopingusingMicrosoft
technologiesformorethantenyears.Hehasbeena TechnicalEditoronmorethan50titlesrangingfrom SQLServertothe.NETFramework.Besidestechnical editingtitles,heisanAssistantDirectorforComputing ServicesatBallStateUniversityinMuncie,Indiana.He livesincentralIndianawithhiswife,Kimberly,and theirfourcharmingchildren.
Plug-in PHP
100 POWER SOLUTIONS
RobinNixon NewYorkChicagoSanFrancisco LisbonLondonMadridMexicoCity MilanNewDelhiSanJuan SeoulSingaporeSydneyToronto
Copyright © 2010 by McGraw-Hill Companies. All rights reserved. Except as permitted under the United States Copyright Act of 1976, no
part of this publication may be reproduced or distributed in any form or by any means, or stored in a database or retrieval system, without the
prior written permission of the publisher.ISBN: 978-0-07-166660-2 MHID: 0-07-166660-5 The material in this eBook also appears in the print version of this title: ISBN: 978-0-07-166659-6, MHID: 0-07-166659-1.
All trademarks are trademarks of their respective owners. Rather than put a trademark symbol after every occurrence of a trademarked name,
we use names in an editorial fashion only, and to the benefit of the trademark owner, with no intention of infringement of the trademark. Where
such designations appear in this book, they have been printed with initial caps.McGraw-Hill eBooks are available at special quantity discounts to use as premiums and sales promotions, or for use in corporate training
programs. To contact a representative please e-mail us at bulksales@mcgraw-hill.com.Information has been obtained by McGraw-Hill from sources believed to be reliable. However, because of the possibility of human or
mechanical error by our sources, McGraw-Hill, or others, McGraw-Hill does not guarantee the accuracy, adequacy, or completeness of any
information and is not responsible for any errors or omissions or the results obtained from the use of such information. TERMS OF USEThis is a copyrighted work and The McGraw-Hill Companies, Inc. (“McGraw-Hill”) and its licensors reserve all rights in and to the work. Use
of this work is subject to these terms. Except as permitted under the Copyright Act of 1976 and the right to store and retrieve one copy of the
work, you may not decompile, disassemble, reverse engineer, reproduce, modify, create derivative works based upon, transmit, distribute,
disseminate, sell, publish or sublicense the work or any part of it without McGraw-Hill’s prior consent. You may use the work for your own
noncommercial and personal use; any other use of the work is strictly prohibited. Your right to use the work may be terminated if you fail to
comply with these terms.THE WORK IS PROVIDED “AS IS.” McGRAW-HILL AND ITS LICENSORS MAKE NO GUARANTEES OR WARRANTIES AS TO THE
ACCURACY, ADEQUACY OR COMPLETENESS OF OR RESULTS TO BE OBTAINED FROM USING THE WORK, INCLUDING ANY
INFORMATION THAT CAN BE ACCESSED THROUGH THE WORK VIA HYPERLINK OR OTHERWISE, AND EXPRESSLY DIS-
CLAIM ANY WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. McGraw-Hill and its licensors do not warrant or guarantee that the
functions contained in the work will meet your requirements or that its operation will be uninterrupted or error free. Neither McGraw-Hill nor
its licensors shall be liable to you or anyone else for any inaccuracy, error or omission, regardless of cause, in the work or for any damages
resulting therefrom. McGraw-Hill has no responsibility for the content of any information accessed through the work. Under no circumstances
shall McGraw-Hill and/or its licensors be liable for any indirect, incidental, special, punitive, consequential or similar damages that result from
the use of or inability to use the work, even if any of them has been advised of the possibility of such damages. This limitation of liability shall
apply to any claim or cause whatsoever whether such claim or cause arises in contract, tort or otherwise.This page intentionally left blank
ForJulie
This page intentionally left blank
Contents at a Glance
1 BuildingaDevelopmentServer ....................................
1
2 UsingthePlug-ins ................................................ 27
3 TextProcessing ................................................... 33
4 ImageHandling .................................................. 59
5 ContentManagement ............................................. 87
6 FormsandUserInput ............................................. 111
7 TheInternet ..................................................... 141
8 ChatandMessaging .............................................. 175
9 MySQL,Sessions,andCookies .................................... 207
10 APIs,RSS,andXML .............................................. 235
11 IncorporatingJavaScript .......................................... 277
12 DiverseSolutions ................................................ 309
Index ........................................................... 335
viiThis page intentionally left blank
Contents
ix P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s
C o n t e n t s
P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s
C o n t e n t s
P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s
C o n t e n t s
P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s
C o n t e n t s C o n t e n t s
P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s
C o n t e n t s C o n t e n t s
P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s
C o n t e n t s C o n t e n t s
P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s
Acknowledgments
hankstoeveryonewhoworkedwithmeonthisbook,particularlyWendy,Todd, Joya,Mike,Vipra,andMelinda,withoutwhomthisbooksimplywouldnotbethe same.Infact,thewholeteamatMcGraw-HillisapleasuretoworkwithandIthank
T youallforyour,kindness,intelligentinsights,andsupport. xxiii
This page intentionally left blank
Introduction
HPisanopen-source(andthereforefree)scriptinglanguageforcreatingdynamic webpages.Sinceitscreationin1995,itspopularityhasgrowntomorethandouble thatofthepreviouslymostusedscriptinglanguage,Perl.
P
Infact,PHPisnowinthetopfivemostpopularandmostusedlanguagesaccordingto amajorityofsurveys,whichishardlysurprisingbecauseitisprovidedwithmostweb hostingaccounts,iseasytointegrateintowebpages,isextremelyfast(giventhatitis interpreted),andithasbuilt-inlinkstoMySQL,theworld’smostpopularopen-source databaseprogram.
Becauseitwaswrittenbyandforprogrammers,PHPcomeswithanextensivelibraryof featuresandfunctionsthatmaybaffleabeginner.Butitispossibletousejustasmallcore subsetofthesetocreatemostofthedynamiccontentawebmastercouldneed,whichis preciselywhatthisbookdemonstrates.
Plug-inPHP isaimedsquarelyatwebsiteownerswhohavelearnedbasicHTMLand
PHPandareinterestedindoingmorewiththeirsites.Forexample,youmaywishtocreate memberareasprotectedbyusernamesandpasswords,orwanttowriteasimpleGuestbook andsoon.UsingPlug-inPHP,youwilllearnhowtodoallthesethingsandmuchmore usingverysimpleready-madePHP.
Itisneverassumedthatyoualreadyknowsomething,soyouaretakenthrougheach subjectstepbystepwithfullexplanations,makingsureyouneverhavetogoelsewhereto findtheinformationyouneed.Thisbookalsopurposefullyignoresmoreadvancedtopics suchasobject-orientedprogramming.Instead,thecodesampleslookverymuchlikeacross betweensimpleCandBasic.Elegant,tightstructuresthatmoreadvancedprogrammers mightappreciatearesetasideinpreferenceformoreunderstandablecode,wheretheflow fromanypointtoanyotherisasobviousaspossible.
Alloftheplug-insandexamplesarewritteninacompleteandready-to-useform thatyoucantypeintoyourownwebpages.Evenifyouhavealmostnoknowledgeof programming,youcanstillmakefulluseofthebook,whichcanbedippedintoasrequired sinceeachchapterismostlyself-contained.Thismeansthatwhereveryouhaveaproblem onyourwebsiteyoucansimplyrefertotherelevantchapter,whichshouldbeallyouneed tosolveit.
Tohelpyougetupandrunningwiththeseplug-ins,thefirstchapterwalksyouthrough howtosetupyourownwebdevelopmentserveronaPC,Mac,orLinuxcomputer,while thesecondshowshowbesttointegratetheplug-insintoyourownprograms.
xxv
P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s
About PHP
PHPwasoriginallydevelopedin1994byRasmusLerdorftoreplaceasetofPerlscriptshe hadbeenusingtomaintainhispersonalwebsite.TheacronymoriginallystoodforPersonal HomePage,butwhenhereleasedaversiontothepublicthefollowingyearitwas recursivelyretitledPHP:HypertextProcessor.
Evenintheearlydays,LerdorfintendedthatPHPshouldbeflexibleandeasily expandable,throughrewritesofthelanguageparser.Thishasremainedakeyethosofthe projecttothisday,withnumerousextensionlibrariesavailablethroughthePEAR(PHP ExtensionandApplicationRepository)add-on.
Evenwithouttheseextensions,PHPcomessuppliedwithhundredsofready-made functions—manymorethaninmostotherprogramminglanguages—makingitaveryrich developmentplatform.Nodoubtthisisacontributingfactortowardsitscurrentpopularity, beinginstalledonathirdofallwebservers,andbehindonlyC++,C,andJavainusagefor webdevelopment.
TherearemanyreasonstousePHPforwebdevelopment.Theseincludeitsincredible speed,whichisevenmoreremarkablegiventhatit’saninterpretedlanguage,itseaseofuse andinteroperabilitywiththeMySQLdatabase,andthefactthatit’salmostalwaysinstalled onanycomputerrunningtheApachewebserver.
PriortoPHP,themostusedscriptinglanguagewasPERL,whichwasdevelopedby LarryWallin1987.Originallyintendedasageneralscriptinglanguagetoautomatereport processingonUnix,itwasadoptedbymanywebdeveloperstoo,andremainsquite populartoday.But,unlikePHP,PERLwasneverdesignedspecificallyforuseonwebsites, whereasPHPwaswrittenfromthegroundupwithwebdevelopmentinmind,whichmay accountforthefactthatPHPisnowmorethantwiceaspopularasPERL.
Regardinglearningandusingthelanguage,PHPisreasonablysimilartootherwell- knownlanguagessuchasC,Java,andPerl,whereasASPusesVisualBasic(althoughASP.net supportsotherlanguages).What’smore—ASPisbuiltontheCOMarchitecture,whereas PHPisnotconstrainedthiswayandrunsmuchfaster.
Fromaperformancepointofview,PHPisextremelyfastandcansupportmillionsof accessesaday.AccordingtoZendTechnologies(thewritersofthemain enginethatPHPuses,PHPoftenoutperformsthecompetition.UnlikeMicrosoft’sASP(Active ServerPages),PHPisavailableonmultipleplatformsand,becauseitisfree(opensource software),itcanbeimplementedatlittlecostotherthanthatofthehardwareitrunson.
InterestinglyaquickcheckatGoogleforthesearches“filetype:php”and“filetype:asp” returns7.4billionPHPpagesand1.8billionASPpagesontheweb.That’saratioofover fourtooneinfavorofPHP.
YoumaybesurprisedatsomeofthesitesthatusePHPastheirbackbonebecauseyou probablyknowmanyofthem.Here’salistofjustfivetopwebsitesthatusePHPforsome oralloftheirsite’sprogramming:
- Yahoo! Apopularsearchengine(seeFigure1)
- Facebook Asocialnetworkingsite
- Wikipedia Acollaborativeencyclopedia
- Photobucket Aphotosharingservice
- Digg Atechnologynewsbookmarkingsite
I n t r o d u c t i o n F
IGURE 1 Yahoo! is possibly the best-known web company that uses PHP extensively.
Actually,Yahoo!shouldn’tbetoomuchofasurprisebecauseRasmusLerdorfhas workedatthecompanyasaDistinguishedEngineersince2002. SowhyisPHPsopopular?Therearethreemainreasons.First,PHPintegratesseamlessly withHTML.Evenifyouknownexttonoprogramming,it’sveryeasytorenameyour.html filesto.phpandtheywillautomaticallybecomePHPprograms,albeitonesthatdisplay themselvesasanHTMLpage.Butthen,wheneveryouneedalittledynamicfunctionality, youcandropinaquicklineofPHPcode,likethefollowingsnippet,whichwilldisplaythe dayoftheweek:
<?phpechodate("l");?>
Second,it’seasytolearn.WithafewsimplePHPfunctionsunderyourbelt,almost withoutknowingit,you’realreadyaPHPprogrammer.Addinforloopsandacoupleof otherconstructsandyoucanveryquicklystartmakingyourowndynamicwebsites.
Third,there’sexcellentsupportfromthePHPprogrammingcommunityandbooks suchasthis.Justtype“helpPHP”intoGoogleandyou’llbepresentedwithastaggering 125millionsearchresults. P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s
What This Book Provides
HavingaccesstoallofPHP’sfunctionsisn’tveryusefulwhenyouneedtoquicklyput togetheraprojecttoatightdeadline,becausethefunctionstypicallyprovideveryspecific functionality.EvenPEARplug-insarenotalwaysthecompletesolutioneither,sincethey usuallytaketimetolearnandstillmustbewrappedinPHPcodeofyourowndevising.
That’swherethisbookcomesintoitsown,becauseitprovides100ready-to-goplug-ins youcansimplydropintoyourprogramsanduse,normallywithasimple,singlecall.Of course,becauseallprojectsaredifferentIonlyprovidethebarebonesneededandleave layoutandstylingtotheabsoluteminimum.Thisleavesyoufreetograbaplug-in,insertit intoyourownprogram,andthentailorittoyourexactrequirements.
Thetypesofplug-inssuppliedofferquickandsimplesolutionstoaverywiderangeof problemsincludingprocessingtextinavarietyofways,uploadingandmanipulating images,servercontentmanagement,formhandling,userinputvalidation,chatand messaging,userauthenticationandsecurity,integrationwiththird-partywebsites,and muchmorebesides.
Withthemyoucanavoidhavingtoreinventthewheeleachtimeyouneedanew feature,becausethechancesarethatthemoduleyouneed(oroneverysimilar)canbe foundinthisbookasaplug-in.Andevenifitisn’t,becauseeachandeveryplug-inis brokendownintocomponentpartsandexplainedindetail,youshouldfindyoucan cherry-pickcodesegmentsfromdifferentplug-instobuildyourown.
About the Plug-ins
Allofthisbook’splug-insareready-to-runandcanbeeithertypedinifyoudon’thave Internetaccess,oryoucandownloadthemfr(seeFigure2)where theyarestoredasbothindividualplug-insandalsogroupedintolargercollectionsby theme.Forexample,alltheauthenticationandsecurityplug-inscanbefoundinthefile security.php.
Whenyouvisitthewebsite,youcannavigatethroughtheplug-inschapterbychapter, andalsoviewthePHPprogramcodehighlightedincolorforclarity.Fromthere,youcan copy,paste,ordownloadindividualplug-ins,groups,orthewholecollectiondirectlyto yourcomputer.
What Is and Isn’t Included
AlthoughthefirstaimofthisbookistoprovidenewcomerstoPHPwithacomprehensive resourceoffunctionsandroutinestodrawon,ithasasecondarygoal,whichistohelpyou moveuptothenextlevelandtocreateyourownprogrammingtoolkit.Thereforeevery plug-inisthoroughlydocumentedandexplainedindetail,andadviceisgivenonwaysto improveandextendthem,aswellashowtoadaptthemtoyourownrequirements.
Toaidwiththis,IhaveattemptedtostickwithabasicsubsetofPHPfunctionssoyou canfamiliarizeyourselfwiththemasyouworkthroughthebook.Exceptforcaseswhereit isunavoidable,Ihavealsosteeredclearofadvancedtechniquessuchasobject-oriented programming(OOP),somostoftheplug-inswork(andcanbeexplained)inaprocedural manner.Ofcourse,OOPispowerfuland,ifyoudon’talreadyuseit,youreallyshouldlearn itbecauseyou’llfindyourproductivityrateincreasessubstantially.
I n t r o d u c t i o n F
IGURE 2 All the plug-ins from this book can be downloaded from
Andwhilethisbookisn’taprogrammingmanualorateachingguide,Idohopethatby readingthroughtheplug-inexplanations,ratherthanjustincludingtheminyourprojects, you’llpickupanumberoftipsandtricksthatmanyprogrammerstakeyearstodiscover, andbyosmosisyouwilllearnmoreaboutthePHPprogramminglanguage.
Plug-in License
Youarefreetouseanyoftheplug-insinthisbookinyourownprojects,andmaymodify themasnecessary,withoutattributingthisbook—althoughifyoudoso,itwillalwaysbe appreciated.
However,youmaynotsell,giveaway,orotherwisedistributetheplug-insthemselves inanymanner,whetherprintedorinelectronicformat,withoutthewrittenpermissionof thepublisher.
Companion Web Site
Acompanionwebsite(ataccompaniesthisbook,whereall100plug-ins areavailabletodownload,alongwithexamplecodeforyoutoexperimentwith.Thesitealso includesusefulextrassuchasan80,000-worddictionaryandageo-locationIPdatafile.
P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s
Thewebsiteisbestusedinconjunctionwiththisbook.Asyoureadachapter,callitup onthewebsite,too,andyoucanlisteachplug-inonscreenwithcolor-highlightedsyntax. Thismakesitveryeasytoseethestructureofeachprogram.
Whenyouwishto,youcanclickalinktocopyandpasteaparticularplug-inrightinto yourownprograms.Or,ifyouprefer,youcandownloadalloftheplug-instoyourcomputer fromwhereyoucanpicktheone(s)touploadtoyourownwebsite.
Tohelpyouwithaccessingthem,theplug-insareallstoredingroupsoftenperfile, eachfilehavingacertaintheme,suchasimagemanipulationortextprocessing,andsoon. Youcanthencopyandpastefromthesefiles,oruseaPHPincludecommandto incorporatetheminyourownprograms.
Thereisalsoablogwhereyoucankeepuptodatewiththelatestdevelopments,aswell asaforumwhereyoucanshareyourexperiencesandaskforassistanceifyouneedit.
P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s
hencreatingplainHTMLwebsites,it’seasytodevelopthemonapersonalcomputer becausenowebserverisneededtoserveupthepages.Yousimplyloadtheminto yourbrowseranddisplaythem.ThesamegoesforJavaScriptandevenFlash.
W However,whenitcomestoPHPit’sawholedifferentballgamebecauseyouneeda
numberofnewprograms,suchasthePHPparserandinterpreter,andawebservertotake theoutputfromPHPandreturnHTMLpages.Plus,ifyou’llbeaccessinganydata,you’ll alsoneedadatabaseprogramsuchasMySQL.
Untilafewyearsago,youronlysimplechoicewastofindahostingcompanythat wouldsetyouupwithaserverwithalltheseoptionsalreadyinplace.Alternatively,ifyou wereanexpert,youcouldinstalleachoftheseitemsseparatelyandconfigurethemtowork witheachother,aprocessoftenfraughtwithmanyhoursoftweakingandhairpulling beforeeverythingwouldworkcorrectly.
Recently,however,anumberofWAMP,MAMP,andLAMPpackageshavesprungup. Respectively,thesestandforWindows/Mac/Linux,Apache,MySQL,andPHPandthey provideanintegratedinstallationenvironmenttoautomaticallyconfigurethevarious elementstoproperlyinteractwitheachother.Evenso,someofthemstillneededabitof tweakingonless-than-standardinstallations.
Early2009,though,sawthereleaseofZendServerCEfromZend,thecompanybehind PHPitself.TheCEstandsforCommunityEdition,whichmeansit’sfreeandcommunity supported,andit’strulyaqualityproduct.WhilenotaspowerfulastheoriginalZend Server,whichwasdesignedforrunningandmanagingbusiness-criticalPHPapplicationsin production,it’sabsolutelyperfecttouseasadevelopmentplatform,andisavailableforall ofthefollowing:
- WindowsXP,servicepack2
- WindowsVista(excludingStarter)
- Windows7
- MostflavorsofLinux
- MacOSX10.4plusrunningonIntelchips ZendServerCEcomeswitheverythingyouneed,includingApacheandPHP(andwith alittleconfiguring,MySQL,too)andisveryeasytoinstall.However,becausetheprocess variesbyplatform,Ihavedivideditsinstallationintodifferentsectionshere.Soplease choosetheonerelevanttoyourcomputer.
Windows XP, Windows Vista, and Windows 7
ToinstalltheprogramonaWindowsmachine,youneedtovisitthefollowingURLand downloadtheWindowsinstallationfile(seeFigure1-1):
Onceyouhavedownloadedtheinstallationfile,whichshouldbearound50MBinsize, youwillhaveanexecutablefileinyourdownloadsfolderwithafilenamesuchasZendServer-
CE-php-5.2.10-4.05-Windows_x86.exe ,dependingontheversion.Tobegininstallationjust
C h a p t e r 1 : B u i l d i n g a D e v e l o p m e n t S e r v e r C h a p t e r 1 : B u i l d i n g a D e v e l o p m e n t S e r v e r F
IGURE 1-1 Downloading the Windows Zend Server CE installation program
double-clickthefile.IfyouarerunningWindowsVistaorWindows7,andaUserAccount ControlboxsuchasthatdisplayedinFigure1-2,clickYestocontinue.
IfyouhavealreadyinstalledZendServerCEandarenowinstallinganewerversion, anotherconfirmationboxwillappearfromtheinstalleritself(seeFigure1-3).Inthiscase, clickYestocontinue.
F
If prompted by User Account Control, click Yes to confirm installation.
P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s
IGURE F 1-3 Click Yes when the Zend installer asks if you wish to continue.
ThescreeninFigure1-4willappear.ClicktheNextbuttontocontinue. Afterawhile,theinstallerwillhavegatheredenoughinformationtocontinuewith theinstallationandyouwillbepromptedtoagreetothetermsoftheEnd-UserLicense
Agreement(seeFigure1-5).
NextyouareaskedwhethertheprogramshouldperformaTypical,Full,orCustom installation(seeFigure1-6).SelectCustomatthispointsoyoursetupwillagreewiththe onedescribedinthischapter.Youcanalwaysre-installagainlaterwithdifferentoptionsif youneedto.
F IGURE 1-4 When prompted a second time, click Next to continue.
C h a p t e r 1 : B u i l d i n g a D e v e l o p m e n t S e r v e r
C h a p t e r 1 : B u i l d i n g a D e v e l o p m e n t S e r v e r
F IGURE 1-5 You must agree to the license agreement to be able to install Zend Server CE.
F IGURE 1-6 Select the Custom installation option and then click Next.
P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s
Havingtoldtheinstalleryouneedacustominstallation,youmustnowsetanoptionto ensurethatMySQLgetsinstalledaswell.Todothis,scrolldownthroughthelistof components(showninFigure1-7)until,neartheend,youseeMySQLServer.Clickits checkbox,andthenclickNext.
YouwillbeaskedwhetheryouwishtoinstallanApacheWebServerorconfigurean existingIISserver(seeFigure1-8).ThelatteroptionwillbedisabledifIISisnotinstalled. IrecommendyouchoosetheApacheoptionanyway,atleastuntilyouhaveverifiedthatthe plug-insinthisbookworkcorrectlyforyou.Youcanalsochoosewheretoinstallthe program(bydefaultitwillbeC:\ProgramFiles\Zend).Ifyouchoosetochangethis,then youwillalsoneedtoremembertousetheappropriatedirectorytoaccessthisfolderwhen thepathnameisreferencedlaterinthischapterandelsewhereinthebook.
If,atthenextscreen,youarepromptedforthewebserverportnumber,leavethe defaultvalueof80whichwillbeoffered,andclickNext.Whenfinishedwiththeseinitial settings,you’llbepresentedwithaconfirmationscreenwhereyoucanreviewthem(see Figure1-9).Iftheyarenotcorrect,clicktheBackbuttonandamendthem;otherwise,click theInstallbutton.
Duringinstallation,youmaybeshownthedialoginFigure1-13(seetheWindows SecurityAlertssection).YoumustclickAllowAccessforApachefortheinstallationtowork properly.Uponsuccessfullycompletingtheinstallation,thescreeninFigure1-10will display.HereyoucanchoosewhethertocreateaDesktopshortcutbeforeclickingFinish.
F IGURE 1-7 Select the MySQL Server checkbox before continuing.
C h a p t e r 1 : B u i l d i n g a D e v e l o p m e n t S e r v e r
C h a p t e r 1 : B u i l d i n g a D e v e l o p m e n t S e r v e r
F IGURE 1-8 Here you can tell the installer to install an Apache web server and where to install the Zend server.
F IGURE 1-9 Review the installation settings before proceeding.
P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s F IGURE 1-10 Upon completion, you can decide whether to create a Desktop shortcut.
Reinstalling Zend Server CE
IfyouhavealreadyinstalledZendServerCEandarereinstallingit,eithertochangethe installationoptions,ortorepairafaultyinstall,youwillbepresentedwiththescreenin Figure1-11(insteadoftheonementionedearlier),whereyoucanalsochoosetouninstall theprogramifyouwish.
Upgrading Zend Server CE
Theprocessofupgradingtheprogramtoanewerversionismuchquickerthananinitial installation,comprisingonlyasinglemainscreen,asshowninFigure1-12.Notethe warningissuedhere,thatonceupgradedyoucannotrollbacktoanearlierversion.You willnotseethisscreenifyouareonlyreinstallingthesameversionasisalreadyinstalled.
Windows Security Alerts
If,atanypointduringinstallation,youreceiveaWindowsSecurityAlert,suchastheonein Figure1-13,askingwhethertounblocktheApacheserver,clickAllowAccess(onWindowsVista and7)orUnblock(onWindowsXP)tograntfullaccesstoZendServerCEanditscomponents.
After Installation
OnceZendServerCEhasbeensuccessfullyinstalled,yourwebbrowserwillopenand you’llbeaskedtoenterapasswordtousewiththesetup(seeFigure1-14).Ifyouare
C h a p t e r 1 : B u i l d i n g a D e v e l o p m e n t S e r v e r
C h a p t e r 1 : B u i l d i n g a D e v e l o p m e n t S e r v e r
F IGURE 1-11 By rerunning the installation program, you can modify, repair, or remove Zend Server CE.
F IGURE 1-12 Upgrading Zend Server CE is even easier than installing it.
P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s
F
IGURE 1-13 If prompted by a Windows Security Alert, you should unblock any Zend Server components.
F IGURE 1-14 Before using Zend Server CE, you must choose a password for accessing it.
C h a p t e r 1 : B u i l d i n g a D e v e l o p m e n t S e r v e r C h a p t e r 1 : B u i l d i n g a D e v e l o p m e n t S e r v e r
reinstallingorupgrading,you’llsimplybeaskedtoconfirmthepreviouspasswordyou created.Youcanalsoenteryoure-mailaddressifyou’dliketoreceivetheZendnewsletter.
AUTION IfyouwillbeforwardingHTTPrequestsfromtheInternettoyourserver(not C
recommendedpermanentlybutusefulforgrantingacolleaguetemporaryaccesstoaprojectin
progress),thenit’sparticularlyimportantthatyouchooseaverysecurepassword.Nowyouaresetupandreadytogo,andthescreenshowninFigure1-15willdisplayin yourbrowser.FromthisscreenyoucancontrolvariousaspectsofyourZendServerCE installation.
Youcanverifythateverythingisworkingcorrectlybyenteringhttp://localhostintoyour webbrowser.TheresultshouldlooklikeFigure1-16.
Uninstalling
TouninstallZendServerCE,fromtheStartMenuselectAllPrograms|ZendServer CommunityEdition|UninstallZendServer.
F IGURE 1-15 After installation, your browser will open up a control window for Zend Server CE.
P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s F IGURE 1-16 Everything installed correctly if you can see this page when you enter http://localhost.
Document Root
Bydefault,yourdocumentroot(theplacewhereallyourHTMLandPHPfilesshouldbe stored)isc:\ProgramFiles\Zend\Apache2\htdocs.Ifyoufindthatyoucannoteditorsave filesintoit,youwillneedtomodifythefolder’spermissionsettings.Youmayfindit convenienttocreateashortcuttothisfolderbynavigatingtoit,rightclicking(andholding) onthehtdocsfolder,anddraggingittotheDesktop.Onceyoureleasethemousebutton,you canthenselectCreateShortcutsHere.
Ubuntu and Debian Linux
OnUbuntuorDebianLinux,youwillneedtoinstalltheMySQLprogramseparatelyifyou don’thaveitalready.It’sveryeasytodobecauseitusesAptitude,afrontendtothe AdvancedPackagingTool(APT)system.
C h a p t e r 1 : B u i l d i n g a D e v e l o p m e n t S e r v e r C h a p t e r 1 : B u i l d i n g a D e v e l o p m e n t S e r v e r
JustopenuptheTerminalbyselectingApplications|Accessories|Terminaland enteringthefollowingtwocommands,thefirstofwhichensuresyouarerunningasroot, whilethesecondinstallstheserver.Ifyouarepromptedforyourpassword,enterit.Atthe endoftheinstallation,youmaybepromptedtoenterarootpasswordasinFigure1-17, which,likeallthefollowingLinuxscreengrabs,isfromUbuntuLinux.
sudo-i apt-getinstallmysql-server
YouarenowreadytoinstallZendServerCEitself.Theprocesstakesafewcommands tosetupbecauseyoumustfollowseveralsteps.First,stayingintheTerminalwindow,you needtochangetothe/etc/aptfolderandtheneditthefilesources.listbytypingthefollowing (assumingyouarestillloggedinasrootafterinstallingMySQL):
cd/etc/apt nanosources.list T
IP IfyouareusingDebianLinuxratherthanUbuntu,andNanoisnotyourdefaulttexteditor,