Sie sind auf Seite 1von 47

SEMINAR

REPORT ON PHP HYPERTEXT PREPROCESSOR

CERTIFICATE
This is to certify that Miss. Sayli S. Mahajan has completed the necessary seminar work and prepared the bona fide report on

PHP HYPERTEXT PRE - PROCESSOR


In a satisfactory manner in partial fulfillment for the requirement of a degree in B.E. !omputers" of #ni$ersity of %une in the &cademic year '((')'((*

+ate , -th &ug .(' %lace , %une %rof. Internal /uide %rof. / % %otdar Seminar coordinator %rof. +r. ! 0 1 2ao 3.4.+

DEPARTMENT OF COMPUTER ENGINEERING

PUNE INSTITUTE OF COMPUTER TECHNOLOGY PUNE - 43

ACKNOWLEDGEMENT

I take this opportunity to thank respected %rof )))))))) Sir my project guide" for his generous assistance. I am also immensely greatful to our 3on. 34+ +r. !.0.1 2ao for his encouragement and guidance. I also e5tend my sincere thanks to all the staff members for their $aluable assistance.

Sayli Mahajan. B.E. 6 I "

CONTENTS

!hapter 7, &n 4$er$iew 4f %3%


7.7 7.' 7.* 7.: 8hat Is %3% 9 3ow +id %3% !ome Into Being 8hy #se %3% 9 8hat !an %3% +o 9 (7 (' (' (*

!hapter ', More on %3%


'.7 ;eatures of %3% '.7.7 Some More ;eatures '.' '.* '.: &d$antages of %3% >imitations of %3% !omparisons of %3% '.:.7 %3% $s. &S% ((< (= 7( 7( 77

'.:.' %3% $s. %erl

7*

!hapter *, Interaction 8ith 8eb Ser$ers


*.7 !onnecting To 4ther Ser$ers *.7.7 &pache *.7.' IIS *.' The @end Engine 777? '(

!hapter :, %rogramming 8ith %3%


:.7 >anguage Synta5 :.7.7 0ariables :.7.' +ynamic 0ariables :.7.* +ata Types :.7.: Typecasting :.7.- E5pressions :.7.< 4perators :.7.= !ontrol Structures :.7.A ;unctions '* '* ': ''? *( *( *7 *:

:.7.A.7 :.7.A.' :.7.A.*

0ariable Scope %assing &rguments Static 0ariables

**< *= *=

:.7.? 8eb 2elated 0ariables

BIB>I4/2&%3B

:(

1.1

Wh ! "# PHP $

%3% recursi$e acronym for C%3%, 3yperte5t %reprocessorC" is a widely used 4pen Source general)purpose scripting language that is especially suited for 8eb de$elopment and can be embedded into 3TM>. %3% is a project of the &pache Software ;oundation. C%3% is a ser$er)sideD cross)platformD 3TM> embedded scripting language.C

E% &'() 1-1.
<html> <head>

A* "*!+,-./!,+0 )% &'() 1

<title>Example</title> </head> <body>

<?php echo "Hi, I'm a PHP script!"; ?> </body> </html>

Eotice how this is different from a script written in other languages like %erl or ! )) instead of writing a program with lots of commands to output 3TM>D you write an 3TM> script with some embedded code to do something in this caseD output some te5t". The %3% code is enclosed in special start and end tags that allow you to jump into and out of C%3% modeC.

1.2 H,3 -"- PHP /,&) "*!, 4)"*5 $


%3% started as a quick %erl hack written by 2asmus >erdof in late 7??:. 4$er the ne5t two to three yearsD it e$ol$ed into what we today know as %3%F;I '.(. %3%F;I started to get a lot of usersD but things didnGt start flying until @ee$ Suraski and &ndi /utmans suddenly came along with a new parser in the summer of 7??=D leading to %3% *.(. %3% *.( defined the synta5 and semantics used in both $ersions * and :. %3% originally stood for G%ersonal 3ome %agesG but the meaning was changed as the language matured. Eow it has a complicated but more descripti$e name of G%3%, 3yperte5t %re)processorGD which is a recursi$e acronymD for $ersion : of %3%. The engine was totally rewritten and became a super fastD and super easy language to use and learn. This new teamD @end.comD also the name of the engine is constantly working on %3% to impro$e the featuresD speed and stability. %3% *D released in Hune 7??AD gained rapid popularityD and is now used in 8eb)related applications by some of the most prominent organiIations such as MitsubishiD 2edhatD +er SpiegelD M%*)>ycosD Ericsson and E&S&. By the middle of 7??=D %3% was being used on appro5imately -(D((( sites worldwide.

1.3

Wh0 .#) PHP $

3ere are a few good reasons to choose %3% for enabling interacti$e content on your web site besides being open source", Because it uses similar synta5 and constructsD knowledge of %3% can help you in The data types and structures of %3% are easy to use and understandD %3% knows

learning the ! language. what you mean and can con$ert types automatically. Bou donGt ha$e to know any special commands to compile your programD it runs

right in your web browser. Bou donGt ha$e to know e$erything there is to know about %3% to start writing

useful programs. %3% ser$es as a CwrapperC for many standard ! librariesD which are easily compiled

into the language gi$ing it the fle5ibility to respond more rapidly to changes in web technology or trends. Things you can do in %3% can be done in other languagesD but %3% was designed to

work in a web conte5tD so things that are difficult or tedious for the applications programmer to Croll their ownC in %erl are easy in %3%. %3% enabled web sites can be deployed with amaIing rapidityD due to its being tuned for dynamic pages and database back ends.

1.4

Wh ! / * PHP -,$

&nything. %3% is mainly focused on ser$er)side scripting so you can do anything any other !/I program can doD such as collect form dataD generate dynamic page contentD or send and recei$e cookies. But %3% can do much more.

1.4.1 6."(-"*5 * /!"7) 3)4 #"!) 1

&n acti$e ser$er works similarly to a traditional web ser$er. & web client requests a script by its #2>D rather than a document. In turnD the web ser$er loads the scriptD e5ecutes it within an en$ironment associated with the web ser$erD and returns the results to the client. The result can be anythingD but is usually web)formatted contentD such as 3TM>D 8M>D %+; or an image. &cti$e web ser$er uses ser$er ) side scripting 6 the scripts run on the web ser$er. This is in stark contrast to client 6 side scripting in which the client runs scripts pro$ided by the ser$er. Scripting languages such as Ha$aScript and 8M>Script use client 6 side scriptingD whereas acti$e ser$er technologies such as Microsoft &cti$e Ser$er %ages side scripting. There are three main fields where %3% scripts are used. S)+7)+-#"-) #/+"'!"*5 1 &S%"D MacromediaJs !old ;usion and %3% are e5amples of acti$e web ser$ers using ser$er 6

This is the most traditional and main target field for %3%. Bou need three things to make this work. The %3% parser !/I or ser$er module"D a web ser$er and a web browser. Bou need to run the web ser$erD with a connected %3% installation. Bou can access the %3% program output with a web browserD $iewing the %3% page through the ser$er. C,&& *- ("*) #/+"'!"*5 1

