Download - Server-side Web Development With PHP
-
7/26/2019 Server-side Web Development With PHP
1/66
7-Server-side web development withPHP
1
-
7/26/2019 Server-side Web Development With PHP
2/66
Origins and Uses of PHP Origins
Rasmus Lerdorf - 199
!eveloped to allow him to tra"# visitors to his $ebsite
PHP was originall% an a"ron%m for PersonalHomePage& but later it be"ame PHP: Hypertext
Preprocessor
PHP is used for form handling& 'le pro"essing&and database a""ess
(
-
7/26/2019 Server-side Web Development With PHP
3/66
Overview of PHP
PHP is a server-side s"ripting language whose s"ripts are embedded in H)*Ldo"uments
PHP is an alternative to +SP,.) and /SP
)he PHP pro"essor has two modes0 "op% H)*L2
$hen the PHP pro"essor 'nds mar#up "ode whi"h ma% in"lude embedded "lient-side s"ript2 inthe input 'le& it simpl% "opies it to the output 'le
interpret PHP2 $hen the pro"essor en"ounters PHP s"ript in the input 'le& it interprets it and sends an% outpu
of the s"ript to the output 'le, )his implies that the output from a PHP s"ript must be H)*L or 3H)*L& either of whi"h "ould
in"lude embedded "lient-side s"ript,
PHP s%nta4 is similar to that of /avaS"ript PHP is d%nami"all% t%ped PHP is purel% interpreted
5
-
7/26/2019 Server-side Web Development With PHP
4/66
6eneral S%nta"ti"
hara"teristi"s
PHP "ode "an be spe"i'ed in an H)*L do"ument internall% ore4ternall%0
8nternall%0 .4ternall%0 include ("myScript.inc")
the 'le "an have both PHP and H)*L
8f the 'le has PHP& the PHP must be in & even if the includeis alread% in
.ver% variable name begin with a $
-
7/26/2019 Server-side Web Development With PHP
5/66
6eneral S%nta"ti"
hara"teristi"s Comments- three dierent #inds /ava and 2
// ...
# ...
/* ... */
ompound statements are formed with bra"es
ompound statements "annot be blo"#s Unless used as the bod% of a fun"tion de'nition& a
"ompound statement "annot be a blo"#, 8t "annotde'ne lo"all% s"oped variables,2
:
-
7/26/2019 Server-side Web Development With PHP
6/66
)he reserved words of PHP
;
-
7/26/2019 Server-side Web Development With PHP
7/66
Primitives& Operations& and
.4pressions Variables
)here are no t%pe de"larations
+n unassigned unbound2 variable has thevalue& NULL )he unsetfun"tion sets a variable to NULL
)he IsSetfun"tion is used to determine whether a
variable is NULL
-
7/26/2019 Server-side Web Development With PHP
8/66
Primitives& Operations& and.4pressions 8f %ou want to be informed when an unbound variableis referen"ed& in"lude a "all to theerr&r'rep&rtin() fun"tion to "hange the errorreporting level of the PHP interpreter to 1:)he default error reporting level is 7& whi"h does not re=uire
the interpreter to report the use of an unbound variable,
PHP has man% prede'ned variables& in"luding theenvironment variables of the host operating s%stem
>ou "an get a list of the prede'ned variables b% "allingphpin&()in a s"ript
?
-
7/26/2019 Server-side Web Development With PHP
9/66
Primitives& Operations& and.4pressions)here are eight primitive t%pes0
-
7/26/2019 Server-side Web Development With PHP
10/66
Strings Single-quoted string literals
.mbedded variables are O) interpolated
i,e, are not substituted for their Calues .mbedded es"ape se=uen"es are O) re"ogniDed
-
7/26/2019 Server-side Web Development With PHP
11/66
Strings Double-quoted string literals
.mbedded variables +R. interpolated
8f there is a variable name in a double-=uotedstring but %ou donFt want it interpolated& it must beba"#slashed
.mbedded es"ape se=uen"es +R. re"ogniDed
-
7/26/2019 Server-side Web Development With PHP
12/66
@oolean @oolean - values aretrue and 2lse"ase
insensitive2
8f an integer e4pression is used in a @oolean "onte4t& itevaluates to
-
7/26/2019 Server-side Web Development With PHP
13/66
+rithmeti" Operators and.4pressions Usual operators K& -& & M& N& KK& and --2
if both operands are integers& the operation is integer and an
integer result is produ"ed, 8f either operand is a double& the operation is double and a double
result is produ"ed 8f the result of integer division is not an integer& a double is
returned
+n% integer operation that results in overow produ"es a double )he modulus operator N2 "oer"es its operands to integer& if
ne"essar% $hen a double is rounded to an integer& the rounding is alwa%s
towards Dero
15
-
7/26/2019 Server-side Web Development With PHP
14/66
+rithmeti" fun"tions
1
-
7/26/2019 Server-side Web Development With PHP
15/66
String Operations and
-
7/26/2019 Server-side Web Development With PHP
16/66
1;
String Operations and
-
7/26/2019 Server-side Web Development With PHP
17/66
S"alar )%pe onversions Implicit (coercions)
String to numeric and vice versa
)here are also fre=uent "oer"ions betweennumeri" and string t%pes.
$henever a numeri" value appears in a string"onte4t& the numeri" value is "oer"ed to a string
Li#ewise& whenever a string value appears in a numeri""onte4t& the string value is "oer"ed to a numeri" value
8f the string "ontains an e or an .& it is "onvertedto doubleG otherwise to integer
8f the string does not begin with a sign or a digit&the "onversion fails and Dero is used,
$hen a double is "onverted to an integer& thefra"tionalpart is droppedG rounding is not done,
17
-
7/26/2019 Server-side Web Development With PHP
18/66
.4pli"it "onversions Casting:three diferent ways
1, One "an "ast an e4pression to a dierent t%pe, )he"ast is a t%pe name in parentheses pre"eding thee4pression
e,g,& (int)$t&t2l
(, +nother wa% to spe"if% e4pli"it t%pe "onversion isto use one of the fun"tions int2l: d&u6le2l:orstr2l
int2l($t&t2l)
1, )he third wa% to spe"if% an e4pli"it t%pe "onversionis with the settypefun"tion& whi"h ta#es twoparameters0 a variable and a string that spe"i'es at%pe name
settype($t&t2l: "inteer") 1?
-
7/26/2019 Server-side Web Development With PHP
19/66
Cariable t%pedetermination two diferent ways
1, Usingettype
fun"tion whi"h ta#es a variable as its parameter and returns a string that
has the name of the t%pe of the "urrent value of the variable ettype($t&t2l) - it ma% return "un=n&7n"
(, use one or more of the t%pe testing fun"tions& ea"h of whi"h ta#es a
variable name as a parameter and returns a @oolean value )hese fun"tions are is'int: is'inteer& and is'l&n& whi"h
test for integer t%peG is'd&u6le: is'l&2t:and is're2l& whi"htest for double t%peG is'6&&l& whi"h tests for @oolean t%peG andis'strin& whi"h tests for string t%pe,
is'inteer($t&t2l) a predi"ate fun"tion
19
-
7/26/2019 Server-side Web Development With PHP
20/66
+ssignment Operators PHP has the same set of assignment
operators as its prede"essor language&
& in"luding the "ompound assignmentoperators su"h as 8 and/8.
(E
-
7/26/2019 Server-side Web Development With PHP
21/66
Output Output from a PHP s"ript is H)*L that is sent to the
browser H)*L is sent to the browser through standard output )here are two wa%s to produ"e output0 printand print
printta#es a string& but will "oer"e other values tostrings
print "!his is t&& much un "9
print ;9
printis e4a"tl% as in and is for formatted output
print(literal_string¶m1¶m2& Q)
(1
-
7/26/2019 Server-side Web Development With PHP
22/66
Output PHP "ode is pla"ed in the bod% of an H)*L do"ument
!rii2l php e2mple
((
-
7/26/2019 Server-side Web Development With PHP
23/66
!ate fun"tion ote that the date information is generatedwith the d2tefun"tion& whose 'rst parameteris a string that spe"i'es the parts of the date
%ou want to see, 8n this e4ample& lre=uests the da% of the
wee#& re=uests the month&A re=uests theda% of the month& and an Sne4t to the A getsthe "orre"t su4 for the da% e, g,& stor nd2
SHO$ t&d2y.phpand displa%
(5
-
7/26/2019 Server-side Web Development With PHP
24/66
ontrol Statements Control Expressions
)he usual si4 & T& &T& V& and 2 have
the usual meanings, PHP also has & whi"h produ"es )RU. onl%
if both operands are the same t%pe and havethe same value& and V& the opposite of ,
8f the t%pes of the operands of the other si4relational operators are not the same& one is"oer"ed to the t%pe of the other
(
-
7/26/2019 Server-side Web Development With PHP
25/66
@oolean operators
same as )here are si4 @oolean operators, 2nd:&r: &r: B: CC: and DD,
)he 2nd andCC operators perform thesame operation& as do &rand DD,
)he dieren"e between them is that thepre"eden"e of 2ndand &ris lower thanthat of CCand DD,
(:
-
7/26/2019 Server-side Web Development With PHP
26/66
Sele"tion statements
i statement PHPFs if statement is li#e that of i: iEelse: elsei
(;
)h
-
7/26/2019 Server-side Web Development With PHP
27/66
)he s7itchstatement as in
)he swit"h e4pression t%pe must beinteger& double& or string
(7
-
7/26/2019 Server-side Web Development With PHP
28/66
Loop Statements 7hile- Aust li#e &re2ch- dis"ussed later)he following e4ample "omputes the
fa"torial of Wn0
(?
-
7/26/2019 Server-side Web Development With PHP
29/66
d&E7hileStatement d&-7hile- Aust li#e
)his e4ample "omputes the sum of thepositive integers up to 1EE0
(9
-
7/26/2019 Server-side Web Development With PHP
30/66
&r St2tement &r- Aust li#e
)he following e4ample "omputes thefa"torial of Wn0
5E
-
7/26/2019 Server-side Web Development With PHP
31/66
)he 6re2=statement
)he6re2= statement "an be used toterminate the e4e"ution of a &r& &r
e2ch: 7hile: &r d& 7hile "onstru"t,)he c&ntinuestatement is used in loop
"onstru"ts to s#ip the remainder of the
"urrent iteration but "ontinue e4e"utionat the beginning of the ne4t,
51
-
7/26/2019 Server-side Web Development With PHP
32/66
.4ample illustrates the form of an 3H)*LMPHP
do"ument& as well as some simplemathemati"al fun"tions and theintermingling of 3H)*L and PHP in a
do"ument,)he sFrtfun"tion returns the s=uare root
of its parameterG
the p&7fun"tion raises its 'rst parameterto the power of its se"ond parameter
SHO$ p&7ers.php
5(
. l
-
7/26/2019 Server-side Web Development With PHP
33/66
.4ample H)*L "an be intermingled with PHP s"ript
%t this p&int: $2 2nd $6 2re
eFu2l
S&: 7e ch2ne $2 t& three times $2
55
+
-
7/26/2019 Server-side Web Development With PHP
34/66
+rra%s ot li#e the arra%s of an% other programming
language + PHP arra% is a generaliDation of the arra%s of other
languages a "ombination of the arra%s of a t%pi"al language an
asso"iative arra%s& or hashes& found in some otherlanguages& su"h as Rub% and P%thon
+ PHP arra% is reall% a mapping of #e%s to values&where the #e%s "an be numbers to get a traditional
arra%2 or strings to get a hash2
5
+ ti
-
7/26/2019 Server-side Web Development With PHP
35/66
+rra% "reation )here are two wa%s to "reate an arra% in PHP
1, +ssigning a value to a subs"ripted variable that previousl% was not an arra%"reates the arra% if no arra% named Wlist"urrentl% e4ists& the following statement "reates one0
$listGH 8 ;G 8f empt% bra"#ets are used in an assignment to an arra%& a numeri"
subs"ript is impli"itl% furnished)he furnished subs"ript is 1 greater than the largest used so far in the
arra% if the arra% alread% has elements with numeri" #e%s$listGH 8 0!&d2y is my 6irthd2yB19$listGH 8 9
the se"ond elementFs subs"ript will be ( demonstrates that the elements of an arra% need not be of the same
t%pe,
5:
+ ti
-
7/26/2019 Server-side Web Development With PHP
36/66
+rra% "reation(, )he se"ond wa% to "reate an arra% is with the arra% "onstru"t,
$list 8 2rr2y(;: : : J)9
)he parameters of arra% spe"if% the values to be pla"ed in anew arra% and sometimes also the #e%s,
8f the arra% is li#e a traditional arra%& onl% the values need to bespe"i'edG the PHP interpreter will furnish the numeri" #e%s,
+bove statement "reates a traditional arra% of four elements&with the #e%s E& 1& (& and 5 8f %ou would rather have dierent #e%s& %ou "an spe"if% them in
the arra% "onstru"t& as follows0
$list 8 2rr2y( 8> ;: 8> : 4 8> : 8> J)9
5;
+rra "reation
-
7/26/2019 Server-side Web Development With PHP
37/66
+rra% "reation String eyed !rray
$2esG+K2ry-H 8 J9 the value of the element whose #e% is 0K2ry1 in the$2es arra% "an be set to (9
)he list"onstru"t )he list"onstru"t "an be used to assign multiple
elements of an arra% to s"alar variables in one statement
57
-
7/26/2019 Server-side Web Development With PHP
38/66
+""essing arra% elements
Use bra"#ets
$listGH 8 ;9
$listG"d2y"H 8 "!uesd2y"9
$listGH 8 ;9
8f an element with the spe"i'ed #e% does
not e4ist& it is "reated 8f the arra% does not e4ist& the arra% is
"reated
5?
-
7/26/2019 Server-side Web Development With PHP
39/66
-
7/26/2019 Server-side Web Development With PHP
40/66
-
7/26/2019 Server-side Web Development With PHP
41/66
+rra% internal logi"al stru"ture 8nternall%& the elements of an arra% are stored in a lin#ed list of
"ells& where ea"h "ell in"ludes both the #e% and the value of the
element, )he "ells themselves are stored in memor% through a #e%
hashing fun"tion so that the% are randoml% distributed in areserved blo"# of storage,
+""esses to elements through string #e%s are implemented
through the hashing fun"tion, However& the elements all have lin#s that "onne"t them in the
order in whi"h the% were "reated& allowing them to be a""essedin that order if the #e%s are strings and in the order of their #e%sif the #e%s are numbers
1
-
7/26/2019 Server-side Web Development With PHP
42/66
+rra% internal logi"al stru"ture
(
Se=uential a""ess to arra% elements
-
7/26/2019 Server-side Web Development With PHP
43/66
Se=uential a""ess to arra% elements PHP in"ludes several dierent wa%s to a""ess arra%
elements in se=uential order
current" pointer .ver% arra% has an internal pointer that referen"es
one element of the arra% )his pointer is initialiDed to referen"e the 'rst
element of the arra% at the time the arra% is "reated, )he element being referen"ed b% the pointer "an be
obtained with the "urrent fun"tion
$c&l&rs 8 2rr2y("Plue": "red": "reen": "yell&7")9
$c&l&r 8 current($c&l&rs)9
print("$c&l&r ")9
produ"es the following output0Plue5
the t fun"tion
-
7/26/2019 Server-side Web Development With PHP
44/66
the netfun"tion )he "urrentI pointer "an be moved with thenet
fun"tion& whi"h both moves the pointer to the ne4t
arra% element and returns the value of that element, 8f the "urrentI pointer is alread% pointing at the last
element of the arra%& ne4t returns
-
7/26/2019 Server-side Web Development With PHP
45/66
the e2chfun"tion the netfun"tion does not alwa%s wor# for e4ample&
if one of the values in the arra% happens to be %LS
+lternative0 e2ch& instead of net fun"tion returns a two element arra% "onsisting of the #e% and
the value of the "urrentI element& avoids this problem, 8t returns
-
7/26/2019 Server-side Web Development With PHP
46/66
*OR. +RR+>
-
7/26/2019 Server-side Web Development With PHP
47/66
)he 2rr2y'pushand 2rr2y'p&pfun"tion )hese provide a simple wa% to implement a sta"# in an arra%, )he 2rr2y'pushfun"tion ta#es an arra% as its 'rst parameter,
+fter this 'rst parameter& there "an be an% number of additionalparameters, )he values of all subse=uent parameters are pla"ed at the end of
the arra%, )he2rr2y'push fun"tion returns the new number of elements in
the arra%, )he 2rr2y'p&p fun"tion ta#es a single parameter0 the name of an
arra%, 8t removes the last element from the arra% and returns it, )he
value ULL is re turned if the arra% is empt%,
7
)he &re2ch statement
-
7/26/2019 Server-side Web Development With PHP
48/66
)he &re2chstatement is designed to build loops that pro"ess all of the elements of
an arra%,
)his statement has two forms0&re2ch (array 2s scalar_variable) loop body
&re2ch (array 2s key => value) loop body
8n the 'rst form& one of the arra%Fs values is set to the s"alar
variable for ea"h iteration of the loop bod%, )he "urrentI pointer is impli"itl% initialiDed& as with reset&
before the 'rst iteration,
&re2ch ($c&l&rs 2s $c&l&r) 3
print "Is $c&l&r y&ur 2&rite c&l&r?"95
Is red y&ur 2&rite c&l&r?
Is 6lue y&ur 2&rite c&l&r?
Is reen y&ur 2&rite c&l&r?
Is yell&7 y&ur 2&rite c&l&r? ?
)he &re2ch statement
-
7/26/2019 Server-side Web Development With PHP
49/66
)he &re2chstatement )he se"ond form of &re2chprovides both the #e%
and the value of ea"h element of the arra%0
&re2ch (array 2s key => value) loop body i,e, &re2ch"an iterate through both #e%s and values0
&re2ch ($c&l&rs 2s $=ey 8> $c&l&r) 3 M 5
.4amples0 $2es 8 2rr2y("P&6" 8> : "K2ry" 8> 4)9
&re2ch ($2es 2s $n2me 8> $2e)
print("$n2me is $2e ye2rs &ld ")9
9
+rra% Sorting
-
7/26/2019 Server-side Web Development With PHP
50/66
+rra% Sorting
-
7/26/2019 Server-side Web Development With PHP
51/66
+rra% Sorting
-
7/26/2019 Server-side Web Development With PHP
52/66
Sorting into the reverseorders
)he rsort& arsort& and krsort fun"tionsbehave li#e the sort& asort& and ksort
fun"tions& respe"tivel%& e4"ept that the% sortinto the reverse orders of their "ounterparts)he following e4ample illustrates s&rt:2s&rt: 2nd =s&rt,
SHO$ s&rtin.php
:(
User-!e'ned
-
7/26/2019 Server-side Web Development With PHP
53/66
User !e'ned
-
7/26/2019 Server-side Web Development With PHP
54/66
Parameters 8f the "aller sends too man% a"tual parameters& the
subprogram ignores the e4tra ones 8f the "aller does not send enough parameters& the
unmat"hed formal parameters are unbound )he default parameter passing method is pass b% value
one-wa% "ommuni"ation2 )o spe"if% pass-b%-referen"e& prepend an ampersand to
the formal parameter uncti&n set'm2(C$m2: $irst: $sec&nd) 3
i ($irst >8 $sec&nd)
$m2 8 $irst9
else $m2 8 $sec&nd95 8f the fun"tion does not spe"if% its parameter to be pass
b% referen"e& %ou "an prepend an ampersand to thea"tual parameter and still get pass-b%-referen"esemanti"s :
)he S"ope of Cariables
-
7/26/2019 Server-side Web Development With PHP
55/66
)he S"ope of Cariables )he default s"ope of a variable de'ned in a fun"tion islocal, + lo"al variable is visible onl% in the fun"tion in whi"h it is used, )o a""ess a nonlocalvariable& it must be de"lared to be
glo$al& as in
l&62l $sum9
::
global de"laration .4ample
-
7/26/2019 Server-side Web Development With PHP
56/66
global de"laration .4ample
:;
)he Lifetime of Cariables
-
7/26/2019 Server-side Web Development With PHP
57/66
)he Lifetime of Cariables 8n some situations& a fun"tion must be histor% sensitiveG that is& it must
retain information about previous a"tivations, )he default lifetime of lo"al variables in a PHP fun"tion is from the time the
variable is 'rst used i, e,& when storage for it is allo"ated2 until thefun"tionFs e4e"ution terminates,
)o support histor% sensitivit%& a fun"tion must have static local %aria$les,)he lifetime of a stati" variable in a fun"tion begins when the variable is'rst used in the 'rst e4e"ution of the fun"tion, 8ts lifetime ends when thes"ript e4e"ution ends, 8n the "ase of PHP& this is when the browser leavesthe do"ument in whi"h the PHP s"ript is embedded,
8n PHP& a lo"al variable in a fun"tion "an be spe"i'ed to be stati" b%de"laring it with the reserved word stati", Su"h a de"laration "an in"lude aninitial value& whi"h is onl% assigned the 'rst time the de"laration is rea"hed
:7
stati" lo"al variables e4ample
-
7/26/2019 Server-side Web Development With PHP
58/66
stati" lo"al variables e4ample !ispla%s the number of times it has been "alled&
even if it is "alled from several dierent pla"es,
)he fa"t that its lo"al variable W"ount is stati"allows this to be done
:?
stati" lo"al variables e4ample
-
7/26/2019 Server-side Web Development With PHP
59/66
stati" lo"al variables e4ample !ispla%s the number of times it has been "alled&
even if it is "alled from several dierent pla"es,
)he fa"t that its lo"al variable W"ount is stati"allows this to be done
:9
Pattern *at"hing
-
7/26/2019 Server-side Web Development With PHP
60/66
g PHP in"ludes two dierent #inds of string pattern mat"hing
using regular e4pressions0 one that is based on POS83 regular e4pressions one that is based on Perl regular e4pressions& li#e those
of /avaS"ript, well )he POS83 regular e4pressions are "ompiled into PHP& but
the Perl-ompatible Regular .4pression PR.2 librar% must
be "ompiled before Perl regular e4pressions "an be used #hepreg_matchunction ta#es two parameters& the 'rst
of whi"h is the Perl-st%le regular e4pression as a string, )hese"ond parameter is the string to be sear"hed,
;E
Pattern *at"hing
-
7/26/2019 Server-side Web Development With PHP
61/66
Pattern *at"hing )hepreg_splitunction operates on strings but
returns an arra% and uses patterns
)he fun"tion ta#es two parameters& the 'rst of whi"h isa Perl-st%le pattern as a string,
)he se"ond parameter is the string to be split,
-
7/26/2019 Server-side Web Development With PHP
62/66
g
-
7/26/2019 Server-side Web Development With PHP
63/66
oo#ies
Recall that the HTTP protocol is stateless;however, there are several reasons why it is useful
for a server to relate a request to earlier requests Targeted advertising Shopping baskets
A cookieis a nae!value pair that is passedbetween a browser and a server in the HTTPheader
;5
-
7/26/2019 Server-side Web Development With PHP
64/66
oo#ies
"n PHP, cookies are created with setc&&=ie
setc&&=ie(cookie#nae, cookie#value, lifetie)
e$g$, setc&&=ie("&ted": "true": time() )9 ?;&EE is the number of se"onds in a da%2,
oo#ies are impli"itl% deleted when their lifetimesare over
%ookies ust be created before any other HT&' iscreated by the script %ookies are obtained in a script the sae way for values
are gotten, using the $'TVISarray
;
-
7/26/2019 Server-side Web Development With PHP
65/66
Session )ra"#ing
+ sessionis the time span during whi"h abrowser intera"ts with a parti"ular server
-
7/26/2019 Server-side Web Development With PHP
66/66
Session )ra"#ing )o "reate a session variable& use
sessi&n'reister )he onl% parameter is a string literal of the name of the session variable
without the dollar sign2 Example0 "ount number of pages visited
Put the following "ode in all do"uments
sessi&n'st2rt()9
i (BIsSet($p2e'num6er))
$p2e'num6er 8 9 print("W&u h2e n&7 isited $p2e'num6er")9
print(" p2es ")9
$p2e'num6er9
$sessi&n'reister("p2e'num6er")9