seminar on php.doc

Upload: dheerajdkulkarni

Post on 04-Jun-2018

218 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/14/2019 seminar on php.doc

    1/47

    S E M I N A R

    R E P O R T

    O N

    P H P

    H Y P E R T E X T

    P R E P R O C E S S O R

  • 8/14/2019 seminar on php.doc

    2/47

    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. %rof. / % %otdar %rof. +r. ! 0 1 2aoInternal /uide Seminar coordinator 3.4.+

    DEPARTMENT OF COMPUTER ENGINEERING

  • 8/14/2019 seminar on php.doc

    3/47

    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 "

  • 8/14/2019 seminar on php.doc

    4/47

    C O N T E N T S

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

    7.7 8hat Is %3% 9 (7

    7.' 3ow +id %3% !ome Into Being ('

    7.* 8hy #se %3% 9 ('

    7.: 8hat !an %3% +o 9 (*

    !hapter ', More on %3%

    '.7 ;eatures of %3% (-

    '.7.7 Some More ;eatures (anguage Synta5 '*

    :.7.7 0ariables '*

    :.7.' +ynamic 0ariables ':

    :.7.* +ata Types '-

    :.7.: Typecasting '?

    :.7.- E5pressions *(

    :.7.< 4perators *(

    :.7.= !ontrol Structures *7

    :.7.A ;unctions *:

  • 8/14/2019 seminar on php.doc

    6/47

    :.7.A.7 0ariable Scope *-

    :.7.A.' %assing &rguments *I4/2&%3 :(

    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$elopmentand 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. A* "*!+,/!,+0 )%&'()

    Example

  • 8/14/2019 seminar on php.doc

    7/47

  • 8/14/2019 seminar on php.doc

    8/47

    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

    learning the ! language.

    The data types and structures of %3% are easy to use and understandD %3% knowswhat you mean and can con$ert types automatically.

    ou donGt ha$e to know any special commands to compile your programD it runsright in your web browser.

    ou donGt ha$e to know e$erything there is to know about %3% to start writinguseful programs.

    %3% ser$es as a CwrapperC for many standard ! librariesD which are easily compiledinto 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 towork 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 amaing 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) ) #"!)

  • 8/14/2019 seminar on php.doc

    9/47

    &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 &S%"D

    MacromediaJs !old ;usion and %3% are e5amples of acti$e web ser$ers using ser$er 6

    side scripting.

    There are three main fields where %3% scripts are used.

    S)+7)+-#") #/+"'!"*5

    This is the most traditional and main target field for %3%. ou need three things to make

    this work. The %3% parser !/I or ser$er module"D a web ser$er and a web browser.

    ou need to run the web ser$erD with a connected %3% installation. ou can access the

    %3% program output with a web browserD $iewing the %3% page through the ser$er.

    C,&&* ("*) #/+"'!"*5

    ou can make a %3% script to run it without any ser$er or browser. ou 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)

  • 8/14/2019 seminar on php.doc

    10/47

    side applications you can also use %3%)/T1 to write such programs. ou 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

    I! "# 8#!)+ !, /,) * 8#!)+ !, )%)/!) The same %3% code runs unaltered on different web ser$ers and different operatingsystems. ;unctionality that is standard with %3% is an add)on in other en$ironments.

    PHP "# 8+)) &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 workswith no royalties.

    PHP +*# ,* UNIX9W"*,# :;9 W"*,# NT * !h) M/"*!,#h %3% is designed to integrate with the &pache web ser$er. &pache another freetechnologyD is the most popular web ser$er on the Internet and comes with source codefor #IL and 8indows.

    PHP "# &,"8"() %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". !apableprogrammers may add new functionality easily. The rich set of functions a$ailable in%3% are e$idence they often do.

    PHP # +"!!)* 8,+ ) '5) /+)!",* %erlD ! and Ha$a are $ery good general languages and are certainly capable of dri$ingweb applications. The unfortunate sacrifice these alternati$es make is the ease ofcommunication with the web e5perience. %3% applications may be rapidly and easilyde$eloped because the source code is encapsulated in the web pages themsel$es.

    PHP "# ','(+ Internet ser$ice pro$iders find %3% to be an attracti$e way to allow their customers tocode 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 toanother as well as a choice of de$elopers to add functionality.

  • 8/14/2019 seminar on php.doc

    11/47

    P+,5+&&"*5 #og 0iewer Script pro$ides a quick summaryof the accesses to a set of pages owned by an indi$idual user. In addition to thatD thepackage can be configured to generate a footer on e$ery page which shows accessinformation.

    A//)## C,*!+,(

    & built)in web)based configuration screen handles access control configuration. It ispossible 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. %agescan be password protectedD completely restrictedD logging disabled and more based onthe clientGs domainD browserD e)mail address or e$en the referring document.

    P,#!5+)#S=L S'',+! %ostgres is an ad$anced free 2+BMS. %3% supports embedding %ostgreS> CS>queriesC directly in .html files. 2;!)7A

  • 8/14/2019 seminar on php.doc

    12/47

    >+"()#9 A++0#9 A##,/"!"7) A++0# %3% supports typed $ariablesD arrays and e$en %erl)like associati$e arrays. These can allbe passed from one web page to another using either /ET or %4ST method forms.

    C,*"!",*(#9 Wh"() L,,'#

    %3% supports a full)featured !)like scripting language. ou can ha$eifFthenFelseifFelseFendif conditions as well as while loops and switchFcase statements toguide the logical flow of how the html page should be displayed.

    E%!)*) R)5(+ E%'+)##",*#

    2egular e5pressions are hea$ily used for pattern matchingD pattern substitutions andgeneral string manipulation. %3% supports all common regular e5pression operations.

    R HTTP H))+ C,*!+,(

    The ability to ha$e web pages send customied raw 3TT% headers based on somecondition 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 beused to turn off cacheing or manipulate the last update header of pages.

    O*-!h)-8(0 GIF "&5) /+)!",*

    %3% has support for Thomas BoutellGs /+ image library which makes it possible togenerate /I; images on the fly.

    ISP ?S8) M,)? #'',+!

    %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 newerreleases of %3%. 0isit the main web site at http,FFwww.php.net

    I!@# F+))

    4ne final essential feature. The package is completely free. It is licensed under the/#F/%> which allows you to use the software for any purposeD commercial or

    otherwise.

    A"("!0 !, "*/() 8"()#

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

  • 8/14/2019 seminar on php.doc

    13/47

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

    2.2 A7*!5)# ,8 PHP

    PHP /* ) #) ,* (( &B,+ ,')+!"*5 #0#!)

    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 etscape 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#!)& * ) #)+7)+

    ;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 realied 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

    %3%Gs abilities include outputting imagesN %+; files and e$en ;lash mo$ies using libswf

    and Ming" generated on the fly. ou 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 #'',+!# ") +*5) ,8 !#)#

  • 8/14/2019 seminar on php.doc

    14/47

    8riting a database)enabled web page is incredibly simple. The following databases are

    currently supported,

    &dabas + Ingres 4racle 4!I= and 4!IA"

    +base InterBase 4$rimosEmpress ;rontBase %ostgreS>

    ;ile%ro read)only" mS> Solid

    3yperwa$e +irect MS)S> Sybase

    IBM +B' MyS> 0elocis

    Informi5 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,+ !(+&%D IM&%D SM%D T%D %4%*D 3TT%D !4M on

    8indows" and countless others. ou 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. ou can also use our !42B& e5tension to access remote objects.

    PHP h# )%!+)&)(0 #)8( !)%! '+,/)##"*5 8)!+)#

    ;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. ou

    can use our LS>T e5tension to transform LM> documents.

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

  • 8/14/2019 seminar on php.doc

    15/47

    E$erything has limitations or disad$antages and %3% is no e5ception. The following are

    the limitations of %3% ,

    PHP "# NOT 1 '+) OB)/! O+")*!) #/+"'!"*5 (*55)

    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 "(( NOT 5"7) !h) ')+8,+&*/) ,8 ?C? ,+ ?C? (*55)

    Because it is scripting language and is interpreted it will be a bit slower than the

    optimied C!PPC programs. ;or top performanceD you should use C!PPC and fast)!/I

    with databaseFwebser$er connection pooling and use !PP compiler optimier C)4*C

    options. @end optimier in %3% : will speed up the performance of %3% and bring it $ery

    close to optimied 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 end optimierD 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,&'+"#,*# "!h ,!h)+ (*55)#

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

  • 8/14/2019 seminar on php.doc

    16/47

    &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'))

    &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)&)*!

    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 T :.( 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,#!# "!h PHP

    4ne of the things you hate most when buying anything is hidden costs. ou buy a car and

    you ha$e to replace the engine. ou buy a house and ha$e to retile the leaking roof. 8ellD

  • 8/14/2019 seminar on php.doc

    17/47

    buying &S% is a bit like that. eed encryption )) buy &S%Encrypt. eed email

    management )) buy Ser$er4bjectGs Mail. eed file uploading 6 buy Software &rtisans

    S&);ile#p. &ll this is built into %3% for free.

    4. M0S=L &

  • 8/14/2019 seminar on php.doc

    18/47

    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%. our in$estment is protected by the

    4pen Source nature of %3%.

    . C+,## P(!8,+& M"5+!",* S!+!)50

    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 "!h P)+( 8,+ D0*&"/ W) P5)#

    %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 webpages %erl has a lot of deficiencies compared to %3%. 3ereGs why...

    1. S/("*5 !h) L)+*"*5 C+7)

    & 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

  • 8/14/2019 seminar on php.doc

    19/47

    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!

    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 FltN9php 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'))

    The general consensus is that %3% is faster as e5plained in the section '.:.7.

    4. M!+"!0

    %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.

  • 8/14/2019 seminar on php.doc

    20/47

    C H A P T E R 3

    I N T E R A C T I O N O F P H P W I T H

    W E 6 S E R > E R S

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

    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 S> requests from multiple web ser$ers.

    T*"*5 Y,+ W) S)+7)+ 8,+ PHP 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

    &pache 7.* is a$ailable on both #ni5 and 8indows. It is the most popular web ser$er in

    the world. &pache uses apre-forkingmodel 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

  • 8/14/2019 seminar on php.doc

    21/47

    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) D)8(! D)#/+"'!",*

    Ma5!lients '-< 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 - The number of child processes to create on startup.

    MinSpareSer$ers - 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 leaksare occurringD or to free under)utilied resources.

    ;or large sitesD $alues close to the following might be better,

    MinSpareSer$ers *'

  • 8/14/2019 seminar on php.doc

    22/47

    Ma5SpareSer$ers

  • 8/14/2019 seminar on php.doc

    23/47

    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. ou can set

    this $alue lower if your clients ha$e low latencies.

    >imit2equestBody ( Ma5imum sie of a %#T or %4ST. 4 means there is no

    limit.

    If you do not require +S lookups and you are not using the htaccess file to configure

    &pache settings for indi$idual directories you can set,

    W disable +S 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,

  • 8/14/2019 seminar on php.doc

    24/47

    4ptions ;ollowSym>inks

    W4ptions Sym>inksIf4wnerMatch

    3.1.2 IIS T*"*5

    IIS is a multi)threaded web ser$er a$ailable on 8indows T and '(((. ;rom the Internet

    Ser$ices ManagerD it is possible to tune the following parameters,

    %erformance Tuning based

    on the number of hits per

    day.

    +etermines how much memory to preallocate for IIS.

    %erformance Tab".

    Bandwidth throttling !ontrols the bandwidth per second allocated per web site.

    %erformance Tab".

    %rocess throttling !ontrols the !%#O a$ailable per 8eb site. %erformance Tab".

    Timeout +efault is ?(( seconds. Set to a lower $alue on a >ocal &rea

    etwork. 8eb Site Tab"

    3TT% !ompressionIn IIS -D you can compress dynamic pagesD html and images. !an

    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

  • 8/14/2019 seminar on php.doc

    25/47

    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.

    ou 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!acheSie 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;ileSie +etermines the ma5imum sie of a file cached in the file cache in bytes.

    +efault is '

  • 8/14/2019 seminar on php.doc

    26/47

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

    3.2 PHP4@# )* E*5"*)

    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,+ generated sent to the client. The opcode was flushed from

    memory after e5ecution.

  • 8/14/2019 seminar on php.doc

    27/47

    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,+

  • 8/14/2019 seminar on php.doc

    28/47

    ;ormerly after e5ecutionD the opcodes were discarded. ow 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 4ptimier 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.

    C H A P T E R 4

    P R O G R A M M I N G W I T H P H P

    4.1 L*55) #0*!%

    0ariable names in %3% are case)sensiti$e. That means that $A and $aare 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. ou 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.

  • 8/14/2019 seminar on php.doc

    29/47

    4.1.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*&"/ >+"()#

    Sometimes it is useful to set and use $ariables dynamically. ormallyD you assign a

    $ariable like this,

    $var = "hello"

    ow letGs say you want a $ariable whose name is the $alue of the $var$ariable. ou 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 helloand assigned it the $alue

    "!orl". ou can nest dynamic $ariables to an infinite le$el in %3%D although once youget 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%,

  • 8/14/2019 seminar on php.doc

    30/47

    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 innerle$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.

    mysl_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,

    -hilelist$ine.$value, = each$array,, $$ine. = $value%

    4.1.3 D! T0')#

    %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)+#

    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

  • 8/14/2019 seminar on php.doc

    31/47

    point numbers if you happen to o$erflow the range. &n integer can be e5pressed in

    decimal base)7("D he5adecimal base)7

  • 8/14/2019 seminar on php.doc

    32/47

    echo 9ello;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))*/) M)*"*5

    ;n ewline

    ;t Tab

    ;r !arriage return

    ;; Backslash

    ;$ +ollar sign

    A++0# &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"

    ote 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 $vararray, 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

  • 8/14/2019 seminar on php.doc

    33/47

    feature is most useful when dealing with multiple)choice 3TM> 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&"e)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,

    -hilelist$ey$value,=each$array,, echo "array&$ey(=$value

  • 8/14/2019 seminar on php.doc

    34/47

    class test var $str = "ello !orl"function init$str, $this7?str = $str%%$class = ne- testrint $class7?str$class7?init"ello",rint $class7?str

    This code creates a testobject 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 testobject also defines a functionD known as a methodD called init ,. This

    method uses the special)purpose $this$ariable to change the $alue of the strproperty

    within that object.

    If you are familiar with object)oriented programmingD you should recognie 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,,()* >()# E$ery $alue in %3% has a boolean truth $alue trueor 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 falseif

    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 isfalse

    if the object has no

    defined $ariables or functionsN otherwise the boolean $alue istrue.

    ;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 trueand falseD where truerepresents the integer $alue

    'and falserepresents the empty string.

  • 8/14/2019 seminar on php.doc

    35/47

    4.1.4 T0') C#!"*5

    0ariables in %3% do not need to be e5plicitly typed. %3% sets the type when a $ariable is

    first used in a script. ou 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')+!,+# F*/!",*

    int,D inte0er, !ast to an integer

    real,D ou)le,D float, !ast to a floating point number

    strin0, !ast to a string

    array, !ast to an array

    o)Dect, !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, 0ettye ,D is_lon0 ,D is_ou)le ,D

    is_strin0 ,D is_array ,D and is_o)Dect ,.

    4.1. E%'+)##",*#

    &n e5pression is the basic building block of the language. &nything with a $alue can be

    thought of as an e5pression. E5amples include,

    EE+E$a

  • 8/14/2019 seminar on php.doc

    36/47

    $a==EsrtF,

    By combining many of these basic e5pressionsD you can build larger and more comple5

    e5pressions.

    ote 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 rintstatementD on the

    other handD can be used as part of comple5 e5pressionD as it does ha$e a return $alue. In

    all other respectsD echoand rintare identical))they output data.

    4.1. O')+!,+#

    E5pressions are combined and manipulated using operators. The following table showsthe 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')+!,+# P A

    :D GD ++D 77D HD the casting operators" 7< 2ight

    *D /D I 7- >eft

    +D 74 7: >eft

  • 8/14/2019 seminar on php.doc

    37/47

    L A >eft

    JJ = >eft

    LL < >eft

    Nconditional operator" - >eft

    =D +=D 7=D *=D /=D I=D K=D 4=D J=D L= : >eft

    An * >eft

    Oor ' >eft

    r 7 >eft

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

    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 ifstatement is a standard conditional found in most languages. 3ere are the two

    synta5es for the ifstatement,

    ifexpr, ifexpr,Nstatements statements% elseifexpr,N

  • 8/14/2019 seminar on php.doc

    38/47

    elseifexpr, statementsstatements elseN% statementselse enifstatements%

    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.

    #"!/h

    The s-itchstatement can be used in place of a lengthy ifstatement. 3ere are the two

    synta5es for s-itch,

    s-itchexpr, s-itchexpr,Ncase exprN case exprN statements statements )rea )reaefaultN efaultN statements statements )rea )rea% ens-itch

    The e5pression for each casestatement is compared against the s-itche5pression andD

    if they matchD the code following that particular case is e5ecuted. The )rea keywordsignals the end of a particular caseN it may be omittedD which causes control to flow into

    the ne5t case. If none of the casee5pressions match the s-itche5pressionD the efault

    case is e5ecuted.

    h"()

    The -hilestatement is a looping construct that repeatedly e5ecutes some code while a

    particular e5pression is true,

    -hileexpr, -hileexpr,Nstatements 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

  • 8/14/2019 seminar on php.doc

    39/47

    falseD howe$erD e5ecution skips to the code immediately following the -hileloop. ote

    that you can omit the curly braces with the first form of the -hilestatement if you only

    need to e5ecute a single statement.

    It is possible to break out of a running loop at any time using the )reakeyword. 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 )reastatement )rean" that specifies the number of nested

    loops it should break out of. ou 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 ninnermost loops.

    ,h"()

    The oF-hile statement is similar to the -hilestatementD e5cept that the conditional

    e5pression is checked at the end of each iteration instead of before it,

    o statements

    % -hileexpr,

    ote that due to the order of the parts of this statementD there is only one $alid synta5. Ifyou only need to e5ecute a single statementD you can omit the curly braces from the

    synta5. The )reaand continuestatements work with this statement in the same way

    that they do with the -hilestatement.

    8,+

    & forloop is a more comple5 looping construct than the simple -hileloop,

    forstart_expr cond_expr iter_expr, statements%forstart_expr cond_expr iter_expr,Nstatements

    enfor

  • 8/14/2019 seminar on php.doc

    40/47

    & forloop takes three e5pressions. The first is the start e5pressionN it is e$aluated once

    when the loop begins. This is generally used for initialiing 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 forstatementD you can omit the braces if you

    only need to e5ecute a single statement.

    The )rea and continue statements work with a forloop like they do with a -hile

    loopD e5cept that continuecauses the iterati$e e5pression to be e$aluated before the loop

    conditional e5pression is checked.

    4.1.; F*/!",*#

    & 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 functionkeyword. ;or

    e5ample,

    function sounchec$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,

    atal errorN Can9t reeclare alreay eclare function in filenameon

    line N

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

    e5ample,

  • 8/14/2019 seminar on php.doc

    41/47

    echo sounchecQ E 1,

    ou 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 thesounchec ,

    function optional,

    function sounchec$a=' $)=3 $c=8, return "Testin0 $a $) $c"%

    4.1.;.1 >+"() S/,')

    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. ote 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)alkeyword. ;or

    e5ample,

    function test , 0lo)al $varecho $var

    %$var="ello !orl"test ,

    The $R>BA>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>BA>&"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.

  • 8/14/2019 seminar on php.doc

    42/47

    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&)*!#

    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 trile$., $.=$.*8return $.%$var='2$trilevar=trile$var,

    In this caseD $vare$aluates to 7( when trile ,is calledD so $.is set to 7( inside the

    function. 8hen $.is tripledD that change does not affect the $alue of $varoutside 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. ow 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 trile$., $.=$.*8return $.%$var='2trileJ$var,

  • 8/14/2019 seminar on php.doc

    43/47

    The Jthat precedes $varin the call to trile ,causes the argument to be passed by

    referenceD so the end result is that $varends up with a $alue of *(.

    4.1.;.3 S!!"/ >+"()#

    %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 initialied and this initialiation only takes place the

    first time the staticdeclaration is e5ecuted. Static $ariables are often used as countersD

    as in this e5ample,

    function hitcount ,

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

    4.1.: W)-R)(!) >+"()#

    %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,

  • 8/14/2019 seminar on php.doc

    44/47

    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,

  • 8/14/2019 seminar on php.doc

    45/47

    6 I 6 L I O G R A P H Y

  • 8/14/2019 seminar on php.doc

    46/47

    R)8)+)*/) 6,,

  • 8/14/2019 seminar on php.doc

    47/47