Bou can make a %3% script to run it without any ser$er or browser. Bou only need the %3% parser to use it this way. This type of usage is ideal for scripts regularly e5ecuted using cron on Kni5 or >inu5" or Task Scheduler on 8indows". These scripts can also be used for simple te5t processing tasks. W+"!"*5 /(")*!-#"-) GUI ''("/ !",*# ,

%3% is probably not the $ery best language to write windowing applicationsD but if you know %3% $ery wellD and would like to use some ad$anced %3% features in your client)

side applications you can also use %3%)/T1 to write such programs. Bou also ha$e the ability to write cross)platform applications this way. %3%)/T1 is an e5tension to %3%D not a$ailable in the main distribution.

2.1

F) !.+)# ,8 PHP 1
I! "# 8 #!)+ !, /,-) *- 8 #!)+ !, )%)/.!) 1

The same %3% code runs unaltered on different web ser$ers and different operating systems. ;unctionality that is standard with %3% is an add)on in other en$ironments. PHP "# 8+)) 1

&nyone may $isit the %3% web site and download the complete source code. There is $ery little risk in trying %3%D and its license allows the code to be used to de$elop works with no royalties. PHP +.*# ,* UNIX9W"*-,3# :;9 W"*-,3# NT *- !h) M /"*!,#h 1

%3% is designed to integrate with the &pache web ser$er. &pache another free technologyD is the most popular web ser$er on the Internet and comes with source code for #EIL and 8indows. PHP "# &,-"8" 4() 1

%3% has been designed to allow for future e5tension of functionality. %3% is coded in ! and pro$ides a well defined &pplication %rogramming Interface &%I". !apable programmers may add new functionality easily. The rich set of functions a$ailable in %3% are e$idence they often do. PHP 3 # 3+"!!)* 8,+ 3)4 ' 5) /+) !",* 1

%erlD ! and Ha$a are $ery good general languages and are certainly capable of dri$ing web applications. The unfortunate sacrifice these alternati$es make is the ease of communication with the web e5perience. %3% applications may be rapidly and easily de$eloped because the source code is encapsulated in the web pages themsel$es. PHP "# ','.( + 1

Internet ser$ice pro$iders find %3% to be an attracti$e way to allow their customers to code web applications without the risks e5posed by !/Is. +e$elopers worldwide offer %3% programming. Sites coded in %3% will ha$e the option of mo$ing from one host to another as well as a choice of de$elopers to add functionality.

P+,5+ &&"*5 #<"((# -)7)(,)- "* ,!h)+ #!+./!.+ ( ( *5. 5)# / * 4) ''(")- !, PHP 1

%3% takes inspiration from both %erl and !.

2.1.1 O!h)+ F) !.+)# ,8 PHP 1


S! *- +- CGI9 F #!CGI *- A' /h) &,-.() #.'',+! 1

&s a standard !/I programD %3% can be installed on any #EIL machine running any #EIL web ser$er. 8ith support for the new ;ast!/I standardD %3% can take ad$antage of the speed impro$ements gained through this mechanism. &s an &pache moduleD %3% becomes an e5tremely powerful and lightning fast alternati$e to !/I programmimg. A//)## L,55"*5 1

8ith the access logging capabilities of %3%D users can maintain their own hit counting and logging. It does not use the systemGs central access log files in any wayD and it pro$ides real)time access monitoring. The >og 0iewer Script pro$ides a quick summary of the accesses to a set of pages owned by an indi$idual user. In addition to thatD the package can be configured to generate a footer on e$ery page which shows access information. A//)## C,*!+,( 1

& built)in web)based configuration screen handles access control configuration. It is possible to create rules for all or some web pages owned by a certain person which place $arious restrictions on who can $iew these pages and how they will be $iewed. %ages can be password protectedD completely restrictedD logging disabled and more based on the clientGs domainD browserD e)mail address or e$en the referring document. P,#!5+)#S=L S.'',+! 1

%ostgres is an ad$anced free 2+BMS. %3% supports embedding %ostgreSM> CSM> queriesC directly in .html files. 2;!)7A<= ;ile #pload Support ) ;ile #pload is a new feature in Eetscape '.(. It lets users upload files to a web ser$er. %3% pro$ides the actual Mime decoding to make this work and also pro$ides the additional framework to do something useful with the uploaded file once it has been recei$ed. HTTP-4 #)- .!h)*!"/ !",* /,*!+,( 1

%3% can be used to create customiIed 3TT%)based authentication mechanisms for the &pache web ser$er.

> +" 4()#9 A++ 0#9 A##,/" !"7) A++ 0# 1

%3% supports typed $ariablesD arrays and e$en %erl)like associati$e arrays. These can all be passed from one web page to another using either /ET or %4ST method forms. C,*-"!",* (#9 Wh"() L,,'# 1

%3% supports a full)featured !)like scripting language. Bou can ha$e ifFthenFelseifFelseFendif conditions as well as while loops and switchFcase statements to guide the logical flow of how the html page should be displayed. E%!)*-)- R)5.( + E%'+)##",*# 1

2egular e5pressions are hea$ily used for pattern matchingD pattern substitutions and general string manipulation. %3% supports all common regular e5pression operations. R 3 HTTP H) -)+ C,*!+,( 1

The ability to ha$e web pages send customiIed raw 3TT% headers based on some condition is essential for high)le$el web site design. & frequent use is to send a >ocation, #2> header to redirect the calling client to some other #2>. It can also be used to turn off cacheing or manipulate the last update header of pages. O*-!h)-8(0 GIF "& 5) /+) !",* 1

%3% has support for Thomas BoutellGs /+ image library which makes it possible to generate /I; images on the fly. ISP ?S 8) M,-)? #.'',+! 1

%3% supports an unique CSafe ModeC which makes it safe to ha$e multiple users run %3% scripts on the same ser$er. Many more new features are being added in newer releases of %3%. 0isit the main web site at http,FFwww.php.net I!@# F+))A 1

4ne final essential feature. The package is completely free. It is licensed under the /E#F/%> which allows you to use the software for any purposeD commercial or otherwise. A4"("!0 !, "*/(.-) 8"()# 1

&n important feature of %3% is its ability to include files. These files may contain additional %3% tags. 8hen you are designing a web applicationD it can be useful to break out some common components and place them in a single file. This makes it much easier

to later change certain aspects in one place and ha$e it take effect across the entire application. To include a fileD you use the include keyword.

2.2

A-7 *! 5)# ,8 PHP 1


PHP / * 4) .#)- ,* (( & B,+ ,')+ !"*5 #0#!)&# 1

Including >inu5D many #ni5 $ariants including 3%)#LD Solaris and 4penBS+"D Microsoft 8indowsD Mac 4S LD 2IS! 4SD and probably others. %3% has also support for most of the web ser$ers today. This includes &pacheD Microsoft Internet Information Ser$erD %ersonal 8eb Ser$erD Eetscape and i%lanet ser$ersD 4reilly 8ebsite %ro ser$erD !audiumD LitamiD 4mni3TT%dD and many others. ;or the majority of the ser$ers %3% has a moduleD for the others supporting the !/I standardD %3% can work as a !/I processor. F+))-,& ,8 /h,,#"*5 * ,')+ !"*5 #0#!)& *3)4 #)+7)+ 1

;urthermoreD you also ha$e the choice of using procedural programming or object oriented programmingD or a mi5ture of them. &lthough not e$ery standard 44% feature is realiIed in the current $ersion of %3%D many code libraries and large applications including the %E&2 library" are written only using 44% code. W"!h PHP 0,. +) *,! ("&"!)- !, ,.!'.! HTML 1

%3%Gs abilities include outputting imagesN %+; files and e$en ;lash mo$ies using libswf and Ming" generated on the fly. Bou can also output easily any te5tD such as L3TM> and any other LM> file. %3% can auto generate these filesD and sa$e them in the file systemD instead of printing it outD %3% can auto generate these filesD and sa$e them in the file systemD instead of printing it outD forming a ser$er)side cache for your dynamic content. PHP #.'',+!# 3"-) + *5) ,8 - ! 4 #)# 1

8riting a database)enabled web page is incredibly simple. The following databases are currently supported, &dabas + +base Empress ;ile%ro read)only" 3yperwa$e IBM +B' Informi5 Ingres 4racle 4!I= and 4!IA" InterBase 4$rimos ;rontBase %ostgreSM> mSM> Solid +irect MS)SM> Sybase MySM> 0elocis 4+B! #ni5 dbm

8e also ha$e a +BL database abstraction e5tension allowing you to transparently use any database supported by that e5tension. &dditionally %3% supports 4+B!D the 4pen +atabase !onnection standardD so you can connect to any other database supporting this world standard.

PHP (#, h # #.'',+! 8,+ ! (<"*5 !, ,!h)+ #)+7"/)# 1

#sing protocols such as >+&%D IM&%D SEM%D EET%D %4%*D 3TT%D !4M on 8indows" and countless others. Bou can also open raw network sockets and interact using any other protocol. %3% has support for the 8++L comple5 data e5change between $irtually all 8eb programming languages. Talking about interconnectionD %3% has support for instantiation of Ha$a objects and using them transparently as %3% objects. Bou can also use our !42B& e5tension to access remote objects. PHP h # )%!+)&)(0 .#)8.( !)%! '+,/)##"*5 8) !.+)# 1

;rom the %4SIL E5tended or %erl regular e5pressions to parsing LM> documents. ;or parsing and accessing LM> documentsD we support the S&L and +4M standards. Bou can use our LS>T e5tension to transform LM> documents.

2.3 L"&"! !",*# ,8 PHP 1

E$erything has limitations or disad$antages and %3% is no e5ception. The following are the limitations of %3% , PHP "# NOT 1CC D '.+) O4B)/! O+")*!)- #/+"'!"*5 ( *5. 5) 1

But in near future %3% may support 7((O object oriented scripting %3% may imitate most of the synta5 of Ha$a language". %3% already imitates some features of Ha$a language. In future %3% language will imitate most features of Ha$a language and Ha$a programmers will lo$e %3%. &nd %3% will ha$e ja$a keywords like classD e5tendsD interfaceD implementsD publicD protectedD pri$ate etc..". PHP 3"(( NOT 5"7) !h) ')+8,+& */) ,8 ?C? ,+ ?CEE? ( *5. 5) 1

Because it is scripting language and is interpreted it will be a bit slower than the optimiIed C!PPC programs. ;or top performanceD you should use C!PPC and fast)!/I with databaseFwebser$er connection pooling and use !PP compiler optimiIer C)4*C options. @end optimiIer in %3% : will speed up the performance of %3% and bring it $ery close to optimiIed C!C code . But note a point that %3% was designed for $ery 2apid 8eb)&pplication +e$elopment tool. If it takes about * months to code a web application in !PPD then using %3% you can de$elop the same web application in just : daysQQ &nd with Iend optimiIerD the speed of e5ecution of %3% will be $ery close to that of equi$alent !PP programQQ 3enceD there is really no ad$antage in using !F!PP for web de$elopment. %3% itself is written in 7((O C!C language.

2.4

C,&' +"#,*# 3"!h ,!h)+ ( *5. 5)# 1

2.4.1 F R) #,*# Wh0 PHP "# 6)!!)+ !h * ASP 1

&cti$e Ser$er %ages &S%" is MicrosoftGs technology for displaying dynamic web pages. &S% supports multiple programming languagesN the most commonly used is 0BScript. %3% is the open source alternati$e to &S% that runs on multiple operating systemsD incuding >inu5 and 8indows. &S% is a good and useful technologyD but in the long runD %3% will pro$e superior )) both technically and in popularity. There are se$en reasons. 1. S'))- S'))- S'))- 1 &S% will probably ne$er be as fast as %3%. &S% is built on a !4M)based architecture. 8hen an &S% programmer uses 0BScriptD he is running a !4M object. 8hen he writes to the clientD heGs calling the 2esponse !4M objectGs 8rite method. 8hen he accesses a databaseD he uses another !4M object to do so. 8hen he accesses the file systemD another !4M object is called. &ll this !4M o$erhead adds up and slows things down. In %3% modulesD e$erything runs in %3%Gs memory space. This means that %3% code will run faster because there is no o$erhead of communicating with different !4M objects in different processes. 2. S.')+",+ M)&,+0 M * 5)&)*! 1 In &S%Gs model in IIS :"D if an &S% file Fheader.asp Fis included into '( web pagesD then '( compiled copies of that Fheader.asp Fare maintained in memory. IIS - has implemented an impro$ed memory management modelD but only programmers who are using 8indows '((( can upgrade because it is not backward compatible with IIS :D and 8indows ET :.( cannot run IIS -. This means that most IIS webser$ers are still stuck with the inferior memory management model. This is unlike %3%D which only loads include files that are required. 3. N, H"--)* C,#!# 3"!h PHP 1 4ne of the things you hate most when buying anything is hidden costs. Bou buy a car and you ha$e to replace the engine. Bou buy a house and ha$e to retile the leaking roof. 8ellD

buying &S% is a bit like that. Eeed encryption )) buy &S%Encrypt. Eeed email management )) buy Ser$er4bjectGs MMail. Eeed file uploading 6 buy Software &rtisans S&);ile#p. &ll this is built into %3% for free. 4. M0S=L & <)# "! /,,()+ 1 %3%Gs integration with MySM> is simply fantastic. There are lots of %3% tools to manage and maintain MySM> databases. The feature set is complete compared to other databases. 8e ha$e $ery useful functions like mysqlRinsertRid and mysqlRaffectedRrows which are not a$ailable for other database products. &S% and %3% are both $ery good solutions for mid)range web sites. 8hat makes %3% stand out is the tight integration with MySM>. MySM> is also tuned for mid)range web)sitesD where selecting and pumping loads of data is more important than transaction support. This transaction support allows the programmer to synchronise updates on multiple tablesN which the majority of web sites do not require. 8hen we compare databases Microsoft &ccess is much slower than MySM>. SM> Ser$er = and 4racle are nearly as fastD but much too e5pensi$e if you donGt need the transaction support. Most 8eb sites ser$e thousands of 8eb pages a dayD but perform fewer data updates. &nd a typical data transaction is simple single table update for user logins or forum posts. So a database with speedy SE>E!Ts and lousy IESE2Ts and #%+&TEs like MySM> is a good trade)off in this en$ironment. G. C(,#)+ !, H 7 ICEE S!0() ,8 P+,5+ &&"*5 1 4ne can agree that you wonGt con$ince a hard)core 0isual Basic programmer to switch to %3% just because %3% has ! or Ha$a style for)loopsD curly)braces and ). But you could con$ince someone who likes !PP or Ha$a that %3% is a better or easier language to learn than 0BScript. %3% also has good support for modular programming in classes. #sage of classes is still rare in 0BScript because of its heritage. %3%Gs common heritage with Ha$a and !PP ensures a large body of programmers who uses classes all the time. J. N, Sh,3 S!,'')+ 6.5# 1

3a$e you e$er asked Microsoft to fi5 a bug in &S%9 If you arenGt a large corporation like BoeingD the chances of getting that fi5 quickly are pretty low. &nd if it is a show)stopper of a bugD where nothing will work if this bug is not fi5edD what are you going to do9 8ith %3%D e$en if you donGt ha$e the e5pertise in)house to fi5 the bugD you can definitely hire the e5pertise. There are no show)stoppers in %3%. Bour in$estment is protected by the 4pen Source nature of %3%. F. C+,## P( !8,+& M"5+ !",* S!+ !)50 1 Microsoft is constantly tuning &S%. The ne5t generationD called &S%P is being pre$iewed now. They are fi5ing some of the criticisms that ha$e been mentioned. But there is also no doubt that Microsoft aims to lock you down to use their products.

2.4.2

C,&' +"*5 PHP 3"!h P)+( 8,+ D0* &"/ W)4 P 5)# 1

%erl is one of the most useful programming languages e$er created. The email system you may use at work is may be glued together by %erl scripts. The regular e5pression support in %erl is the best in the world. 3owe$er for generating web pages %erl has a lot of deficiencies compared to %3%. 3ereGs why... 1. S/ ("*5 !h) L) +*"*5 C.+7) 1 & typical web programmer has to be familiar with both client)side and ser$er)side scripting. That means the person needs to be familiar with 3TM>D Ha$ascript and at least one ser$er)side language. 4ne can ad$ocate HScript as the ser$er)scripting language when using &S% because the student should ha$e less to learn. #nfortunately beginners always get client and ser$er scripting confused because HScript is nearly identical to Ha$ascript. So itGs better for beginners to learn a ser$er)side language thatGs slightly different from Ha$ascript. %3% is $ery easy to learn because the core language of %3% is quite smallD and the constructs are similar to Ha$ascript. &s a bonusD many basic 3TT% concepts are built

into the language. ;or e5ampleD 3TT%D %4ST and /ET $ariables can be treated as global $ariablesD which seems quite natural to beginners. %eople who are familiar with Ha$ascript will ha$e no problems learning %3%. It has been said that %erl is easy to learn. That may be trueD but the %erl style of programming is uniqueD and quite unlike Ha$ascript. &ccessing %4ST and /ET $ariables in %erl also requires either detailed knowledge of either 3TT% header formats or one of many %erl !/I libraries. 2. PHP9 M,#)# *- !h) S)' + !",* ,8 C,-) *- D ! 1 4ne of the first code management techniques we are taught or stumble upon" is separating code from data. This allows us to make changes to the code or data without affecting the other. %3% wisely uses the FSltN9php 9 Ftags to indicate CFcode insideFC. So just like Moses di$ided the 2ed SeaD we ha$e %3% di$iding the code from the 3TM> for easy management. In %erlD you are encouraged to use print statements to generate all your 3TM>. True you can implement templates in %erl to separate code and 3TM>D but ?(O of sample %erl code that you download doesnGt do that. 3. S'))-9 S'))-9 S'))- 1 The general consensus is that %3% is faster as e5plained in the section '.:.7. 4. M !.+"!0 1 %3% owes a lot to %erl. %3% was first prototyped using %erl. %3% still shows traces of its %erl ancestry in its string manipulation features. &nd it is here that %erl has the edge on %3%. %3% is a younger language. %erl has much more depth in terms of supportD tutorials and modules a$ailableD and maturity of the code. There are definitely more %erl e5perts than %3% gurus.

INTERACTION WE6

OF

PHP

WITH

SER>ERS

3.1

C,**)/!"*5 !, O!h)+ S)+7)+# 1

If your web ser$er requires ser$ices running on other ser$ersD it is possible that those ser$ers become the bottleneck. The most common e5ample of this is a slow database ser$er that is ser$icing too many complicated SM> requests from multiple web ser$ers.

T.*"*5 Y,.+ W)4 S)+7)+ 8,+ PHP 1

3ow to get the best %3% performance for the two most common web ser$ers in use todayD &pache 7.* and IIS. & lot of the ad$ice here is rele$ant for ser$ing 3TM> also.

3.1.1 A' /h) 1.3 1


&pache 7.* is a$ailable on both #ni5 and 8indows. It is the most popular web ser$er in the world. &pache uses a pre-forking model for web ser$ing. 8hen &pache starts upD it creates multiple child processes that handle 3TT% requests. The initial parent process acts like a guardian angelD making sure that all the child processes are working properly and coordinating e$erything. &s more 3TT% requests come inD more child processes are spawned to process them. &s the 3TT% requests slow downD the parent will kill the idle child processesD freeing up resources for other processes. The beauty of this scheme is that it makes &pache e5tremely robust. E$en if a child process crashesD the parent and the other child processes are insulated from the crashing child. The pre)forking model is not as fast as some other possible designsD but that it is Cmuch ado about nothingC on a ser$er ser$ing %3% scripts because other bottlenecks will kick in long before &pache performance issues become significant. The robustness and

reliability of &pache is more important. &pache '.( will offer impro$ed multi)threaded supportD addressing most of the criticisms made against the pre)forking model. &pache is configured using the httpd.conf file. The following parameters are particularly important in configuring child processes,

D"+)/!"7) Ma5!lients

D)8 .(! '-<

D)#/+"'!",* The ma5imum number of child processes to create. The default means that up to '-< 3TT% requests can be handled concurrently. &ny further connection requests are queued.

StartSer$ers MinSpareSer$ers

The number of child processes to create on startup. The number of idle child processes that should be created. If the number of idle child processes falls to less than this numberD 7 child is created initiallyD then ' after another secondD then : after another secondD and so forth till *' children are created per second.

Ma5SpareSer$ers

7(

If more than this number of child processes are ali$eD then these e5tra processes will be terminated.

Ma52equests%er!hild

Sets the number of 3TT% requests a child can handle before terminating. Setting to ( means ne$er terminate. Set this to a $alue to between 7(( to 7(((( if you suspect memory leaks are occurringD or to free under)utiliIed resources.

;or large sitesD $alues close to the following might be better, MinSpareSer$ers *'

Ma5SpareSer$ers <: &pache on 8indows beha$es differently. Instead of using child processesD &pache uses threads. The abo$e parameters are not used. Instead we ha$e one parameter, ThreadsPerChild which defaults to -(. This parameter sets the number of threads that can be spawned by &pache. &s there is only one child process in the 8indows $ersionD the default setting of -( means only -( concurrent 3TT% requests can be handled. ;or web ser$ers e5periencing higher trafficD increase this $alue to between '-< to 7(':. 4ther useful performance parameters you can change include,

D"+)/!"7) SendBufferSiIe

D)8 .(!

D)#/+"'!",*

Set to 4S +etermines the siIe of the output buffer in bytes" used in default T!%FI% connections. This is primarily useful for congested or slow networks when packets need to be bufferedN you then set this parameter close to the siIe of the largest file normally downloaded. 4ne T!%FI% buffer will be created per client connection. In the original 3TT% specificationD e$ery 3TT% request had

1eep&li$e TonUoffV

4n

to establish a separate connection to the ser$er. To reduce the o$erhead of frequent connectsD the keep)ali$e header was de$eloped. 1eep)ali$es tells the ser$er to reuse the same socket connection for multiple 3TT% requests. If a separate dedicated web ser$er ser$es all imagesD you can disable this option. This technique can substantially impro$e resource utiliIation. The number of seconds to keep the socket connection ali$e.

1eep&li$eTimeout

7-

This time includes the generation of content by the ser$er and acknowledgements by the client. If the client does not

respond in timeD it must make a new connection. This $alue should be kept low as the socket will be idle for e5tended periods otherwise. Ma51eep&li$e2eq uests 7(( Socket connections will be terminated when the number of requests set by Ma51eep&li$e2equests is reached. 1eep this to a high $alue below Ma5!lients or Threads%er!hild. Time4ut *(( +isconnect when idle time e5ceeds this $alue. Bou can set this $alue lower if your clients ha$e low latencies. >imit2equestBody ( Ma5imum siIe of a %#T or %4ST. 4 means there is no limit. If you do not require +ES lookups and you are not using the htaccess file to configure &pache settings for indi$idual directories you can set, W disable +ES lookups, %3% scripts only get the I% address 3ostname>ookups ,88 W disable htaccess checks X+irectory FY &llow4$erride *,*) XF+irectoryY If you are not worried about the directory security when accessing symbolic linksD turn on ;ollowSym>inks and turn off Sym>inksIf4wnerMatch to pre$ent additional lstat " system calls from being made,

4ptions ;ollowSym>inks W4ptions Sym>inksIf4wnerMatch

3.1.2 IIS T.*"*5 1


IIS is a multi)threaded web ser$er a$ailable on 8indows ET and '(((. ;rom the Internet Ser$ices ManagerD it is possible to tune the following parameters,

%erformance Tuning based +etermines how much memory to preallocate for IIS. on the number of hits per day. Bandwidth throttling !ontrols the bandwidth per second allocated per web site. %erformance Tab". %rocess throttling Timeout !ontrols the !%#O a$ailable per 8eb site. %erformance Tab". +efault is ?(( seconds. Set to a lower $alue on a >ocal &rea Eetwork. 8eb Site Tab" In IIS -D you can compress dynamic pagesD html and images. !an 3TT% !ompression be configured to cache compressed static html and images. By default compression is off. 3TT% compression has to be enabled for the entire physical ser$er. To turn it on open the IIS consoleD right)click on the ser$er not any of the subsitesD but the ser$er in the left)hand %erformance Tab".

pane"D and get %roperties. !lick on the Ser$ice tabD and select C!ompress application filesC to compress dynamic contentD and C!ompress static filesC to compress static content. Bou can also configure the default isolation le$el of your web site. In the 3ome +irectory tab under &pplication %rotectionD you can define your le$el of isolation. & highly isolated web site will run slower because it is running as a separate process from IISD while running web site in the IIS process is the fastest but will bring down the ser$er if there are serious bugs in the web site code. 2un %3% web sites using !/ID or using IS&%I with &pplication %rotection set to high.

Mem!acheSiIe

Sets the amount of memory that IIS will use for its file cache. By default IIS will use -(O of a$ailable memory. Increase if IIS is the only application on the ser$er. 0alue is in megabytes.

Ma5!ached;ileSiIe

+etermines the ma5imum siIe of a file cached in the file cache in bytes. +efault is '<'D7:: '-<1".

4bject!acheTT>

Sets the length of time in milliseconds" that objects in the cache are held in memory. +efault is *(D((( milliseconds *( seconds".

Ma5%oolThreads

Sets the number of pool threads to create per processor. +etermines how many !/I applications can run concurrently. +efault is :. Increase this $alue if you are using %3% in !/I mode.

>istenBack>og

Specifies the ma5imum number of acti$e 1eep &li$e connections that IIS maintains in the connection queue. +efault is 7-D and should be increased to the number of concurrent connections you want to support. Ma5imum is '-(.

If the settings are missing from this registry locationD the defaults are being used.

3.2

PHP4@# K)*- E*5"*) 1

The @end Engine is the internal compiler and runtime engine used by %3%:. +e$eloped by @ee$ Suraski and &ndi /utmansD the @end Engine is an abbre$iation of their names. In the early days of %3%:D it worked in the following fashion,

F"5.+) 3.2.1W,+<"*5 O8 Th) K)*- E*5"*) I* Th) E +(0 D 0#

The %3% script was loaded by the @end Engine and compiled into @end opcode. 4pcodesD short for operation codesD are low le$el binary instructions. Then the opcode was e5ecuted and the 3TM> generated sent to the client. The opcode was flushed from memory after e5ecution.

TodayD there are a multitude of products and techniques to help you speed up this process. In the following diagramD we show the how modern %3% scripts workN all the shaded bo5es are optional.

F"5. 3.2.2 W,+<"*5 O8 Th) K)*- E*5"*) F,+ M,-)+* PHP S/+"'!#

%3% Scripts are loaded into memory and compiled into @end opcodes. These opcodes can now be optimiIed using an optional peephole optimiIer called @end 4ptimiIer. +epending on the scriptD it can increase the speed of your %3% code by ()-(O.

;ormerly after e5ecutionD the opcodes were discarded. Eow the opcodes can be optionally cached in memory using se$eral alternati$e open source products and the @end &ccelerator formerly @end !ache"D which is a commercial closed source product. The only opcode cache that is compatible with the @end 4ptimiIer is the @end &ccelerator. &n opcode cache speeds e5ecution by remo$ing the script loading and compilation steps. E5ecution times can impro$e between 7()'((O using an opcode cache.

R 4

PROGRAMMING

WITH

PHP

4.1

L *5. 5) #0*! % 1

0ariable names in %3% are case)sensiti$e. That means that $A and $a are two distinct $ariables. 3owe$erD function names in %3% are not case)sensiti$e. This applies to both built)in functions and user)defined functions. %3% ignores whitespace between tokens. Bou can use spacesD tabsD and newlines to format and indent your code to make it more readable. %3% statements are terminated by semicolons. There are three types of comments in %3%,
/* C style comments */ // C++ style comments # Bourne shell style comments

The !PP and Bourne shell style comments can be inserted anywhere in your code. E$erything from the comment characters to the end of the line is ignored. The !)style comment tells %3% to ignore e$erything from the start of the comment until the end) comment characters are seen. This means that this style of comment can span multiple lines.

4.1.1

> +" 4()# 1

In %3%D all $ariable names begin with a dollar sign $". The $ is followed by an alphabetic character or an underscoreD and optionally followed by a sequence of alphanumeric characters and underscores. There is no limit on the length of a $ariable. 0ariable names in %3% are case)sensiti$e. 3ere are some e5amples,
$i $counter $first_name $_TMP

In %3%D unlike in many other languagesD you do not ha$e to e5plicitly declare $ariables. %3% automatically declares a $ariable the first time a $alue is assigned to it. %3% $ariables are untypedN you can assign a $alue of any type to a $ariable.

4.1.2

D0* &"/ > +" 4()# 1

Sometimes it is useful to set and use $ariables dynamically. EormallyD you assign a $ariable like this,
$var = "hello"

Eow letGs say you want a $ariable whose name is the $alue of the $var $ariable. Bou can do that like this,
$$var = "!orl""

%3% parses $$var by first dereferencing the innermost $ariableD meaning that $var becomes "hello". The e5pression that is left is then $"hello"D which is just $hello. In other wordsD we ha$e just created a new $ariable named hello and assigned it the $alue
"!orl"".

Bou can nest dynamic $ariables to an infinite le$el in %3%D although once you

get beyond two le$elsD it can be $ery confusing for someone who is trying to read your code. There is a special synta5 for using dynamic $ariables inside quoted strings in %3%,

echo "#ello $$$var%"

This synta5 is also used to help resol$e an ambiguity that occurs when $ariable arrays are used. Something like $$var&'( is ambiguous because it is impossible for %3% to know which le$el to apply the array inde5 to. $$$var&'(% tells %3% to dereference the inner le$el first and apply the array inde5 to the result before dereferencing the outer le$el. $
$$var%&'(D

on the other handD tells %3% to apply the inde5 to the outer le$el.

+ynamic $ariables may not initially seem that usefulD but there are times when they can shorten the amount of code you need to write to perform certain tasks. ;or e5ampleD say you ha$e an associati$e array that looks like this,
$array&"a)c"( = "#ello" $array&""ef"( = "!orl""

&ssociati$e arrays like this are returned by $arious functions in the %3% modules.
mys*l_fetch_array+ ,

is one e5ample. The indices in the array usually refer to fields

or entity names within the conte5t of the module you are working with. It can be handy to turn these entity names into real %3% $ariablesD so you can refer to them as simply $a)c and $"ef. This can be done as follows,
-hile+list+$in"e./$value, = each+$array,, $ $$in"e. = $value %

4.1.3

D ! T0')# 1

%3% pro$ides three primiti$e data types, integersD floating point numbersD and strings. In additionD there are two compound data types, arrays and objects. I*!)5)+# 1

Integers are whole numbers. The range of integers in %3% is equi$alent to the range of the lon0 data type in !. 4n *')bit platformsD integer $alues can range from )'D7:=D:A*D<:A to P'D7:=D:A*D<:=. %3% automatically con$erts larger $alues to floating

point numbers if you happen to o$erflow the range. &n integer can be e5pressed in decimal base)7("D he5adecimal base)7<"D or octal base)A". ;or e5ample,
$"ecimal='1 $he.=2.'2 $octal=232

F(, !"*5 P,"*! N.&4)+# 1

;loating point numbers represent decimal $alues. The range of floating point numbers in %3% is equi$alent to the range of the "ou)le type in !. 4n most platforms a double can range from 7.=E)*(A to 7.=EP*(A. & double may be e5pressed either as a regular number with a decimal point or in scientific notation. ;or e5ample,
$var=242'5 $var='542678

Eote that %3% also has a set of functions known as the B! binary calculator" functions. These functions can manipulate arbitrary precision numbers. If you are dealing with $ery large numbers or numbers that require a high degree of precisionD you should use these functions. S!+"*5# 1

& string is a sequence of characters. & string can be delimited by single quotes or double quotes,
9P#P is cool9 "#ello/ !orl":"

+ouble)quoted strings are subject to $ariable substitution and escape sequence handlingD while single quotes are not. ;or e5ample,
$a="!orl"" echo "#ello;t$a;n"

This displays C3elloC followed by a tab and then C8orldC followed by a newline. In other wordsD $ariable substitution is performed on the $ariable $a and the escape sequences are con$erted to their corresponding characters. !ontrast that with,

echo 9#ello;t$a;n9

In this caseD the output is e5actly C3elloZt[aZnC. There is no $ariable substitution or handling of escape sequences. The following table shows the escape sequences understood by %3%,

E#/ ') S)L.)*/)


;n ;t ;r ;; ;$

M) *"*5 Eewline Tab !arriage return Backslash +ollar sign

A++ 0# 1

&n array is a compound data type that can contain multiple data $aluesD inde5ed either numerically or with strings. ;or e5ampleD an array of strings can be written like this,
$var&2(="#ello" $var&'(="!orl""

Eote that when you assign array elements like thisD you do not ha$e to use consecuti$e numbers to inde5 the elements. &s a shortcutD %3% allows you to add an element onto the end of an array without specifying an inde5. ;or e5ample,
$var&(="Test"

%3% picks the ne5t logical numerical inde5. In this caseD the CTestC element is gi$en the inde5 ' in our $var array, if the array has non)consecuti$e elementsD %3% selects the inde5 $alue that is one greater than the current highest inde5 $alue. This auto)inde5ing

feature is most useful when dealing with multiple)choice 3TM> <=6>6CT? form elementsD as weGll see in a later e5ample. &lthough strings are a primiti$e data typeD it is actually possible to treat a string as a compound data typeD where each character in the string can be accessed separately. In other wordsD you can think of a string as an array of charactersD where the first character is at inde5 (. ThusD you can pick the third character out of a string with,
$strin0&3(

&rrays can also be inde5ed using stringsN these kinds of arrays are called associative arrays ,
$var&"@anuary"(=' $var&"Ae)ruary"(=3

In factD you can use a mi5 of numerical and string indices with a single array. That is because internally %3% treats all arrays as hash tables and the hashD or inde5D can be whate$er you want. &ll arrays in %3% can be tra$ersed safely with the following mechanism,
-hile+list+$Bey/$value,=each+$array,, $ echo "array&$Bey(=$value<)r?;n" %

This is the most common way to loop through each element of an arrayD whether it is a linear or an associati$e array. %3% pro$ides a number of array manipulation functionsN these are detailed later in the C;unction 2eferenceC section. O4B)/!# 1

&n object is a compound data type that can contain any number of $ariables and functions. %3%Gs support for objects is $ery basic in 0ersion *. %3% 0ersion : will impro$e the object)oriented capabilities of %3%. In %3% *.( the object)oriented support is designed to make it easy to encapsulate data structures and functions in order to package them into reusable classes. 3ereGs a simple e5ample,

class test $ var $str = "#ello !orl"" function init+$str, $ $this7?str = $str % % $class = ne- test Crint $class7?str $class7?init+"#ello", Crint $class7?str

This code creates a test object using the new operator. Then it sets a $ariable called str within the object. In object)speakD a $ariable in an object is known as a property of that object. The test object also defines a functionD known as a methodD called init+ ,. This method uses the special)purpose $this $ariable to change the $alue of the str property within that object. If you are familiar with object)oriented programmingD you should recogniIe that %3%Gs implementation is minimal. %3%* does not support multiple inheritanceD data protection or encapsulation"D and destructors. %3% does ha$e inheritance and constructorsD though. 6,,() * > (.)# 1

E$ery $alue in %3% has a boolean truth $alue true or false" associated with it. This $alue is typically used in control structuresD like if/else and for. The boolean $alue associated with a data $alue is determined as follows,

;or an integer or floating point $alueD the boolean $alue is false if the $alue is 2N otherwise the boolean $alue is true. ;or a string $alueD the boolean $alue is false if the string is emptyN otherwise the boolean $alue is true. ;or an arrayD the boolean $alue is false if the array has no elementsN otherwise the boolean $alue is true. ;or an objectD the boolean $alue is false if the object has no defined $ariables or functionsN otherwise the boolean $alue is true. ;or an undefined object a $ariable that has not been defined at all"D the boolean $alue is false.

%3% has two built)in keywordsD true and falseD where true represents the integer $alue
'

and false represents the empty string.

4.1.4

T0') C #!"*5 1

0ariables in %3% do not need to be e5plicitly typed. %3% sets the type when a $ariable is first used in a script. Bou can e5plicitly specify a type using !)style casting. ;or e5ample,
$var = +int, "'38a)c"

8ithout the +int, in this e5ampleD %3% creates a string $ariable. 8ith the e5plicit castD howe$erD we ha$e created an integer $ariable with a $alue of 7'*. The following table shows the a$ailable cast operators in %3%,

O')+ !,+#
+int,D +inte0er, +real,D +"ou)le,D +float, +strin0, +array, +o)Dect,

F.*/!",* !ast to an integer !ast to a floating point number !ast to a string !ast to an array !ast to an object

&lthough they are not usually neededD %3% does pro$ide the following built)in functions to check $ariable types in your program, 0ettyCe+ ,D is_lon0+ ,D is_"ou)le+ ,D
is_strin0+ ,D is_array+ ,D

and is_o)Dect+ ,.

4.1.G

E%'+)##",*# 1

&n e5pression is the basic building block of the language. &nything with a $alue can be thought of as an e5pression. E5amples include,
E E+E $a

$a==E s*rt+F,

By combining many of these basic e5pressionsD you can build larger and more comple5 e5pressions. Eote that the echo statement weG$e used in numerous e5amples cannot be part of a comple5 e5pression because it does not ha$e a return $alue. The Crint statementD on the other handD can be used as part of comple5 e5pressionD as it does ha$e a return $alue. In all other respectsD echo and Crint are identical))they output data.

4.1.G

O')+ !,+# 1

E5pressions are combined and manipulated using operators. The following table shows the operators a$ailable in %3%D along with their precedence %" and associati$ity &". The following table lists the operators from highest to lowest precedence. These operators should be familiar to you if you ha$e any !D Ha$aD or %erl e5perience.

O')+ !,+#
:D GD ++D 77D HD *D /D I +D 7 4 <<D ?? <D <=D ?=D ? ==D := J K

the casting operators" 7< 2ight 7- >eft 7: >eft 7* >eft 7' Eon)associati$e 77 Eon)associati$e 7( >eft ? >eft

L JJ LL M N

A >eft = >eft < >eft conditional operator" - >eft : >eft * >eft ' >eft 7 >eft

=D +=D 7=D *=D /=D I=D K=D 4=D J=D L= An" Oor Pr

4.1.F

C,*!+,( S!+./!.+)# 1

The control structures in %3% are $ery similar to those used by the ! language. !ontrol structures are used to control the logical flow through a %3% script. %3%Gs control structures ha$e two synta5es that can be used interchangeably. The first form uses !)style curly braces to enclose statement blocksD while the second style uses a more $erbose synta5 that includes e5plicit ending statements. The first style is preferable when the control structure is completely within a %3% code block. The second style is useful when the construct spans a large section of intermi5ed code and 3TM>. The two styles are completely interchangeableD howe$erD so it is really a matter of personal preference which one you use.

"8
The if statement is a standard conditional found in most languages. 3ere are the two synta5es for the if statement,
if+expr, $ statements % if+expr,N statements elseif+expr,N

elseif+expr, $ statements statements elseN % statements else $ en"if statements %

The if statement causes particular code to be e5ecuted if the e5pression it acts on is


true.

8ith the first formD you can omit the braces if you only need to e5ecute a single

statement.

#3"!/h
The s-itch statement can be used in place of a lengthy if statement. 3ere are the two synta5es for s-itch,
s-itch+expr, $ case exprN statements )reaB "efaultN statements )reaB % s-itch+expr,N case exprN statements )reaB "efaultN statements )reaB en"s-itch

The e5pression for each case statement is compared against the s-itch e5pression andD if they matchD the code following that particular case is e5ecuted. The )reaB keyword signals the end of a particular caseN it may be omittedD which causes control to flow into the ne5t case. If none of the case e5pressions match the s-itch e5pressionD the "efault case is e5ecuted.

3h"()
The -hile statement is a looping construct that repeatedly e5ecutes some code while a particular e5pression is true,
-hile+expr, $ statements % -hile+expr,N statements en"-hile

The -hile e5pression is checked before the start of each iteration. If the e5pression e$aluates to trueD the code within the loop is e5ecuted. If the e5pression e$aluates to

falseD

howe$erD e5ecution skips to the code immediately following the -hile loop. Eote

that you can omit the curly braces with the first form of the -hile statement if you only need to e5ecute a single statement. It is possible to break out of a running loop at any time using the )reaB keyword. This stops the current loop andD if control is within a nested set of loopsD the ne5t outer loop continues. It is also possible to break out of many le$els of nested loops by passing a numerical argument to the )reaB statement )reaB n" that specifies the number of nested loops it should break out of. Bou can skip the rest of a gi$en loop and go onto the ne5t iteration by using the continue keyword. 8ith continue nD you can skip the current iterations of the n innermost loops.

-,I3h"()
The "oF-hile statement is similar to the -hile statementD e5cept that the conditional e5pression is checked at the end of each iteration instead of before it,
"o $ statements % -hile+expr,

Eote that due to the order of the parts of this statementD there is only one $alid synta5. If you only need to e5ecute a single statementD you can omit the curly braces from the synta5. The )reaB and continue statements work with this statement in the same way that they do with the -hile statement.

8,+
& for loop is a more comple5 looping construct than the simple -hile loop,
for+start_expr statements % for+start_expr statements en"for cond_expr iter_expr, $

cond_expr

iter_expr,N

& for loop takes three e5pressions. The first is the start e5pressionN it is e$aluated once when the loop begins. This is generally used for initialiIing a loop counter. The second e5pression is a conditional e5pression that controls the iteration of the loop. This e5pression is checked prior to each iteration. The third e5pressionD the iterati$e e5pressionD is e$aluated at the end of each iteration and is typically used to increment the loop counter. 8ith the first form of the for statementD you can omit the braces if you only need to e5ecute a single statement. The )reaB and continue statements work with a for loop like they do with a -hile loopD e5cept that continue causes the iterati$e e5pression to be e$aluated before the loop conditional e5pression is checked.

4.1.;

F.*/!",*# 1

& function is a named sequence of code statements that can optionally accept parameters and return a $alue. & function call is an e5pression that has a $alueN its $alue is the returned $alue from the function. %3% pro$ides a large number of internal functions. The C;unction 2eferenceC section lists all of the commonly a$ailable functions. %3% also supports user)definable functions. To define a functionD use the function keyword. ;or e5ample,
function soun"checB+$a/ $)/ $c, $ return "Testin0/ $a/ $)/ $c" %

8hen you define a functionD you need to be careful what name you gi$e it. In particularD you need to make sure that the name does not conflict with any of the internal %3% functions. If you do use a function name that conflicts with an internal functionD you get the following error,
Aatal errorN Can9t re"eclare alrea"y "eclare" function in filename on line N

&fter you define a functionD you call it by passing in the appropriate arguments. ;or e5ample,

echo soun"checB+Q/ E/ 1,

Bou can also create functions with optional parameters. To do soD you set a default $alue for each optional parameter in the definitionD using !PP style. ;or e5ampleD hereGs how to make all the parameters to the soun"checB+ , function optional,
function soun"checB+$a='/ $)=3/ $c=8, $ return "Testin0/ $a/ $)/ $c" %

4.1.;.1

> +" 4() S/,') 1

The scope of a $ariable refers to where in a program the $ariable is a$ailable. If a $ariable is defined in the main part of a %3% script i.e.D not inside a function or a class"D it is in the global scope. Eote that global $ariables are only a$ailable during the current request. The only way to make $ariables in one page a$ailable to subsequent requests to another page is to pass them to that page $ia cookiesD /ET method dataD or %#T method data. To access a global $ariable from inside a functionD you need to use the 0lo)al keyword. ;or e5ample,
function test+ , $ 0lo)al $var echo $var % $var="#ello !orl"" test+ ,

The $R>PBA>= array is an alternati$e mechanism for accessing $ariables in the global scope. This is an associati$e array of all the $ariables currently defined in the global scope,
function test+ , $ echo $R>PBA>=&"var"( % $var="#ello !orl"" test+ ,

E$ery function has its own scope. 8hen you create a $ariable inside of a functionD that $ariable has local scope. In other wordsD it is only a$ailable within the function. In additionD if there is a global $ariable with the same name as a $ariable within a functionD any changes to the function $ariable do not affect the $alue of the global $ariable.

8hen you call a functionD the arguments you pass to the function if any" are defined as $ariables within the functionD using the parameter names as $ariable names. Hust as with $ariables created within a functionD these passed arguments are only a$ailable within the scope of the function.

4.1.;.2

P ##"*5 A+5.&)*!# 1

There are two ways you can pass arguments to a function, by $alue and by reference. To pass an argument by $alueD you pass in any $alid e5pression. That e5pression is e$aluated and the $alue is assigned to the corresponding parameter defined within the function. &ny changes you make to the parameter within the function ha$e no effect on the argument passed to the function. ;or e5ample,
function triCle+$., $ $.=$.*8 return $. % $var='2 $triClevar=triCle+$var,

In this caseD $var e$aluates to 7( when triCle+ , is calledD so $. is set to 7( inside the function. 8hen $. is tripledD that change does not affect the $alue of $var outside the function. In contrastD when you pass an argument by referenceD changes to the parameter within the function do affect the $alue of the argument outside the scope of the function. ThatGs because when you pass an argument by referenceD you must pass a $ariable to the function. Eow the parameter in the function refers directly to the $alue of the $ariableD meaning that any changes within the function are also $isible outside the function. ;or e5ample,
function triCle+$., $ $.=$.*8 return $. % $var='2 triCle+J$var,

The J that precedes $var in the call to triCle+ , causes the argument to be passed by referenceD so the end result is that $var ends up with a $alue of *(.

4.1.;.3

S! !"/ > +" 4()# 1

%3% supports declaring local function $ariables as static. & static $ariable retains its $alue between function callsD but is still accessible only from within the function it is declared in. Static $ariables can be initialiIed and this initialiIation only takes place the first time the static declaration is e5ecuted. Static $ariables are often used as countersD as in this e5ample,
function hitcount+ static $count = 2 ,

if +$count == 2, $ Crint "This is the first time this Ca0e" Crint " has )een accesse"" % else $ Crint "This Ca0e has )een accesse" $count" Crint " times" % $count++

4.1.:

W)4-R)( !)- > +" 4()# 1

%3% automatically creates global $ariables for all the data it recei$es in an 3TT% request. This can include /ET dataD %4ST dataD cookie dataD and en$ironment $ariables. Say you ha$e an 3TM> form that looks as follows,
<APSM ACTTPU="test4ChC8" M6T#PV="PP=T"? <TUPWT TXP6=te.t UAM6=var? </APSM?

8hen the form is submitted to the test.php3 fileD the $var $ariable within that file is set to whate$er the user entered in the te5t field. & $ariable can also be set in a #2> like this,
httCN//your4server/test4ChC8Mvar=#ello+!orl"

8hen the request for this #2> is processedD the $var $ariable is set for the test.php3 page. &ny en$ironment $ariables present in your web ser$erGs configuration are also made a$ailableD along with any !/I)style $ariables your web ser$er might set. The actual set of $ariables $aries between different web ser$ers. The best way to get a list of these $ariables is to use %3%Gs special information tag. %ut the following code in a page and load the page in your browser,
<M ChCinfo+ , M?

Bou should see a page with quite a bit of information about %3% and the machine it is running on. There is a table that describes each of the e5tensions currently enabled in %3%. &nother table shows the current $alues of all the $arious configuration directi$es from your php3.ini file. ;ollowing those two tables are more tables showing the regular en$ironment $ariablesD the special %3% internal $ariablesD and the special en$ironment $ariables that your web ser$er has added. ;inallyD the 3TT% request and response headers for the current request are shown. Sometimes it is con$enient to create a generic form handlerD where you donGt necessarily know all the form element names. To support thisD %3% pro$ides /ETD %4STD and cookie associati$e arrays that contain all of the data passed to the page using the different techniques. These arrays are named
$#TTP_R6T_VATAD $#TTP_PP=T_VATAD $#TTP_CPPYT6_VATAD

respecti$ely. ;or e5ampleD hereGs another way to access the $alue

of the te5t field in our form,


echo $#TTP_PP=T_ZAS=&"var"(

%3% sets global $ariables in a particular order. By defaultD global $ariables are set first from /ET dataD then from %4ST dataD and then finally from cookie data. This means that if you ha$e a form with a field named var that uses the /ET method and a cookie with a
var

$alueD there is just one global $ariable named $var that has the $alue of the cookie

data. 4f courseD you can still get at the /ET data through the $#TTP_R6T_VATA array. The default order can be defined with the 0Cc_or"er directi$e in the php3.ini file.

6I6LIOGRAPHY

R)8)+)*/) 6,,<# 1
7 , Title 6 8ireless 8eb +e$elopment 8ith %3% and 8&% &uthor 6 2ay 2ischpater %ublication 6 &press ' , Title 6 !ore %3% %rogramming &uthor 6 >eon &tkinson %ublication 6

URLM# 1
7, 3: 5: 7: http,FFwww.php.net http://www.dk.php.net http://www.th2.php.net http://www.apache.org ', http,FFwww.mysql.com 4: 6: 8: http://www.pgsql.com http://www.zend.com

http://www.php.resourceinde .com

Das könnte Ihnen auch gefallen