You are on page 1of 95

PHP TUTORIAL

PHP is a server scripting language, and is a powerful tool for making dynamic and interactive
e! pages"
PHP is a widely#used, free, and efficient alternative to competitors suc$ as %icrosoft&s A'P"
()ample
*+,O-T.P( $tml/
*$tml/
*!ody/
*0p$p
ec$o 1%y first PHP script+12
0/
*3!ody/
*3$tml/
PHP code is e)ecuted on t$e server"
$at .ou '$ould Already 4now
5efore you continue you s$ould $ave a !asic understanding of t$e following6
HT%L
7ava'cript
$at is PHP0
PHP stands for PHP6 Hyperte)t Preprocessor
PHP is a widely#used, open source scripting language
PHP scripts are e)ecuted on t$e server
PHP is free to download and use
$at is a PHP 8ile0
PHP files can contain te)t, HT%L, 7ava'cript code, and PHP code
PHP code are e)ecuted on t$e server, and t$e result is returned to t$e !rowser as plain
HT%L
1
PHP files $ave a default file e)tension of 1"p$p1
$at -an PHP ,o0
PHP can generate dynamic page content
PHP can create, open, read, write, and close files on t$e server
PHP can collect form data
PHP can send and receive cookies
PHP can add, delete, modify data in your data!ase
PHP can restrict users to access some pages on your we!site
PHP can encrypt data
it$ PHP you are not limited to output HT%L" .ou can output images, P,8 files, and even
8las$ movies" .ou can also output any te)t, suc$ as 9HT%L and 9%L"
$y PHP0
PHP runs on different platforms :indows, Linu), Uni), %ac O' 9, etc";
PHP is compati!le wit$ almost all servers used today :Apac$e, II', etc";
PHP $as support for a wide range of data!ases
PHP is free" ,ownload it from t$e official PHP resource6 www"p$p"net
PHP is easy to learn and runs efficiently on t$e server side
$at ,o I <eed0
To start using PHP, you can6
8ind a we! $ost wit$ PHP and %y'=L support
Install a we! server on your own P-, and t$en install PHP and %y'=L
Use a e! Host it$ PHP 'upport
If your server $as activated support for PHP you do not need to do anyt$ing"
2
7ust create some "p$p files, place t$em in your we! directory, and t$e server will
automatically parse t$em for you"
.ou do not need to compile anyt$ing or install any e)tra tools"
5ecause PHP is free, most we! $osts offer PHP support"
3
'et Up PHP on .our Own P-
However, if your server does not support PHP, you must6
install a we! server
install PHP
install a data!ase, suc$ as %y'=L
T$e official PHP we!site :PHP"net; $as installation instructions for PHP6
$ttp633p$p"net3manual3en3install"p$p
T$e PHP script is e)ecuted on t$e server, and t$e plain HT%L result is sent !ack to t$e
!rowser"
5asic PHP 'ynta)
A PHP script always starts wit$ *0p$p and ends wit$ 0/" A PHP script can !e placed
anyw$ere in t$e document"
On servers wit$ s$ort$and#support, you can start a PHP script wit$ *0 and end wit$ 0/"
8or ma)imum compati!ility, we recommend t$at you use t$e standard form :*0p$p; rat$er
t$an t$e s$ort$and form"
*0p$p
33 PHP code goes $ere
0/
T$e default file e)tension for PHP files is 1"p$p1"
A PHP file normally contains HT%L tags, and some PHP scripting code"
5elow, we $ave an e)ample of a simple PHP script t$at sends t$e te)t 1Hello orld+1 !ack to
t$e !rowser6
()ample
*+,O-T.P( $tml/
*$tml/
*!ody/
*0p$p
ec$o 1Hello orld+12
0/
4
*3!ody/
*3$tml/
(ac$ code line in PHP must end wit$ a semicolon" T$e semicolon is a separator and is used to
distinguis$ one set of instructions from anot$er"
T$ere are two !asic statements to output te)t wit$ PHP6 ec$o and print"
In t$e e)ample a!ove we $ave used t$e ec$o statement to output t$e te)t 1Hello orld1"
-omments in PHP
In PHP, we use 33 to make a one#line comment, or 3> and >3 to make a comment !lock6
()ample
*+,O-T.P( $tml/
*$tml/
*!ody/
*0p$p
33T$is is a comment
3>
T$is is
a comment
!lock
>3
0/
*3!ody/
*3$tml/
PHP ?aria!les
?aria!les are 1containers1 for storing information"
PHP varia!les are used to $old values or e)pressions"
A varia!le can $ave a s$ort name, like ), or a more descriptive name, like car<ame"
Rules for PHP varia!le names6
?aria!les in PHP starts wit$ a @ sign, followed !y t$e name of t$e varia!le
T$e varia!le name must !egin wit$ a letter or t$e underscore c$aracter
5
A varia!le name can only contain alp$a#numeric c$aracters and underscores :A#A, B#
C, and D ;
A varia!le name s$ould not contain spaces
?aria!le names are case sensitive :y and . are two different varia!les;
-reating :,eclaring; PHP ?aria!les
PHP $as no command for declaring a varia!le"
A varia!le is created t$e moment you first assign a value to it6
@my-arE1?olvo12
After t$e e)ecution of t$e statement a!ove, t$e varia!le my-ar will $old t$e value ?olvo"
Tip6 If you want to create a varia!le wit$out assigning it a value, t$en you assign it t$e value
of null"
Let&s create a varia!le containing a string, and a varia!le containing a num!er6
*0p$p
@t)tE1Hello orld+12
@)EFG2
0/
<ote6 $en you assign a te)t value to a varia!le, put Huotes around t$e value"
PHP is a Loosely Typed Language
In PHP, a varia!le does not need to !e declared !efore adding a value to it"
In t$e e)ample a!ove, notice t$at we did not $ave to tell PHP w$ic$ data type t$e varia!le is"
PHP automatically converts t$e varia!le to t$e correct data type, depending on its value"
In a strongly typed programming language, you $ave to declare :define; t$e type and name of
t$e varia!le !efore using it"
PHP ?aria!le 'cope
T$e scope of a varia!le is t$e portion of t$e script in w$ic$ t$e varia!le can !e referenced"
PHP $as four different varia!le scopes6
6
local
glo!al
static
parameter
Local 'cope
A varia!le declared wit$in a PHP function is local and can only !e accessed wit$in t$at
function" :t$e varia!le $as local scope;6
*0p$p
@a E I2 33 glo!al scope
function myTest:;
J
ec$o @a2 33 local scope
K
myTest:;2
0/
T$e script a!ove will not produce any output !ecause t$e ec$o statement refers to t$e local
scope varia!le @a, w$ic$ $as not !een assigned a value wit$in t$is scope"
.ou can $ave local varia!les wit$ t$e same name in different functions, !ecause local
varia!les are only recogniAed !y t$e function in w$ic$ t$ey are declared"
Local varia!les are deleted as soon as t$e function is completed"
Llo!al 'cope
Llo!al scope refers to any varia!le t$at is defined outside of any function"
Llo!al varia!les can !e accessed from any part of t$e script t$at is not inside a function"
To access a glo!al varia!le from wit$in a function, use t$e glo!al keyword6
*0p$p
@a E I2
@! E FB2
function myTest:;
J
glo!al @a, @!2
7
@! E @a M @!2
K
myTest:;2
ec$o @!2
0/
T$e script a!ove will output FI"
PHP also stores all glo!al varia!les in an array called @LLO5AL'Ninde)O" Its inde) is t$e
name of t$e varia!le" T$is array is also accessi!le from wit$in functions and can !e used to
update glo!al varia!les directly"
T$e e)ample a!ove can !e rewritten as t$is6
*0p$p
@a E I2
@! E FB2
function myTest:;
J
@LLO5AL'N&!&O E @LLO5AL'N&a&O M @LLO5AL'N&!&O2
K
myTest:;2
ec$o @!2
0/
'tatic 'cope
$en a function is completed, all of its varia!les are normally deleted" However, sometimes
you want a local varia!le to not !e deleted"
To do t$is, use t$e static keyword w$en you first declare t$e varia!le6
static @remem!er%e2
T$en, eac$ time t$e function is called, t$at varia!le will still $ave t$e information it contained
from t$e last time t$e function was called"
<ote6 T$e varia!le is still local to t$e function"
Parameters
A parameter is a local varia!le w$ose value is passed to t$e function !y t$e calling code"
Parameters are declared in a parameter list as part of t$e function declaration6
8
function myTest:@paraF,@paraP,""";
J
33 function code
K
Parameters are also called arguments"
9
'tring ?aria!les in PHP
'tring varia!les are used for values t$at contain c$aracters"
In t$is c$apter we are going to look at t$e most common functions and operators used to
manipulate strings in PHP"
After we create a string we can manipulate it" A string can !e used directly in a function or it
can !e stored in a varia!le"
5elow, t$e PHP script assigns t$e te)t 1Hello orld1 to a string varia!le called @t)t6
*0p$p
@t)tE1Hello orld12
ec$o @t)t2
0/
T$e output of t$e code a!ove will !e6
Hello orld
<ow, lets try to use some different functions and operators to manipulate t$e string"
T$e -oncatenation Operator
T$ere is only one string operator in PHP"
T$e concatenation operator :"; is used to put two string values toget$er"
To concatenate two string varia!les toget$er, use t$e concatenation operator6
*0p$p
@t)tFE1Hello orld+12
@t)tPE1$at a nice day+12
ec$o @t)tF " 1 1 " @t)tP2
0/
T$e output of t$e code a!ove will !e6
Hello orld+ $at a nice day+
If we look at t$e code a!ove you see t$at we used t$e concatenation operator two times" T$is
is !ecause we $ad to insert a t$ird string :a space c$aracter;, to separate t$e two strings"
10
T$e strlen:; function
T$e strlen:; function is used to return t$e lengt$ of a string"
Let&s find t$e lengt$ of a string6
*0p$p
ec$o strlen:1Hello world+1;2
0/
T$e output of t$e code a!ove will !e6
FP
T$e lengt$ of a string is often used in loops or ot$er functions, w$en it is important to know
w$en t$e string ends" :i"e" in a loop, we would want to stop t$e loop after t$e last c$aracter in
t$e string;"
T$e strpos:; function
T$e strpos:; function is used to searc$ for a c$aracter3te)t wit$in a string"
If a matc$ is found, t$is function will return t$e c$aracter position of t$e first matc$" If no
matc$ is found, it will return 8AL'("
Let&s see if we can find t$e string 1world1 in our string6
*0p$p
ec$o strpos:1Hello world+1,1world1;2
0/
T$e output of t$e code a!ove will !e6
G
T$e position of t$e string 1world1 in t$e e)ample a!ove is G" T$e reason t$at it is G :and not
Q;, is t$at t$e first c$aracter position in t$e string is B, and not F"
11
Arit$metic Operators
T$e ta!le !elow lists t$e arit$metic operators in PHP6
Operator <ame
) M y Addition
) # y 'u!traction
) > y %ultiplication
) 3 y ,ivision
) R y %odulus
# ) <egation
a " ! -oncatenation
Assignment Operators
T$e !asic assignment operator in PHP is 1E1" It means t$at t$e left operand gets set to t$e
value of t$e e)pression on t$e rig$t" T$at is, t$e value of 1@) E I1 is I"
Assignment 'ame as"""
) E y ) E y
) ME y ) E ) M y
) #E y ) E ) # y
) >E y ) E ) > y
) 3E y ) E ) 3 y
) RE y ) E ) R y
a "E ! a E a " !
12
Incrementing3,ecrementing Operators
Operator <ame
MM ) Pre#increment
) MM Post#increment
## ) Pre#decrement
) ## Post#decrement
-omparison Operators
-omparison operators allows you to compare two values6
Operator <ame
) EE y (Hual
) EEE y Identical
) +E y <ot eHual
) */ y <ot eHual
) +EE y <ot identical
) / y Lreater t$an
) * y Less t$an
) /E y Lreater t$an or eHual to
) *E y Less t$an or eHual to
Logical Operators
Operator <ame
) and y And
) or y Or
) )or y 9or
) SS y And
13
) TT y Or
+ ) <ot
Array Operators
Operator <ame
) M y Union
) EE y (Huality
) EEE y Identity
) +E y IneHuality
) */ y IneHuality
) +EE y <on#identity
14
-onditional 'tatements
-onditional statements are used to perform different actions !ased on different conditions"
?ery often w$en you write code, you want to perform different actions for different decisions"
.ou can use conditional statements in your code to do t$is"
In PHP we $ave t$e following conditional statements6
if statement # use t$is statement to e)ecute some code only if a specified condition is true
if"""else statement # use t$is statement to e)ecute some code if a condition is true and
anot$er code if t$e condition is false
if"""elseif""""else statement # use t$is statement to select one of several !locks of code to !e
e)ecuted
switc$ statement # use t$is statement to select one of many !locks of code to !e e)ecuted
T$e if 'tatement
Use t$e if statement to e)ecute some code only if a specified condition is true"
'ynta)
if :condition; code to !e e)ecuted if condition is true2
T$e following e)ample will output 1Have a nice weekend+1 if t$e current day is 8riday6
*$tml/
*!ody/
*0p$p
@dEdate:1,1;2
if :@dEE18ri1; ec$o 1Have a nice weekend+12
0/
*3!ody/
*3$tml/
<otice t$at t$ere is no ""else"" in t$is synta)" T$e code is e)ecuted only if t$e specified
condition is true"
15
T$e if"""else 'tatement
Use t$e if""""else statement to e)ecute some code if a condition is true and anot$er code if a
condition is false"
'ynta)
if :condition;
J
code to !e e)ecuted if condition is true2
K
else
J
code to !e e)ecuted if condition is false2
K
()ample
T$e following e)ample will output 1Have a nice weekend+1 if t$e current day is 8riday,
ot$erwise it will output 1Have a nice day+16
*$tml/
*!ody/
*0p$p
@dEdate:1,1;2
if :@dEE18ri1;
J
ec$o 1Have a nice weekend+12
K
else
J
ec$o 1Have a nice day+12
K
0/
*3!ody/
*3$tml/
T$e if"""elseif""""else 'tatement
Use t$e if""""elseif"""else statement to select one of several !locks of code to !e e)ecuted"
'ynta)
if :condition;
J
code to !e e)ecuted if condition is true2
K
elseif :condition;
J
code to !e e)ecuted if condition is true2
16
K
else
J
code to !e e)ecuted if condition is false2
K
()ample
T$e following e)ample will output 1Have a nice weekend+1 if t$e current day is 8riday, and
1Have a nice 'unday+1 if t$e current day is 'unday" Ot$erwise it will output 1Have a nice
day+16
*$tml/
*!ody/
*0p$p
@dEdate:1,1;2
if :@dEE18ri1;
J
ec$o 1Have a nice weekend+12
K
elseif :@dEE1'un1;
J
ec$o 1Have a nice 'unday+12
K
else
J
ec$o 1Have a nice day+12
K
0/
*3!ody/
*3$tml/
17
T$e PHP 'witc$ 'tatement
Use t$e switc$ statement to select one of many !locks of code to !e e)ecuted"
'ynta)
switc$ :n;
J
case la!elF6
code to !e e)ecuted if nEla!elF2
!reak2
case la!elP6
code to !e e)ecuted if nEla!elP2
!reak2
default6
code to !e e)ecuted if n is different from !ot$ la!elF and la!elP2
K
T$is is $ow it works6 8irst we $ave a single e)pression n :most often a varia!le;, t$at is
evaluated once" T$e value of t$e e)pression is t$en compared wit$ t$e values for eac$ case in
t$e structure" If t$ere is a matc$, t$e !lock of code associated wit$ t$at case is e)ecuted" Use
!reak to prevent t$e code from running into t$e ne)t case automatically" T$e default
statement is used if no matc$ is found"
()ample
*$tml/
*!ody/
*0p$p
@)EF2
switc$ :@);
J
case F6
ec$o 1<um!er F12
!reak2
case P6
ec$o 1<um!er P12
!reak2
case U6
ec$o 1<um!er U12
!reak2
default6
ec$o 1<o num!er !etween F and U12
K
0/
*3!ody/
*3$tml/
18
$at is an Array0
A varia!le is a storage area $olding a num!er or te)t" T$e pro!lem is, a varia!le will $old
only one value"
An array is a special varia!le, w$ic$ can store multiple values in one single varia!le"
If you $ave a list of items :a list of car names, for e)ample;, storing t$e cars in single
varia!les could look like t$is6
@carsFE1'aa!12
@carsPE1?olvo12
@carsUE15%12
However, w$at if you want to loop t$roug$ t$e cars and find a specific one0 And w$at if you
$ad not U cars, !ut UBB0
T$e !est solution $ere is to use an array+
An array can $old all your varia!le values under a single name" And you can access t$e
values !y referring to t$e array name"
(ac$ element in t$e array $as its own inde) so t$at it can !e easily accessed"
In PHP, t$ere are t$ree kind of arrays6
<umeric array # An array wit$ a numeric inde)
Associative array # An array w$ere eac$ I, key is associated wit$ a value
%ultidimensional array # An array containing one or more arrays
<umeric Arrays
A numeric array stores eac$ array element wit$ a numeric inde)"
T$ere are two met$ods to create a numeric array"
F" In t$e following e)ample t$e inde) are automatically assigned :t$e inde) starts at B;6
@carsEarray:1'aa!1,1?olvo1,15%1,1Toyota1;2
P" In t$e following e)ample we assign t$e inde) manually6
@carsNBOE1'aa!12
@carsNFOE1?olvo12
@carsNPOE15%12
@carsNUOE1Toyota12
19
()ample
In t$e following e)ample you access t$e varia!le values !y referring to t$e array name and
inde)6
*0p$p
@carsNBOE1'aa!12
@carsNFOE1?olvo12
@carsNPOE15%12
@carsNUOE1Toyota12
ec$o @carsNBO " 1 and 1 " @carsNFO " 1 are 'wedis$ cars"12
0/
T$e code a!ove will output6
'aa! and ?olvo are 'wedis$ cars"
Associative Arrays
An associative array, eac$ I, key is associated wit$ a value"
$en storing data a!out specific named values, a numerical array is not always t$e !est way
to do it"
it$ associative arrays we can use t$e values as keys and assign values to t$em"
()ample F
In t$is e)ample we use an array to assign ages to t$e different persons6
@ages E array:1Peter1E/UP, 1=uagmire1E/UB, 17oe1E/UV;2
()ample P
T$is e)ample is t$e same as e)ample F, !ut s$ows a different way of creating t$e array6
@agesN&Peter&O E 1UP12
@agesN&=uagmire&O E 1UB12
@agesN&7oe&O E 1UV12
T$e I, keys can !e used in a script6
*0p$p
@agesN&Peter&O E 1UP12
@agesN&=uagmire&O E 1UB12
@agesN&7oe&O E 1UV12
ec$o 1Peter is 1 " @agesN&Peter&O " 1 years old"12
0/
T$e code a!ove will output6
20
Peter is UP years old"
%ultidimensional Arrays
In a multidimensional array, eac$ element in t$e main array can also !e an array" And eac$
element in t$e su!#array can !e an array, and so on"
()ample
In t$is e)ample we create a multidimensional array, wit$ automatically assigned I, keys6
@families E array
:
1Lriffin1E/array
:
1Peter1,
1Lois1,
1%egan1
;,
1=uagmire1E/array
:
1Llenn1
;,
15rown1E/array
:
1-leveland1,
1Loretta1,
17unior1
;
;2
T$e array a!ove would look like t$is if written to t$e output6
Array
:
NLriffinO E/ Array
:
NBO E/ Peter
NFO E/ Lois
NPO E/ %egan
;
N=uagmireO E/ Array
:
NBO E/ Llenn
;
N5rownO E/ Array
:
NBO E/ -leveland
NFO E/ Loretta
NPO E/ 7unior
;
;
21
()ample P
Lets try displaying a single value from t$e array a!ove6
ec$o 1Is 1 " @familiesN&Lriffin&ONPO "
1 a part of t$e Lriffin family012
T$e code a!ove will output6
Is %egan a part of t$e Lriffin family0
PHP Loops
Often w$en you write code, you want t$e same !lock of code to run over and over again in a
row" Instead of adding several almost eHual lines in a script we can use loops to perform a
task like t$is"
In PHP, we $ave t$e following looping statements6
w$ile # loops t$roug$ a !lock of code w$ile a specified condition is true
do"""w$ile # loops t$roug$ a !lock of code once, and t$en repeats t$e loop as long as a
specified condition is true
for # loops t$roug$ a !lock of code a specified num!er of times
foreac$ # loops t$roug$ a !lock of code for eac$ element in an array
T$e w$ile Loop
T$e w$ile loop e)ecutes a !lock of code w$ile a condition is true"
'ynta)
w$ile :condition;
J
code to !e e)ecuted2
K
()ample
T$e e)ample !elow first sets a varia!le i to F :@iEF2;"
T$en, t$e w$ile loop will continue to run as long as i is less t$an, or eHual to I" i will increase
!y F eac$ time t$e loop runs6
*$tml/
*!ody/
*0p$p
@iEF2
22
w$ile:@i*EI;
J
ec$o 1T$e num!er is 1 " @i " 1*!r/12
@iMM2
K
0/
*3!ody/
*3$tml/
Output6
T$e num!er is F
T$e num!er is P
T$e num!er is U
T$e num!er is V
T$e num!er is I
T$e do"""w$ile 'tatement
T$e do"""w$ile statement will always e)ecute t$e !lock of code once, it will t$en c$eck t$e
condition, and repeat t$e loop w$ile t$e condition is true"
'ynta)
do
J
code to !e e)ecuted2
K
w$ile :condition;2
()ample
T$e e)ample !elow first sets a varia!le i to F :@iEF2;"
T$en, it starts t$e do"""w$ile loop" T$e loop will increment t$e varia!le i wit$ F, and t$en
write some output" T$en t$e condition is c$ecked :is i less t$an, or eHual to I;, and t$e loop
will continue to run as long as i is less t$an, or eHual to I6
*$tml/
*!ody/
*0p$p
@iEF2
do
J
@iMM2
ec$o 1T$e num!er is 1 " @i " 1*!r/12
K
w$ile :@i*EI;2
0/
23
*3!ody/
*3$tml/
Output6
T$e num!er is P
T$e num!er is U
T$e num!er is V
T$e num!er is I
T$e num!er is G
T$e for Loop
T$e for loop is used w$en you know in advance $ow many times t$e script s$ould run"
'ynta)
for :init2 condition2 increment;
J
code to !e e)ecuted2
K
Parameters6
init6 %ostly used to set a counter :!ut can !e any code to !e e)ecuted once at t$e !eginning of
t$e loop;
condition6 (valuated for eac$ loop iteration" If it evaluates to TRU(, t$e loop continues" If it
evaluates to 8AL'(, t$e loop ends"
increment6 %ostly used to increment a counter :!ut can !e any code to !e e)ecuted at t$e end
of t$e iteration;
<ote6 T$e init and increment parameters a!ove can !e empty or $ave multiple e)pressions
:separated !y commas;"
()ample
T$e e)ample !elow defines a loop t$at starts wit$ iEF" T$e loop will continue to run as long
as t$e varia!le i is less t$an, or eHual to I" T$e varia!le i will increase !y F eac$ time t$e loop
runs6
*$tml/
*!ody/
*0p$p
for :@iEF2 @i*EI2 @iMM;
J
ec$o 1T$e num!er is 1 " @i " 1*!r/12
K
0/
24
*3!ody/
*3$tml/
Output6
T$e num!er is F
T$e num!er is P
T$e num!er is U
T$e num!er is V
T$e num!er is I
T$e foreac$ Loop
T$e foreac$ loop is used to loop t$roug$ arrays"
'ynta)
foreac$ :@array as @value;
J
code to !e e)ecuted2
K
8or every loop iteration, t$e value of t$e current array element is assigned to @value :and t$e
array pointer is moved !y one; # so on t$e ne)t loop iteration, you&ll !e looking at t$e ne)t
array value"
()ample
T$e following e)ample demonstrates a loop t$at will print t$e values of t$e given array6
*$tml/
*!ody/
*0p$p
@)Earray:1one1,1two1,1t$ree1;2
foreac$ :@) as @value;
J
ec$o @value " 1*!r/12
K
0/
*3!ody/
*3$tml/
Output6
one
two
t$ree
25
PHP 8unctions
In t$is c$apter we will s$ow you $ow to create your own functions"
To keep t$e script from !eing e)ecuted w$en t$e page loads, you can put it into a function"
A function will !e e)ecuted !y a call to t$e function"
.ou may call a function from anyw$ere wit$in a page"
-reate a PHP 8unction
A function will !e e)ecuted !y a call to t$e function"
'ynta)
function function<ame:;
J
code to !e e)ecuted2
K
PHP function guidelines6
Live t$e function a name t$at reflects w$at t$e function does
T$e function name can start wit$ a letter or underscore :not a num!er;
()ample
A simple function t$at writes my name w$en it is called6
*$tml/
*!ody/
*0p$p
function write<ame:;
J
ec$o 14ai 7im Refsnes12
K
ec$o 1%y name is 12
write<ame:;2
0/
*3!ody/
*3$tml/
Output6
%y name is 4ai 7im Refsnes
26
PHP 8unctions # Adding parameters
To add more functionality to a function, we can add parameters" A parameter is Wust like a
varia!le"
Parameters are specified after t$e function name, inside t$e parent$eses"
()ample F
T$e following e)ample will write different first names, !ut eHual last name6
*$tml/
*!ody/
*0p$p
function write<ame:@fname;
J
ec$o @fname " 1 Refsnes"*!r/12
K
ec$o 1%y name is 12
write<ame:14ai 7im1;2
ec$o 1%y sister&s name is 12
write<ame:1Hege1;2
ec$o 1%y !rot$er&s name is 12
write<ame:1'tale1;2
0/
*3!ody/
*3$tml/
Output6
%y name is 4ai 7im Refsnes"
%y sister&s name is Hege Refsnes"
%y !rot$er&s name is 'tale Refsnes"
()ample P
T$e following function $as two parameters6
*$tml/
*!ody/
*0p$p
function write<ame:@fname,@punctuation;
J
ec$o @fname " 1 Refsnes1 " @punctuation " 1*!r/12
K
ec$o 1%y name is 12
write<ame:14ai 7im1,1"1;2
27
ec$o 1%y sister&s name is 12
write<ame:1Hege1,1+1;2
ec$o 1%y !rot$er&s name is 12
write<ame:1'tXle1,101;2
0/
*3!ody/
*3$tml/
Output6
%y name is 4ai 7im Refsnes"
%y sister&s name is Hege Refsnes+
%y !rot$er&s name is 'tXle Refsnes0

PHP 8unctions # Return values
To let a function return a value, use t$e return statement"
()ample
*$tml/
*!ody/
*0p$p
function add:@),@y;
J
@totalE@)M@y2
return @total2
K
ec$o 1F M FG E 1 " add:F,FG;2
0/
*3!ody/
*3$tml/
Output6
F M FG E FQ
PHP 8orm Handling
T$e most important t$ing to notice w$en dealing wit$ HT%L forms and PHP is t$at any form
element in an HT%L page will automatically !e availa!le to your PHP scripts"
()ample
T$e e)ample !elow contains an HT%L form wit$ two input fields and a su!mit !utton6
28
*$tml/
*!ody/
*form actionE1welcome"p$p1 met$odE1post1/
<ame6 *input typeE1te)t1 nameE1fname1/
Age6 *input typeE1te)t1 nameE1age1/
*input typeE1su!mit1/
*3form/
*3!ody/
*3$tml/
$en a user fills out t$e form a!ove and clicks on t$e su!mit !utton, t$e form data is sent to
a PHP file, called 1welcome"p$p16
1welcome"p$p1 looks like t$is6
*$tml/
*!ody/
elcome *0p$p ec$o @DPO'TN1fname1O2 0/+*!r/
.ou are *0p$p ec$o @DPO'TN1age1O2 0/ years old"
*3!ody/
*3$tml/
Output could !e somet$ing like t$is6
elcome 7o$n+
.ou are PY years old"
T$e PHP @DL(T and @DPO'T varia!les will !e e)plained in t$e ne)t c$apters"
8orm ?alidation
User input s$ould !e validated on t$e !rowser w$enever possi!le :!y client scripts;" 5rowser
validation is faster and reduces t$e server load"
.ou s$ould consider server validation if t$e user input will !e inserted into a data!ase" A
good way to validate a form on t$e server is to post t$e form to itself, instead of Wumping to a
different page" T$e user will t$en get t$e error messages on t$e same page as t$e form" T$is
makes it easier to discover t$e error"
T$e @DL(T ?aria!le
T$e predefined @DL(T varia!le is used to collect values in a form wit$ met$odE1get1
Information sent from a form wit$ t$e L(T met$od is visi!le to everyone :it will !e
displayed in t$e !rowser&s address !ar; and $as limits on t$e amount of information to send"
29
()ample
*form actionE1welcome"p$p1 met$odE1get1/
<ame6 *input typeE1te)t1 nameE1fname1/
Age6 *input typeE1te)t1 nameE1age1/
*input typeE1su!mit1/
*3form/
$en t$e user clicks t$e 1'u!mit1 !utton, t$e URL sent to t$e server could look somet$ing
like t$is6
$ttp633www"restarttec$nologies"com3welcome"p$p0fnameEPeterSageEUQ
T$e 1welcome"p$p1 file can now use t$e @DL(T varia!le to collect form data :t$e names of
t$e form fields will automatically !e t$e keys in t$e @DL(T array;6
elcome *0p$p ec$o @DL(TN1fname1O2 0/"*!r/
.ou are *0p$p ec$o @DL(TN1age1O2 0/ years old+
$en to use met$odE1get10
$en using met$odE1get1 in HT%L forms, all varia!le names and values are displayed in
t$e URL"
<ote6 T$is met$od s$ould not !e used w$en sending passwords or ot$er sensitive
information+
However, !ecause t$e varia!les are displayed in t$e URL, it is possi!le to !ookmark t$e
page" T$is can !e useful in some cases"
T$e @DPO'T ?aria!le
T$e predefined @DPO'T varia!le is used to collect values from a form sent wit$
met$odE1post1"
Information sent from a form wit$ t$e PO'T met$od is invisi!le to ot$ers and $as no limits
on t$e amount of information to send"
<ote6 However, t$ere is an Y %5 ma) siAe for t$e PO'T met$od, !y default :can !e c$anged
!y setting t$e postDma)DsiAe in t$e p$p"ini file;"
()ample
*form actionE1welcome"p$p1 met$odE1post1/
<ame6 *input typeE1te)t1 nameE1fname1/
Age6 *input typeE1te)t1 nameE1age1/
*input typeE1su!mit1/
*3form/
$en t$e user clicks t$e 1'u!mit1 !utton, t$e URL will look like t$is6
$ttp633www"restarttec$nologies"com3welcome"p$p
30
T$e 1welcome"p$p1 file can now use t$e @DPO'T varia!le to collect form data :t$e names of
t$e form fields will automatically !e t$e keys in t$e @DPO'T array;6
elcome *0p$p ec$o @DPO'TN1fname1O2 0/+*!r/
.ou are *0p$p ec$o @DPO'TN1age1O2 0/ years old"
$en to use met$odE1post10
Information sent from a form wit$ t$e PO'T met$od is invisi!le to ot$ers and $as no limits
on t$e amount of information to send"
However, !ecause t$e varia!les are not displayed in t$e URL, it is not possi!le to !ookmark
t$e page"
T$e PHP @DR(=U('T ?aria!le
T$e predefined @DR(=U('T varia!le contains t$e contents of !ot$ @DL(T, @DPO'T, and
@D-OO4I("
T$e @DR(=U('T varia!le can !e used to collect form data sent wit$ !ot$ t$e L(T and
PO'T met$ods"
()ample
elcome *0p$p ec$o @DR(=U('TN1fname1O2 0/+*!r/
.ou are *0p$p ec$o @DR(=U('TN1age1O2 0/ years old"
T$e PHP ,ate:; 8unction
T$e PHP date:; function formats a timestamp to a more reada!le date and time"
A timestamp is a seHuence of c$aracters, denoting t$e date and3or time at w$ic$ a certain
event occurred"
'ynta)
date:format,timestamp;
Parameter
format
timestamp
31
PHP ,ate:; # 8ormat t$e ,ate
T$e reHuired format parameter in t$e date:; function specifies $ow to format t$e date3time"
Here are some c$aracters t$at can !e used6
d # Represents t$e day of t$e mont$ :BF to UF;
m # Represents a mont$ :BF to FP;
. # Represents a year :in four digits;
A list of all t$e c$aracters t$at can !e used in t$e format parameter, can !e found in our PHP
,ate reference"
Ot$er c$aracters, like131, 1"1, or 1#1 can also !e inserted !etween t$e letters to add additional
formatting6
*0p$p
ec$o date:1.3m3d1; " 1*!r/12
ec$o date:1."m"d1; " 1*!r/12
ec$o date:1.#m#d1;2
0/
T$e output of t$e code a!ove could !e somet$ing like t$is6
PBBC3BI3FF
PBBC"BI"FF
PBBC#BI#FF
PHP ,ate:; # Adding a Timestamp
T$e optional timestamp parameter in t$e date:; function specifies a timestamp" If you do not
specify a timestamp, t$e current date and time will !e used"
T$e mktime:; function returns t$e Uni) timestamp for a date"
T$e Uni) timestamp contains t$e num!er of seconds !etween t$e Uni) (poc$ :7anuary F
FCQB BB6BB6BB L%T; and t$e time specified"
'ynta) for mktime:;
mktime:$our,minute,second,mont$,day,year,isDdst;
To go one day in t$e future we simply add one to t$e day argument of mktime:;6
*0p$p
@tomorrow E mktime:B,B,B,date:1m1;,date:1d1;MF,date:1.1;;2
ec$o 1Tomorrow is 1"date:1.3m3d1, @tomorrow;2
0/
32
T$e output of t$e code a!ove could !e somet$ing like t$is6
Tomorrow is PBBC3BI3FP
PHP include and reHuire 'tatements
In PHP, you can insert t$e content of one PHP file into anot$er PHP file !efore t$e server
e)ecutes it"
T$e include and reHuire statements are used to insert useful codes written in ot$er files, in t$e
flow of e)ecution"
Include and reHuire are identical, e)cept upon failure6
reHuire will produce a fatal error :(D-O%PIL(D(RROR; and stop t$e script
include will only produce a warning :(DAR<I<L; and t$e script will continue
'o, if you want t$e e)ecution to go on and s$ow users t$e output, even if t$e include file is
missing, use include" Ot$erwise, in case of 8rameork, -%' or a comple) PHP application
coding, always use reHuire to include a key file to t$e flow of e)ecution" T$is will $elp avoid
compromising your application&s security and integrity, Wust in#case one key file is
accidentally missing"
Including files saves a lot of work" T$is means t$at you can create a standard $eader, footer,
or menu file for all your we! pages" T$en, w$en t$e $eader needs to !e updated, you can only
update t$e $eader include file"
'ynta)
include &filename&2
or
reHuire &filename&2
PHP include and reHuire 'tatement
5asic ()ample
Assume t$at you $ave a standard $eader file, called 1$eader"p$p1" To include t$e $eader file
in a page, use include3reHuire6
*$tml/
*!ody/
*0p$p include &$eader"p$p&2 0/
*$F/elcome to my $ome page+*3$F/
*p/'ome te)t"*3p/
33
*3!ody/
*3$tml/
()ample P
Assume we $ave a standard menu file t$at s$ould !e used on all pages"
1menu"p$p16
ec$o &*a $refE13default"p$p1/Home*3a/
*a $refE13tutorials"p$p1/Tutorials*3a/
*a $refE13references"p$p1/References*3a/
*a $refE13e)amples"p$p1/()amples*3a/
*a $refE13a!out"p$p1/A!out Us*3a/
*a $refE13contact"p$p1/-ontact Us*3a/&2
All pages in t$e e! site s$ould include t$is menu file" Here is $ow it can !e done6
*$tml/
*!ody/
*div classE1leftmenu1/
*0p$p include &menu"p$p&2 0/
*3div/
*$F/elcome to my $ome page"*3$F/
*p/'ome te)t"*3p/
*3!ody/
*3$tml/
()ample U
Assume we $ave an include file wit$ some varia!les defined :1vars"p$p1;6
*0p$p
@colorE&red&2
@carE&5%&2
0/
T$en t$e varia!les can !e used in t$e calling file6
*$tml/
*!ody/
*$F/elcome to my $ome page"*3$F/
*0p$p include &vars"p$p&2
ec$o 1I $ave a @color @car12 33 I $ave a red 5%
0/
*3!ody/
*3$tml/
34
35
PHP 8ile Handling
T$e fopen:; function is used to open files in PHP"
Opening a 8ile
T$e fopen:; function is used to open files in PHP"
T$e first parameter of t$is function contains t$e name of t$e file to !e opened and t$e second
parameter specifies in w$ic$ mode t$e file s$ould !e opened6
*$tml/
*!ody/
*0p$p
@fileEfopen:1welcome"t)t1,1r1;2
0/
*3!ody/
*3$tml/
T$e file may !e opened in one of t$e following modes6
%odes
r
rM
w
wM
a
aM
)
)M
<ote6 If t$e fopen:; function is una!le to open t$e specified file, it returns B :false;"
36
()ample
T$e following e)ample generates a message if t$e fopen:; function is una!le to open t$e
specified file6
*$tml/
*!ody/
*0p$p
@fileEfopen:1welcome"t)t1,1r1; or e)it:1Una!le to open file+1;2
0/
*3!ody/
*3$tml/
-losing a 8ile
T$e fclose:; function is used to close an open file6
*0p$p
@file E fopen:1test"t)t1,1r1;2
33some code to !e e)ecuted
fclose:@file;2
0/
-$eck (nd#of#file
T$e feof:; function c$ecks if t$e 1end#of#file1 :(O8; $as !een reac$ed"
T$e feof:; function is useful for looping t$roug$ data of unknown lengt$"
<ote6 .ou cannot read from files opened in w, a, and ) mode+
if :feof:@file;; ec$o 1(nd of file12
Reading a 8ile Line !y Line
T$e fgets:; function is used to read a single line from a file"
<ote6 After a call to t$is function t$e file pointer $as moved to t$e ne)t line"
37
()ample
T$e e)ample !elow reads a file line !y line, until t$e end of file is reac$ed6
*0p$p
@file E fopen:1welcome"t)t1, 1r1; or e)it:1Una!le to open file+1;2
33Output a line of t$e file until t$e end is reac$ed
w$ile:+feof:@file;;
J
ec$o fgets:@file;" 1*!r/12
K
fclose:@file;2
0/
Reading a 8ile -$aracter !y -$aracter
T$e fgetc:; function is used to read a single c$aracter from a file"
<ote6 After a call to t$is function t$e file pointer moves to t$e ne)t c$aracter"
()ample
T$e e)ample !elow reads a file c$aracter !y c$aracter, until t$e end of file is reac$ed6
*0p$p
@fileEfopen:1welcome"t)t1,1r1; or e)it:1Una!le to open file+1;2
w$ile :+feof:@file;;
J
ec$o fgetc:@file;2
K
fclose:@file;2
0/
-reate an Upload#8ile 8orm
To allow users to upload files from a form can !e very useful"
Look at t$e following HT%L form for uploading files6
*$tml/
*!ody/
*form actionE1uploadDfile"p$p1 met$odE1post1
enctypeE1multipart3form#data1/
*la!el forE1file1/8ilename6*3la!el/
*input typeE1file1 nameE1file1 idE1file1/*!r/
*input typeE1su!mit1 nameE1su!mit1 valueE1'u!mit1/
*3form/
38
*3!ody/
*3$tml/
<otice t$e following a!out t$e HT%L form a!ove6
T$e enctype attri!ute of t$e *form/ tag specifies w$ic$ content#type to use w$en
su!mitting t$e form" 1multipart3form#data1 is used w$en a form reHuires !inary data,
like t$e contents of a file, to !e uploaded
T$e typeE1file1 attri!ute of t$e *input/ tag specifies t$at t$e input s$ould !e
processed as a file" 8or e)ample, w$en viewed in a !rowser, t$ere will !e a !rowse#
!utton ne)t to t$e input field
<ote6 Allowing users to upload files is a !ig security risk" Only permit trusted users to
perform file uploads"
-reate T$e Upload 'cript
T$e 1uploadDfile"p$p1 file contains t$e code for uploading a file6
*0p$p
if :@D8IL('N1file1ON1error1O / B;
J
ec$o 1(rror6 1 " @D8IL('N1file1ON1error1O " 1*!r/12
K
else
J
ec$o 1Upload6 1 " @D8IL('N1file1ON1name1O " 1*!r/12
ec$o 1Type6 1 " @D8IL('N1file1ON1type1O " 1*!r/12
ec$o 1'iAe6 1 " :@D8IL('N1file1ON1siAe1O 3 FBPV; " 1 k5*!r/12
ec$o 1'tored in6 1 " @D8IL('N1file1ON1tmpDname1O2
K
0/
5y using t$e glo!al PHP @D8IL(' array you can upload files from a client computer to t$e
remote server"
T$e first parameter is t$e form&s input name and t$e second inde) can !e eit$er 1name1,
1type1, 1siAe1, 1tmpDname1 or 1error1" Like t$is6
@D8IL('N1file1ON1name1O # t$e name of t$e uploaded file
@D8IL('N1file1ON1type1O # t$e type of t$e uploaded file
@D8IL('N1file1ON1siAe1O # t$e siAe in kilo!ytes of t$e uploaded file
@D8IL('N1file1ON1tmpDname1O # t$e name of t$e temporary copy of t$e file stored on
t$e server
39
@D8IL('N1file1ON1error1O # t$e error code resulting from t$e file upload
T$is is a very simple way of uploading files" 8or security reasons, you s$ould add restrictions
on w$at t$e user is allowed to upload"
Restrictions on Upload
In t$is script we add some restrictions to t$e file upload" T$e user may upload "gif, "Wpeg,
and "png files2 and t$e file siAe must !e under PB k56
*0p$p
@allowed()ts E array:1Wpg1, 1Wpeg1, 1gif1, 1png1;2
@e)tension E end:e)plode:1"1, @D8IL('N1file1ON1name1O;;2
if :::@D8IL('N1file1ON1type1O EE 1image3gif1;
TT :@D8IL('N1file1ON1type1O EE 1image3Wpeg1;
TT :@D8IL('N1file1ON1type1O EE 1image3png1;
TT :@D8IL('N1file1ON1type1O EE 1image3pWpeg1;;
SS :@D8IL('N1file1ON1siAe1O * PBBBB;
SS inDarray:@e)tension, @allowed()ts;;
J
if :@D8IL('N1file1ON1error1O / B;
J
ec$o 1(rror6 1 " @D8IL('N1file1ON1error1O " 1*!r/12
K
else
J
ec$o 1Upload6 1 " @D8IL('N1file1ON1name1O " 1*!r/12
ec$o 1Type6 1 " @D8IL('N1file1ON1type1O " 1*!r/12
ec$o 1'iAe6 1 " :@D8IL('N1file1ON1siAe1O 3 FBPV; " 1 k5*!r/12
ec$o 1'tored in6 1 " @D8IL('N1file1ON1tmpDname1O2
K
K
else
J
ec$o 1Invalid file12
K
0/
<ote6 8or I( to recogniAe Wpg files t$e type must !e pWpeg, for 8ire8o) it must !e Wpeg"
'aving t$e Uploaded 8ile
T$e e)amples a!ove create a temporary copy of t$e uploaded files in t$e PHP temp folder on
t$e server"
T$e temporary copied files disappears w$en t$e script ends" To store t$e uploaded file we
need to copy it to a different location6
40
*0p$p
@allowed()ts E array:1Wpg1, 1Wpeg1, 1gif1, 1png1;2
@e)tension E end:e)plode:1"1, @D8IL('N1file1ON1name1O;;2
if :::@D8IL('N1file1ON1type1O EE 1image3gif1;
TT :@D8IL('N1file1ON1type1O EE 1image3Wpeg1;
TT :@D8IL('N1file1ON1type1O EE 1image3png1;
TT :@D8IL('N1file1ON1type1O EE 1image3pWpeg1;;
SS :@D8IL('N1file1ON1siAe1O * PBBBB;
SS inDarray:@e)tension, @allowed()ts;;
J
if :@D8IL('N1file1ON1error1O / B;
J
ec$o 1Return -ode6 1 " @D8IL('N1file1ON1error1O " 1*!r/12
K
else
J
ec$o 1Upload6 1 " @D8IL('N1file1ON1name1O " 1*!r/12
ec$o 1Type6 1 " @D8IL('N1file1ON1type1O " 1*!r/12
ec$o 1'iAe6 1 " :@D8IL('N1file1ON1siAe1O 3 FBPV; " 1 k5*!r/12
ec$o 1Temp file6 1 " @D8IL('N1file1ON1tmpDname1O " 1*!r/12
if :fileDe)ists:1upload31 " @D8IL('N1file1ON1name1O;;
J
ec$o @D8IL('N1file1ON1name1O " 1 already e)ists" 12
K
else
J
moveDuploadedDfile:@D8IL('N1file1ON1tmpDname1O,
1upload31 " @D8IL('N1file1ON1name1O;2
ec$o 1'tored in6 1 " 1upload31 " @D8IL('N1file1ON1name1O2
K
K
K
else
J
ec$o 1Invalid file12
K
0/
T$e script a!ove c$ecks if t$e file already e)ists, if it does not, it copies t$e file to a folder
called 1upload1"
$at is a -ookie0
A cookie is often used to identify a user" A cookie is a small file t$at t$e server em!eds on t$e
user&s computer" (ac$ time t$e same computer reHuests a page wit$ a !rowser, it will send t$e
cookie too" it$ PHP, you can !ot$ create and retrieve cookie values"
How to -reate a -ookie0
41
T$e setcookie:; function is used to set a cookie"
<ote6 T$e setcookie:; function must appear 5(8OR( t$e *$tml/ tag"
'ynta)
setcookie:name, value, e)pire, pat$, domain;2
()ample F
In t$e e)ample !elow, we will create a cookie named 1user1 and assign t$e value 1Ale)
Porter1 to it" e also specify t$at t$e cookie s$ould e)pire after one $our6
*0p$p
setcookie:1user1, 1Ale) Porter1, time:;MUGBB;2
0/
*$tml/
"""""
<ote6 T$e value of t$e cookie is automatically URLencoded w$en sending t$e cookie, and
automatically decoded w$en received :to prevent URLencoding, use setrawcookie:; instead;"
()ample P
.ou can also set t$e e)piration time of t$e cookie in anot$er way" It may !e easier t$an using
seconds"
*0p$p
@e)pireEtime:;MGB>GB>PV>UB2
setcookie:1user1, 1Ale) Porter1, @e)pire;2
0/
*$tml/
"""""
In t$e e)ample a!ove t$e e)piration time is set to a mont$ :GB sec > GB min > PV $ours > UB
days;"
How to Retrieve a -ookie ?alue0
T$e PHP @D-OO4I( varia!le is used to retrieve a cookie value"
In t$e e)ample !elow, we retrieve t$e value of t$e cookie named 1user1 and display it on a
page6
*0p$p
33 Print a cookie
ec$o @D-OO4I(N1user1O2
33 A way to view all cookies
42
printDr:@D-OO4I(;2
0/
In t$e following e)ample we use t$e isset:; function to find out if a cookie $as !een set6
*$tml/
*!ody/
*0p$p
if :isset:@D-OO4I(N1user1O;;
ec$o 1elcome 1 " @D-OO4I(N1user1O " 1+*!r/12
else
ec$o 1elcome guest+*!r/12
0/
*3!ody/
*3$tml/
How to ,elete a -ookie0
$en deleting a cookie you s$ould assure t$at t$e e)piration date is in t$e past"
,elete e)ample6
*0p$p
33 set t$e e)piration date to one $our ago
setcookie:1user1, 11, time:;#UGBB;2
0/
$at if a 5rowser ,oes <OT 'upport -ookies0
If your application deals wit$ !rowsers t$at do not support cookies, you will $ave to use ot$er
met$ods to pass information from one page to anot$er in your application" One met$od is to
pass t$e data t$roug$ forms :forms and user input are descri!ed earlier in t$is tutorial;"
T$e form !elow passes t$e user input to 1welcome"p$p1 w$en t$e user clicks on t$e 1'u!mit1
!utton6
*$tml/
*!ody/
*form actionE1welcome"p$p1 met$odE1post1/
<ame6 *input typeE1te)t1 nameE1name1/
Age6 *input typeE1te)t1 nameE1age1/
*input typeE1su!mit1/
43
*3form/
*3!ody/
*3$tml/
Retrieve t$e values in t$e 1welcome"p$p1 file like t$is6
*$tml/
*!ody/
elcome *0p$p ec$o @DPO'TN1name1O2 0/"*!r/
.ou are *0p$p ec$o @DPO'TN1age1O2 0/ years old"
*3!ody/
*3$tml/
PHP 'ession ?aria!les
$en you are working wit$ an application, you open it, do some c$anges and t$en you close
it" T$is is muc$ like a 'ession" T$e computer knows w$o you are" It knows w$en you start
t$e application and w$en you end" 5ut on t$e internet t$ere is one pro!lem6 t$e we! server
does not know w$o you are and w$at you do !ecause t$e HTTP address doesn&t maintain
state"
A PHP session solves t$is pro!lem !y allowing you to store user information on t$e server for
later use :i"e" username, s$opping items, etc;" However, session information is temporary and
will !e deleted after t$e user $as left t$e we!site" If you need a permanent storage you may
want to store t$e data in a data!ase"
'essions work !y creating a uniHue id :UI,; for eac$ visitor and store varia!les !ased on t$is
UI," T$e UI, is eit$er stored in a cookie or is propagated in t$e URL"
'tarting a PHP 'ession
5efore you can store user information in your PHP session, you must first start up t$e
session"
<ote6 T$e sessionDstart:; function must appear 5(8OR( t$e *$tml/ tag6
*0p$p sessionDstart:;2 0/
*$tml/
*!ody/
*3!ody/
*3$tml/
T$e code a!ove will register t$e user&s session wit$ t$e server, allow you to start saving user
information, and assign a UI, for t$at user&s session"
44
45
'toring a 'ession ?aria!le
T$e correct way to store and retrieve session varia!les is to use t$e PHP @D'(''IO<
varia!le6
*0p$p
sessionDstart:;2
33 store session data
@D'(''IO<N&views&OEF2
0/
*$tml/
*!ody/
*0p$p
33retrieve session data
ec$o 1PageviewsE1" @D'(''IO<N&views&O2
0/
*3!ody/
*3$tml/
Output6
PageviewsEF
In t$e e)ample !elow, we create a simple page#views counter" T$e isset:; function c$ecks if
t$e 1views1 varia!le $as already !een set" If 1views1 $as !een set, we can increment our
counter" If 1views1 doesn&t e)ist, we create a 1views1 varia!le, and set it to F6
*0p$p
sessionDstart:;2
if:isset:@D'(''IO<N&views&O;;
@D'(''IO<N&views&OE@D'(''IO<N&views&OMF2
else
@D'(''IO<N&views&OEF2
ec$o 1?iewsE1" @D'(''IO<N&views&O2
0/
,estroying a 'ession
If you wis$ to delete some session data, you can use t$e unset:; or t$e sessionDdestroy:;
function"
T$e unset:; function is used to free t$e specified session varia!le6
46
*0p$p
sessionDstart:;2
if:isset:@D'(''IO<N&views&O;;
unset:@D'(''IO<N&views&O;2
0/
.ou can also completely destroy t$e session !y calling t$e sessionDdestroy:; function6
*0p$p
sessionDdestroy:;2
0/
<ote6 sessionDdestroy:; will reset your session and you will lose all your stored session data"
T$e PHP mail:; 8unction
T$e PHP mail:; function is used to send emails from inside a script"
'ynta)
mail:to,su!Wect,message,$eaders,parameters;
Parameter
to
su!Wect
message
$eaders
parameters
<ote6 8or t$e mail functions to !e availa!le, PHP reHuires an installed and working email
system" T$e program to !e used is defined !y t$e configuration settings in t$e p$p"ini file"
Read more in our PHP %ail reference"
PHP 'imple (#%ail
T$e simplest way to send an email wit$ PHP is to send a te)t email"
In t$e e)ample !elow we first declare t$e varia!les :@to, @su!Wect, @message, @from,
@$eaders;, t$en we use t$e varia!les in t$e mail:; function to send an e#mail6
*0p$p
@to E 1someoneZe)ample"com12
@su!Wect E 1Test mail12
@message E 1Hello+ T$is is a simple email message"12
@from E 1someonelseZe)ample"com12
@$eaders E 18rom61 " @from2
mail:@to,@su!Wect,@message,@$eaders;2
ec$o 1%ail 'ent"12
0/
47
PHP %ail 8orm
it$ PHP, you can create a feed!ack#form on your we!site" T$e e)ample !elow sends a te)t
message to a specified e#mail address6
*$tml/
*!ody/
*0p$p
if :isset:@DR(=U('TN&email&O;;
33if 1email1 is filled out, send email
J
33send email
@email E @DR(=U('TN&email&O 2
@su!Wect E @DR(=U('TN&su!Wect&O 2
@message E @DR(=U('TN&message&O 2
mail:1someoneZe)ample"com1, @su!Wect,
@message, 18rom61 " @email;2
ec$o 1T$ank you for using our mail form12
K
else
33if 1email1 is not filled out, display t$e form
J
ec$o 1*form met$odE&post& actionE&mailform"p$p&/
(mail6 *input nameE&email& typeE&te)t&/*!r/
'u!Wect6 *input nameE&su!Wect& typeE&te)t&/*!r/
%essage6*!r/
*te)tarea nameE&message& rowsE&FI& colsE&VB&/
*3te)tarea/*!r/
*input typeE&su!mit&/
*3form/12
K
0/
*3!ody/
*3$tml/
T$is is $ow t$e e)ample a!ove works6
8irst, c$eck if t$e email input field is filled out
If it is not set :like w$en t$e page is first visited;2 output t$e HT%L form
If it is set :after t$e form is filled out;2 send t$e email from t$e form
$en su!mit is pressed after t$e form is filled out, t$e page reloads, sees t$at t$e
email input is set, and sends t$e email
48
<ote6 T$is is t$e simplest way to send e#mail, !ut it is not secure" In t$e ne)t c$apter of t$is
tutorial you can read more a!out vulnera!ilities in e#mail scripts, and $ow to validate user
input to make it more secure"
PHP 'ecure (mails
8irst, look at t$e PHP code from t$e previous c$apter6
*$tml/
*!ody/
*0p$p
if :isset:@DR(=U('TN&email&O;;
33if 1email1 is filled out, send email
J
33send email
@email E @DR(=U('TN&email&O 2
@su!Wect E @DR(=U('TN&su!Wect&O 2
@message E @DR(=U('TN&message&O 2
mail:1someoneZe)ample"com1, 1'u!Wect6 @su!Wect1,
@message, 18rom6 @email1 ;2
ec$o 1T$ank you for using our mail form12
K
else
33if 1email1 is not filled out, display t$e form
J
ec$o 1*form met$odE&post& actionE&mailform"p$p&/
(mail6 *input nameE&email& typeE&te)t&/*!r/
'u!Wect6 *input nameE&su!Wect& typeE&te)t&/*!r/
%essage6*!r/
*te)tarea nameE&message& rowsE&FI& colsE&VB&/
*3te)tarea/*!r/
*input typeE&su!mit&/
*3form/12
K
0/
*3!ody/
*3$tml/
T$e pro!lem wit$ t$e code a!ove is t$at unaut$oriAed users can insert data into t$e mail
$eaders via t$e input form"
$at $appens if t$e user adds t$e following te)t to t$e email input field in t$e form0
someoneZe)ample"comRBA-c6personPZe)ample"com
RBA5cc6personUZe)ample"com,personUZe)ample"com,
anot$erpersonVZe)ample"com,personIZe)ample"com
RBA5To6personGZe)ample"com
49
T$e mail:; function puts t$e te)t a!ove into t$e mail $eaders as usual, and now t$e $eader $as
an e)tra -c6, 5cc6, and To6 field" $en t$e user clicks t$e su!mit !utton, t$e e#mail will !e
sent to all of t$e addresses a!ove+
PHP 'topping (#mail InWections
T$e !est way to stop e#mail inWections is to validate t$e input"
T$e code !elow is t$e same as in t$e previous c$apter, !ut now we $ave added an input
validator t$at c$ecks t$e email field in t$e form6
*$tml/
*!ody/
*0p$p
function spamc$eck:@field;
J
33filterDvar:; sanitiAes t$e e#mail
33address using 8ILT(RD'A<ITI[(D(%AIL
@fieldEfilterDvar:@field, 8ILT(RD'A<ITI[(D(%AIL;2
33filterDvar:; validates t$e e#mail
33address using 8ILT(RD?ALI,AT(D(%AIL
if:filterDvar:@field, 8ILT(RD?ALI,AT(D(%AIL;;
J
return TRU(2
K
else
J
return 8AL'(2
K
K
if :isset:@DR(=U('TN&email&O;;
J33if 1email1 is filled out, proceed
33c$eck if t$e email address is invalid
@mailc$eck E spamc$eck:@DR(=U('TN&email&O;2
if :@mailc$eckEE8AL'(;
J
ec$o 1Invalid input12
K
else
J33send email
@email E @DR(=U('TN&email&O 2
@su!Wect E @DR(=U('TN&su!Wect&O 2
@message E @DR(=U('TN&message&O 2
mail:1someoneZe)ample"com1, 1'u!Wect6 @su!Wect1,
@message, 18rom6 @email1 ;2
ec$o 1T$ank you for using our mail form12
K
50
K
else
J33if 1email1 is not filled out, display t$e form
ec$o 1*form met$odE&post& actionE&mailform"p$p&/
(mail6 *input nameE&email& typeE&te)t&/*!r/
'u!Wect6 *input nameE&su!Wect& typeE&te)t&/*!r/
%essage6*!r/
*te)tarea nameE&message& rowsE&FI& colsE&VB&/
*3te)tarea/*!r/
*input typeE&su!mit&/
*3form/12
K
0/
*3!ody/
*3$tml/
In t$e code a!ove we use PHP filters to validate input6
T$e 8ILT(RD'A<ITI[(D(%AIL filter removes all illegal e#mail c$aracters from a
string
T$e 8ILT(RD?ALI,AT(D(%AIL filter validates value as an e#mail address
PHP (rror Handling
$en creating scripts and we! applications, error $andling is an important part" If your code
lacks error c$ecking code, your program may look very unprofessional and you may !e open
to security risks"
T$is tutorial contains some of t$e most common error c$ecking met$ods in PHP"
e will s$ow different error $andling met$ods6
'imple 1die:;1 statements
-ustom errors and error triggers
(rror reporting
5asic (rror Handling6 Using t$e die:; function
T$e first e)ample s$ows a simple script t$at opens a te)t file6
*0p$p
@fileEfopen:1welcome"t)t1,1r1;2
0/
If t$e file does not e)ist you mig$t get an error like t$is6
51
arning6 fopen:welcome"t)t; Nfunction"fopenO6 failed to open stream6
<o suc$ file or directory in -6\we!folder\test"p$p on line P
To avoid t$at t$e user gets an error message like t$e one a!ove, we test if t$e file e)ist !efore
we try to access it6
*0p$p
if:+fileDe)ists:1welcome"t)t1;;
J
die:18ile not found1;2
K
else
J
@fileEfopen:1welcome"t)t1,1r1;2
K
0/
<ow if t$e file does not e)ist you get an error like t$is6
8ile not found
T$e code a!ove is more efficient t$an t$e earlier code, !ecause it uses a simple error $andling
mec$anism to stop t$e script after t$e error"
However, simply stopping t$e script is not always t$e rig$t way to go" Let&s take a look at
alternative PHP functions for $andling errors"
-reating a -ustom (rror Handler
-reating a custom error $andler is Huite simple" e simply create a special function t$at can
!e called w$en an error occurs in PHP"
T$is function must !e a!le to $andle a minimum of two parameters :error level and error
message; !ut can accept up to five parameters :optionally6 file, line#num!er, and t$e error
conte)t;6
'ynta)
errorDfunction:errorDlevel,errorDmessage,
errorDfile,errorDline,errorDconte)t;
Parameter
errorDlevel
errorDmessage
errorDfile
errorDline
errorDconte)t
52
(rror Report levels
T$ese error report levels are t$e different types of error t$e user#defined error $andler can !e
used for6
?alue -onstant
P (DAR<I<L
Y (D<OTI-(
PIG (DU'(RD(RROR
IFP (DU'(RDAR<I<L
FBPV (DU'(RD<OTI-(
VBCG (DR(-O?(RA5L(D(RROR
YFCF (DALL
<ow lets create a function to $andle errors6
function custom(rror:@errno, @errstr;
J
ec$o 1*!/(rror6*3!/ N@errnoO @errstr*!r/12
ec$o 1(nding 'cript12
die:;2
K
T$e code a!ove is a simple error $andling function" $en it is triggered, it gets t$e error level
and an error message" It t$en outputs t$e error level and message and terminates t$e script"
<ow t$at we $ave created an error $andling function we need to decide w$en it s$ould !e
triggered"
'et (rror Handler
T$e default error $andler for PHP is t$e !uilt in error $andler" e are going to make t$e
function a!ove t$e default error $andler for t$e duration of t$e script"
It is possi!le to c$ange t$e error $andler to apply for only some errors, t$at way t$e script can
$andle different errors in different ways" However, in t$is e)ample we are going to use our
custom error $andler for all errors6
setDerrorD$andler:1custom(rror1;2
'ince we want our custom function to $andle all errors, t$e setDerrorD$andler:; only needed
one parameter, a second parameter could !e added to specify an error level"
()ample
Testing t$e error $andler !y trying to output varia!le t$at does not e)ist6
53
*0p$p
33error $andler function
function custom(rror:@errno, @errstr;
J
ec$o 1*!/(rror6*3!/ N@errnoO @errstr12
K
33set error $andler
setDerrorD$andler:1custom(rror1;2
33trigger error
ec$o:@test;2
0/
T$e output of t$e code a!ove s$ould !e somet$ing like t$is6
(rror6 NYO Undefined varia!le6 test
Trigger an (rror
In a script w$ere users can input data it is useful to trigger errors w$en an illegal input occurs"
In PHP, t$is is done !y t$e triggerDerror:; function"
()ample
In t$is e)ample an error occurs if t$e 1test1 varia!le is !igger t$an 1F16
*0p$p
@testEP2
if :@test/F;
J
triggerDerror:1?alue must !e F or !elow1;2
K
0/
T$e output of t$e code a!ove s$ould !e somet$ing like t$is6
<otice6 ?alue must !e F or !elow
in -6\we!folder\test"p$p on line G
An error can !e triggered anyw$ere you wis$ in a script, and !y adding a second parameter,
you can specify w$at error level is triggered"
Possi!le error types6
(DU'(RD(RROR # 8atal user#generated run#time error" (rrors t$at can not !e
recovered from" ()ecution of t$e script is $alted
54
(DU'(RDAR<I<L # <on#fatal user#generated run#time warning" ()ecution of t$e
script is not $alted
(DU'(RD<OTI-( # ,efault" User#generated run#time notice" T$e script found
somet$ing t$at mig$t !e an error, !ut could also $appen w$en running a script
normally
()ample
In t$is e)ample an (DU'(RDAR<I<L occurs if t$e 1test1 varia!le is !igger t$an 1F1" If an
(DU'(RDAR<I<L occurs we will use our custom error $andler and end t$e script6
*0p$p
33error $andler function
function custom(rror:@errno, @errstr;
J
ec$o 1*!/(rror6*3!/ N@errnoO @errstr*!r/12
ec$o 1(nding 'cript12
die:;2
K
33set error $andler
setDerrorD$andler:1custom(rror1,(DU'(RDAR<I<L;2
33trigger error
@testEP2
if :@test/F;
J
triggerDerror:1?alue must !e F or !elow1,(DU'(RDAR<I<L;2
K
0/
T$e output of t$e code a!ove s$ould !e somet$ing like t$is6
(rror6 NIFPO ?alue must !e F or !elow
(nding 'cript
<ow t$at we $ave learned to create our own errors and $ow to trigger t$em, lets take a look at
error logging"
(rror Logging
5y default, PHP sends an error log to t$e server&s logging system or a file, depending on $ow
t$e errorDlog configuration is set in t$e p$p"ini file" 5y using t$e errorDlog:; function you can
send error logs to a specified file or a remote destination"
'ending error messages to yourself !y e#mail can !e a good way of getting notified of
specific errors"
55
'end an (rror %essage !y (#%ail
In t$e e)ample !elow we will send an e#mail wit$ an error message and end t$e script, if a
specific error occurs6
*0p$p
33error $andler function
function custom(rror:@errno, @errstr;
J
ec$o 1*!/(rror6*3!/ N@errnoO @errstr*!r/12
ec$o 1e!master $as !een notified12
errorDlog:1(rror6 N@errnoO @errstr1,F,
1someoneZe)ample"com1,18rom6 we!masterZe)ample"com1;2
K
33set error $andler
setDerrorD$andler:1custom(rror1,(DU'(RDAR<I<L;2
33trigger error
@testEP2
if :@test/F;
J
triggerDerror:1?alue must !e F or !elow1,(DU'(RDAR<I<L;2
K
0/
T$e output of t$e code a!ove s$ould !e somet$ing like t$is6
(rror6 NIFPO ?alue must !e F or !elow
e!master $as !een notified
And t$e mail received from t$e code a!ove looks like t$is6
(rror6 NIFPO ?alue must !e F or !elow
T$is s$ould not !e used wit$ all errors" Regular errors s$ould !e logged on t$e server using
t$e default PHP logging system"
56
$at is an ()ception
it$ PHP I came a new o!Wect oriented way of dealing wit$ errors"
()ception $andling is used to c$ange t$e normal flow of t$e code e)ecution if a specified
error :e)ceptional; condition occurs" T$is condition is called an e)ception"
T$is is w$at normally $appens w$en an e)ception is triggered6
T$e current code state is saved
T$e code e)ecution will switc$ to a predefined :custom; e)ception $andler function
,epending on t$e situation, t$e $andler may t$en resume t$e e)ecution from t$e
saved code state, terminate t$e script e)ecution or continue t$e script from a different
location in t$e code
e will s$ow different error $andling met$ods6
5asic use of ()ceptions
-reating a custom e)ception $andler
%ultiple e)ceptions
Re#t$rowing an e)ception
'etting a top level e)ception $andler
<ote6 ()ceptions s$ould only !e used wit$ error conditions, and s$ould not !e used to Wump
to anot$er place in t$e code at a specified point"
5asic Use of ()ceptions
$en an e)ception is t$rown, t$e code following it will not !e e)ecuted, and PHP will try to
find t$e matc$ing 1catc$1 !lock"
If an e)ception is not caug$t, a fatal error will !e issued wit$ an 1Uncaug$t ()ception1
message"
Lets try to t$row an e)ception wit$out catc$ing it6
*0p$p
33create function wit$ an e)ception
function c$eck<um:@num!er;
J
if:@num!er/F;
J
57
t$row new ()ception:1?alue must !e F or !elow1;2
K
return true2
K
33trigger e)ception
c$eck<um:P;2
0/
T$e code a!ove will get an error like t$is6
8atal error6 Uncaug$t e)ception &()ception&
wit$ message &?alue must !e F or !elow& in -6\we!folder\test"p$p6G
'tack trace6 ]B -6\we!folder\test"p$p:FP;6
c$eck<um:PY; ]F JmainK t$rown in -6\we!folder\test"p$p on line G
Try, t$row and catc$
To avoid t$e error from t$e e)ample a!ove, we need to create t$e proper code to $andle an
e)ception"
Proper e)ception code s$ould include6
1. Try # A function using an e)ception s$ould !e in a 1try1 !lock" If t$e e)ception does
not trigger, t$e code will continue as normal" However if t$e e)ception triggers, an
e)ception is 1t$rown1
2. T$row # T$is is $ow you trigger an e)ception" (ac$ 1t$row1 must $ave at least one
1catc$1
3. -atc$ # A 1catc$1 !lock retrieves an e)ception and creates an o!Wect containing t$e
e)ception information
Lets try to trigger an e)ception wit$ valid code6
*0p$p
33create function wit$ an e)ception
function c$eck<um:@num!er;
J
if:@num!er/F;
J
t$row new ()ception:1?alue must !e F or !elow1;2
K
return true2
K
33trigger e)ception in a 1try1 !lock
try
J
c$eck<um:P;2
33If t$e e)ception is t$rown, t$is te)t will not !e s$own
ec$o &If you see t$is, t$e num!er is F or !elow&2
58
K
33catc$ e)ception
catc$:()ception @e;
J
ec$o &%essage6 & "@e#/get%essage:;2
K
0/
T$e code a!ove will get an error like t$is6
%essage6 ?alue must !e F or !elow
()ample e)plained6
T$e code a!ove t$rows an e)ception and catc$es it6
1. T$e c$eck<um:; function is created" It c$ecks if a num!er is greater t$an F" If it is, an
e)ception is t$rown
2. T$e c$eck<um:; function is called in a 1try1 !lock
3. T$e e)ception wit$in t$e c$eck<um:; function is t$rown
4. T$e 1catc$1 !lock retrives t$e e)ception and creates an o!Wect :@e; containing t$e
e)ception information
5. T$e error message from t$e e)ception is ec$oed !y calling @e#/get%essage:; from t$e
e)ception o!Wect
However, one way to get around t$e 1every t$row must $ave a catc$1 rule is to set a top level
e)ception $andler to $andle errors t$at slip t$roug$"
-reating a -ustom ()ception -lass
-reating a custom e)ception $andler is Huite simple" e simply create a special class wit$
functions t$at can !e called w$en an e)ception occurs in PHP" T$e class must !e an e)tension
of t$e e)ception class"
T$e custom e)ception class in$erits t$e properties from PHP&s e)ception class and you can
add custom functions to it"
Lets create an e)ception class6
*0p$p
class custom()ception e)tends ()ception
J
pu!lic function error%essage:;
J
59
33error message
@error%sg E &(rror on line &"@t$is#/getLine:;"& in &"@t$is#/get8ile:;
"&6 *!/&"@t$is#/get%essage:;"&*3!/ is not a valid (#%ail address&2
return @error%sg2
K
K
@email E 1someoneZe)ample"""com12
try
J
33c$eck if
if:filterDvar:@email, 8ILT(RD?ALI,AT(D(%AIL; EEE 8AL'(;
J
33t$row e)ception if email is not valid
t$row new custom()ception:@email;2
K
K
catc$ :custom()ception @e;
J
33display custom message
ec$o @e#/error%essage:;2
K
0/
T$e new class is a copy of t$e old e)ception class wit$ an addition of t$e error%essage:;
function" 'ince it is a copy of t$e old class, and it in$erits t$e properties and met$ods from
t$e old class, we can use t$e e)ception class met$ods like getLine:; and get8ile:; and
get%essage:;"
()ample e)plained6
T$e code a!ove t$rows an e)ception and catc$es it wit$ a custom e)ception class6
1. T$e custom()ception:; class is created as an e)tension of t$e old e)ception class"
T$is way it in$erits all met$ods and properties from t$e old e)ception class
2. T$e error%essage:; function is created" T$is function returns an error message if an e#
mail address is invalid
3. T$e @email varia!le is set to a string t$at is not a valid e#mail address
4. T$e 1try1 !lock is e)ecuted and an e)ception is t$rown since t$e e#mail address is
invalid
5. T$e 1catc$1 !lock catc$es t$e e)ception and displays t$e error message
%ultiple ()ceptions
60
It is possi!le for a script to use multiple e)ceptions to c$eck for multiple conditions"
It is possi!le to use several if""else !locks, a switc$, or nest multiple e)ceptions" T$ese
e)ceptions can use different e)ception classes and return different error messages6
*0p$p
class custom()ception e)tends ()ception
J
pu!lic function error%essage:;
J
33error message
@error%sg E &(rror on line &"@t$is#/getLine:;"& in &"@t$is#/get8ile:;
"&6 *!/&"@t$is#/get%essage:;"&*3!/ is not a valid (#%ail address&2
return @error%sg2
K
K
@email E 1someoneZe)ample"com12
try
J
33c$eck if
if:filterDvar:@email, 8ILT(RD?ALI,AT(D(%AIL; EEE 8AL'(;
J
33t$row e)ception if email is not valid
t$row new custom()ception:@email;2
K
33c$eck for 1e)ample1 in mail address
if:strpos:@email, 1e)ample1; +EE 8AL'(;
J
t$row new ()ception:1@email is an e)ample e#mail1;2
K
K
catc$ :custom()ception @e;
J
ec$o @e#/error%essage:;2
K
catc$:()ception @e;
J
ec$o @e#/get%essage:;2
K
0/
()ample e)plained6
T$e code a!ove tests two conditions and t$rows an e)ception if any of t$e conditions are not
met6
1. T$e custom()ception:; class is created as an e)tension of t$e old e)ception class"
T$is way it in$erits all met$ods and properties from t$e old e)ception class
61
2. T$e error%essage:; function is created" T$is function returns an error message if an e#
mail address is invalid
3. T$e @email varia!le is set to a string t$at is a valid e#mail address, !ut contains t$e
string 1e)ample1
4. T$e 1try1 !lock is e)ecuted and an e)ception is not t$rown on t$e first condition
5. T$e second condition triggers an e)ception since t$e e#mail contains t$e string
1e)ample1
6. T$e 1catc$1 !lock catc$es t$e e)ception and displays t$e correct error message
If t$e e)ception t$rown were of t$e class custom()ception and t$ere were no
custom()ception catc$, only t$e !ase e)ception catc$, t$e e)ception would !e $andled t$ere"
62
Re#t$rowing ()ceptions
'ometimes, w$en an e)ception is t$rown, you may wis$ to $andle it differently t$an t$e
standard way" It is possi!le to t$row an e)ception a second time wit$in a 1catc$1 !lock"
A script s$ould $ide system errors from users" 'ystem errors may !e important for t$e coder,
!ut is of no interest to t$e user" To make t$ings easier for t$e user you can re#t$row t$e
e)ception wit$ a user friendly message6
*0p$p
class custom()ception e)tends ()ception
J
pu!lic function error%essage:;
J
33error message
@error%sg E @t$is#/get%essage:;"& is not a valid (#%ail address"&2
return @error%sg2
K
K
@email E 1someoneZe)ample"com12
try
J
try
J
33c$eck for 1e)ample1 in mail address
if:strpos:@email, 1e)ample1; +EE 8AL'(;
J
33t$row e)ception if email is not valid
t$row new ()ception:@email;2
K
K
catc$:()ception @e;
J
33re#t$row e)ception
t$row new custom()ception:@email;2
K
K
catc$ :custom()ception @e;
J
33display custom message
ec$o @e#/error%essage:;2
K
0/
()ample e)plained6
63
T$e code a!ove tests if t$e email#address contains t$e string 1e)ample1 in it, if it does, t$e
e)ception is re#t$rown6
1. T$e custom()ception:; class is created as an e)tension of t$e old e)ception class"
T$is way it in$erits all met$ods and properties from t$e old e)ception class
2. T$e error%essage:; function is created" T$is function returns an error message if an e#
mail address is invalid
3. T$e @email varia!le is set to a string t$at is a valid e#mail address, !ut contains t$e
string 1e)ample1
4. T$e 1try1 !lock contains anot$er 1try1 !lock to make it possi!le to re#t$row t$e
e)ception
5. T$e e)ception is triggered since t$e e#mail contains t$e string 1e)ample1
6. T$e 1catc$1 !lock catc$es t$e e)ception and re#t$rows a 1custom()ception1
7. T$e 1custom()ception1 is caug$t and displays an error message
If t$e e)ception is not caug$t in its current 1try1 !lock, it will searc$ for a catc$ !lock on
1$ig$er levels1"
'et a Top Level ()ception Handler
T$e setDe)ceptionD$andler:; function sets a user#defined function to $andle all uncaug$t
e)ceptions"
*0p$p
function my()ception:@e)ception;
J
ec$o 1*!/()ception6*3!/ 1 , @e)ception#/get%essage:;2
K
setDe)ceptionD$andler:&my()ception&;2
t$row new ()ception:&Uncaug$t ()ception occurred&;2
0/
T$e output of t$e code a!ove s$ould !e somet$ing like t$is6
()ception6 Uncaug$t ()ception occurred
In t$e code a!ove t$ere was no 1catc$1 !lock" Instead, t$e top level e)ception $andler
triggered" T$is function s$ould !e used to catc$ uncaug$t e)ceptions"
64
Rules for e)ceptions
-ode may !e surrounded in a try !lock, to $elp catc$ potential e)ceptions
(ac$ try !lock or 1t$row1 must $ave at least one corresponding catc$ !lock
%ultiple catc$ !locks can !e used to catc$ different classes of e)ceptions
()ceptions can !e t$rown :or re#t$rown; in a catc$ !lock wit$in a try !lock
A simple rule6 If you t$row somet$ing, you $ave to catc$ it"
$at is %y'=L0
%y'=L is a data!ase server
%y'=L is ideal for !ot$ small and large applications
%y'=L supports standard '=L
%y'=L compiles on a num!er of platforms
%y'=L is free to download and use
T$e data in %y'=L is stored in data!ase o!Wects called ta!les"
A ta!le is a collection of related data entries and it consists of columns and rows"
,ata!ases are useful w$en storing information categorically" A company may $ave a data!ase
wit$ t$e following ta!les6 1(mployees1, 1Products1, 1-ustomers1 and 1Orders1"
PHP M %y'=L
PHP com!ined wit$ %y'=L are cross#platform :you can develop in indows and
serve on a Uni) platform;
,ata!ase Ta!les
A data!ase most often contains one or more ta!les" (ac$ ta!le is identified !y a name :e"g"
1-ustomers1 or 1Orders1;" Ta!les contain records :rows; wit$ data"
5elow is an e)ample of a ta!le called 1Persons16
Last<ame
Hansen
'vendson
65
Pettersen
T$e ta!le a!ove contains t$ree records :one for eac$ person; and four columns :Last<ame,
8irst<ame, Address, and -ity;"
=ueries
A Huery is a Huestion or a reHuest"
it$ %y'=L, we can Huery a data!ase for specific information and $ave a recordset
returned"
Look at t$e following Huery6
'(L(-T Last<ame 8RO% Persons
T$e Huery a!ove selects all t$e data in t$e 1Last<ame1 column from t$e 1Persons1 ta!le, and
will return a recordset like t$is6
Last<ame
Hansen
'vendson
Pettersen
,ownload %y'=L ,ata!ase
If you don&t $ave a PHP server wit$ a %y'=L ,ata!ase, you can download %y'=L for free
$ere6 $ttp633www"mysHl"com3downloads3
-reate a -onnection to a %y'=L ,ata!ase
5efore you can access data in a data!ase, you must create a connection to t$e data!ase"
In PHP, t$is is done wit$ t$e mysHlDconnect:; function"
'ynta)
mysHlDconnect:servername,username,password;2
Parameter
servername
username
password
66
()ample
In t$e following e)ample we store t$e connection in a varia!le :@con; for later use in t$e
script" T$e 1die1 part will !e e)ecuted if t$e connection fails6
*0p$p
@con E mysHlDconnect:1local$ost1,1peter1,1a!cFPU1;2
if :+@con;
J
die:&-ould not connect6 & " mysHlDerror:;;2
K
33 some code
0/
-losing a -onnection
T$e connection will !e closed automatically w$en t$e script ends" To close t$e connection
!efore, use t$e mysHlDclose:; function6
*0p$p
@con E mysHlDconnect:1local$ost1,1peter1,1a!cFPU1;2
if :+@con;
J
die:&-ould not connect6 & " mysHlDerror:;;2
K
33 some code
mysHlDclose:@con;2
0/
$at is a PHP 8ilter0
A PHP filter is used to validate and filter data coming from insecure sources"
To test, validate and filter user input or custom data is an important part of any we!
application"
T$e PHP filter e)tension is designed to make data filtering easier and Huicker"
$y use a 8ilter0
67
Almost all we! applications depend on e)ternal input" Usually t$is comes from a user or
anot$er application :like a we! service;" 5y using filters you can !e sure your application gets
t$e correct input type"
.ou s$ould always filter all e)ternal data+
Input filtering is one of t$e most important application security issues"
$at is e)ternal data0
Input data from a form
-ookies
e! services data
'erver varia!les
,ata!ase Huery results
8unctions and 8ilters
To filter a varia!le, use one of t$e following filter functions6
filterDvar:; # 8ilters a single varia!le wit$ a specified filter
filterDvarDarray:; # 8ilter several varia!les wit$ t$e same or different filters
filterDinput # Let one input varia!le and filter it
filterDinputDarray # Let several input varia!les and filter t$em wit$ t$e same or
different filters
In t$e e)ample !elow, we validate an integer using t$e filterDvar:; function6
*0p$p
@int E FPU2
if:+filterDvar:@int, 8ILT(RD?ALI,AT(DI<T;;
J
ec$o:1Integer is not valid1;2
K
else
J
ec$o:1Integer is valid1;2
K
0/
T$e code a!ove uses t$e 18ILT(RD?ALI,AT(DI<T1 filter to filter t$e varia!le" 'ince t$e
integer is valid, t$e output of t$e code a!ove will !e6 1Integer is valid1"
68
If we try wit$ a varia!le t$at is not an integer :like 1FPUa!c1;, t$e output will !e6 1Integer is
not valid1"
?alidating and 'anitiAing
T$ere are two kinds of filters6
?alidating filters6
Are used to validate user input
'trict format rules :like URL or (#%ail validating;
Returns t$e e)pected type on success or 8AL'( on failure
'anitiAing filters6
Are used to allow or disallow specified c$aracters in a string
<o data format rules
Always return t$e string
Options and 8lags
Options and flags are used to add additional filtering options to t$e specified filters"
,ifferent filters $ave different options and flags"
In t$e e)ample !elow, we validate an integer using t$e filterDvar:; and t$e 1minDrange1 and
1ma)Drange1 options6
*0p$p
@varEUBB2
@intDoptions E array:
1options1E/array
:
1minDrange1E/B,
1ma)Drange1E/PIG
;
;2
if:+filterDvar:@var, 8ILT(RD?ALI,AT(DI<T, @intDoptions;;
J
ec$o:1Integer is not valid1;2
K
69
else
J
ec$o:1Integer is valid1;2
K
0/
Like t$e code a!ove, options must !e put in an associative array wit$ t$e name 1options1" If a
flag is used it does not need to !e in an array"
'ince t$e integer is 1UBB1 it is not in t$e specified range, and t$e output of t$e code a!ove
will !e6 1Integer is not valid1"
?alidate Input
Let&s try validating input from a form"
T$e first t$ing we need to do is to confirm t$at t$e input data we are looking for e)ists"
T$en we filter t$e input data using t$e filterDinput:; function"
In t$e e)ample !elow, t$e input varia!le 1email1 is sent to t$e PHP page6
*0p$p
if:+filterD$asDvar:I<PUTDL(T, 1email1;;
J
ec$o:1Input type does not e)ist1;2
K
else
J
if :+filterDinput:I<PUTDL(T, 1email1, 8ILT(RD?ALI,AT(D(%AIL;;
J
ec$o 1(#%ail is not valid12
K
else
J
ec$o 1(#%ail is valid12
K
K
0/
()ample ()plained
T$e e)ample a!ove $as an input :email; sent to it using t$e 1L(T1 met$od6
1. -$eck if an 1email1 input varia!le of t$e 1L(T1 type e)ist
2. If t$e input varia!le e)ists, c$eck if it is a valid e#mail address
70
'anitiAe Input
Let&s try cleaning up an URL sent from a form"
8irst we confirm t$at t$e input data we are looking for e)ists"
T$en we sanitiAe t$e input data using t$e filterDinput:; function"
In t$e e)ample !elow, t$e input varia!le 1url1 is sent to t$e PHP page6
*0p$p
if:+filterD$asDvar:I<PUTDPO'T, 1url1;;
J
ec$o:1Input type does not e)ist1;2
K
else
J
@url E filterDinput:I<PUTDPO'T,
1url1, 8ILT(RD'A<ITI[(DURL;2
K
0/
()ample ()plained
T$e e)ample a!ove $as an input :url; sent to it using t$e 1PO'T1 met$od6
1. -$eck if t$e 1url1 input of t$e 1PO'T1 type e)ists
2. If t$e input varia!le e)ists, sanitiAe :take away invalid c$aracters; and store it in t$e
@url varia!le
If t$e input varia!le is a string like t$is 1$ttp633www"Restarttec$nologies"com31, t$e @url
varia!le after t$e sanitiAing will look like t$is6
$ttp633www"Restarttec$nologies"com3
8ilter %ultiple Inputs
A form almost always consist of more t$an one input field" To avoid calling t$e filterDvar or
filterDinput functions over and over, we can use t$e filterDvarDarray or t$e filterDinputDarray
functions"
In t$is e)ample we use t$e filterDinputDarray:; function to filter t$ree L(T varia!les" T$e
received L(T varia!les is a name, an age and an e#mail address6
*0p$p
@filters E array
71
:
1name1 E/ array
:
1filter1E/8ILT(RD'A<ITI[(D'TRI<L
;,
1age1 E/ array
:
1filter1E/8ILT(RD?ALI,AT(DI<T,
1options1E/array
:
1minDrange1E/F,
1ma)Drange1E/FPB
;
;,
1email1E/ 8ILT(RD?ALI,AT(D(%AIL
;2
@result E filterDinputDarray:I<PUTDL(T, @filters;2
if :+@resultN1age1O;
J
ec$o:1Age must !e a num!er !etween F and FPB"*!r/1;2
K
elseif:+@resultN1email1O;
J
ec$o:1(#%ail is not valid"*!r/1;2
K
else
J
ec$o:1User input is valid1;2
K
0/
()ample ()plained
T$e e)ample a!ove $as t$ree inputs :name, age and email; sent to it using t$e 1L(T1 met$od6
1. 'et an array containing t$e name of input varia!les and t$e filters used on t$e
specified input varia!les
2. -all t$e filterDinputDarray:; function wit$ t$e L(T input varia!les and t$e array we
Wust set
3. -$eck t$e 1age1 and 1email1 varia!les in t$e @result varia!le for invalid inputs" :If any
of t$e input varia!les are invalid, t$at input varia!le will !e 8AL'( after t$e
filterDinputDarray:; function;
T$e second parameter of t$e filterDinputDarray:; function can !e an array or a single filter I,"
If t$e parameter is a single filter I, all values in t$e input array are filtered !y t$e specified
filter"
72
If t$e parameter is an array it must follow t$ese rules6
%ust !e an associative array containing an input varia!le as an array key :like t$e
1age1 input varia!le;
T$e array value must !e a filter I, or an array specifying t$e filter, flags and options
Using 8ilter -all!ack
It is possi!le to call a user defined function and use it as a filter using t$e
8ILT(RD-ALL5A-4 filter" T$is way, we $ave full control of t$e data filtering"
.ou can create your own user defined function or use an e)isting PHP function
T$e function you wis$ to use to filter is specified t$e same way as an option is specified" In
an associative array wit$ t$e name 1options1
In t$e e)ample !elow, we use a user created function to convert all 1D1 to w$itespaces6
*0p$p
function convert'pace:@string;
J
return strDreplace:1D1, 1 1, @string;2
K
@string E 1PeterDisDaDgreatDguy+12
ec$o filterDvar:@string, 8ILT(RD-ALL5A-4,
array:1options1E/1convert'pace1;;2
0/
T$e result from t$e code a!ove s$ould look like t$is6
Peter is a great guy+
()ample ()plained
T$e e)ample a!ove converts all 1D1 to w$itespaces6
1. -reate a function to replace 1D1 to w$itespaces
2. -all t$e filterDvar:; function wit$ t$e 8ILT(RD-ALL5A-4 filter and an array
containing our function
PHP %y'=L -reate ,ata!ase and Ta!les
A data!ase $olds one or multiple ta!les"
73
-reate a ,ata!ase
T$e -R(AT( ,ATA5A'( statement is used to create a data!ase in %y'=L"
'ynta)
-R(AT( ,ATA5A'( data!aseDname
To get PHP to e)ecute t$e statement a!ove we must use t$e mysHlDHuery:; function" T$is function is
used to send a Huery or command to a %y'=L connection"
()ample
T$e following e)ample creates a data!ase called 1myDd!16
*0p$p
@con E mysHlDconnect:1local$ost1,1peter1,1a!cFPU1;2
if :+@con;
J
die:&-ould not connect6 & " mysHlDerror:;;2
K
if :mysHlDHuery:1-R(AT( ,ATA5A'( myDd!1,@con;;
J
ec$o 1,ata!ase created12
K
else
J
ec$o 1(rror creating data!ase6 1 " mysHlDerror:;2
K
mysHlDclose:@con;2
0/
-reate a Ta!le
T$e -R(AT( TA5L( statement is used to create a ta!le in %y'=L"
'ynta)
-R(AT( TA5L( ta!leDname
:
columnDnameF dataDtype,
columnDnameP dataDtype,
columnDnameU dataDtype,
""""
;
e must add t$e -R(AT( TA5L( statement to t$e mysHlDHuery:; function to e)ecute t$e
command"
74
()ample
T$e following e)ample creates a ta!le named 1Persons1, wit$ t$ree columns" T$e column
names will !e 18irst<ame1, 1Last<ame1 and 1Age16
*0p$p
@con E mysHlDconnect:1local$ost1,1peter1,1a!cFPU1;2
if :+@con;
J
die:&-ould not connect6 & " mysHlDerror:;;2
K
33 -reate data!ase
if :mysHlDHuery:1-R(AT( ,ATA5A'( myDd!1,@con;;
J
ec$o 1,ata!ase created12
K
else
J
ec$o 1(rror creating data!ase6 1 " mysHlDerror:;2
K
33 -reate ta!le
mysHlDselectDd!:1myDd!1, @con;2
@sHl E 1-R(AT( TA5L( Persons
:
8irst<ame varc$ar:FI;,
Last<ame varc$ar:FI;,
Age int
;12
33 ()ecute Huery
mysHlDHuery:@sHl,@con;2
mysHlDclose:@con;2
0/
Important6 A data!ase must !e selected !efore a ta!le can !e created" T$e data!ase is
selected wit$ t$e mysHlDselectDd!:; function"
<ote6 $en you create a data!ase field of type varc$ar, you must specify t$e ma)imum
lengt$ of t$e field, e"g" varc$ar:FI;"
T$e data type specifies w$at type of data t$e column can $old"
Primary 4eys and Auto Increment 8ields
(ac$ ta!le s$ould $ave a primary key field"
75
A primary key is used to uniHuely identify t$e rows in a ta!le" (ac$ primary key value must
!e uniHue wit$in t$e ta!le" 8urt$ermore, t$e primary key field cannot !e null !ecause t$e
data!ase engine reHuires a value to locate t$e record"
T$e following e)ample sets t$e personI, field as t$e primary key field" T$e primary key field
is often an I, num!er, and is often used wit$ t$e AUTODI<-R(%(<T setting"
AUTODI<-R(%(<T automatically increases t$e value of t$e field !y F eac$ time a new
record is added" To ensure t$at t$e primary key field cannot !e null, we must add t$e <OT
<ULL setting to t$e field"
()ample
@sHl E 1-R(AT( TA5L( Persons
:
personI, int <OT <ULL AUTODI<-R(%(<T,
PRI%AR. 4(.:personI,;,
8irst<ame varc$ar:FI;,
Last<ame varc$ar:FI;,
Age int
;12
mysHlDHuery:@sHl,@con;2
76
Insert ,ata Into a ,ata!ase Ta!le
T$e I<'(RT I<TO statement is used to add new records to a data!ase ta!le"
'ynta)
It is possi!le to write t$e I<'(RT I<TO statement in two forms"
T$e first form doesn&t specify t$e column names w$ere t$e data will !e inserted, only t$eir
values6
I<'(RT I<TO ta!leDname
?ALU(' :valueF, valueP, valueU,""";
T$e second form specifies !ot$ t$e column names and t$e values to !e inserted6
I<'(RT I<TO ta!leDname :columnF, columnP, columnU,""";
?ALU(' :valueF, valueP, valueU,""";
To learn more a!out '=L, please visit our '=L tutorial"
To get PHP to e)ecute t$e statements a!ove we must use t$e mysHlDHuery:; function" T$is
function is used to send a Huery or command to a %y'=L connection"
()ample
In t$e previous c$apter we created a ta!le named 1Persons1, wit$ t$ree columns2 18irstname1,
1Lastname1 and 1Age1" e will use t$e same ta!le in t$is e)ample" T$e following e)ample
adds two new records to t$e 1Persons1 ta!le6
*0p$p
@con E mysHlDconnect:1local$ost1,1peter1,1a!cFPU1;2
if :+@con;
J
die:&-ould not connect6 & " mysHlDerror:;;2
K
mysHlDselectDd!:1myDd!1, @con;2
mysHlDHuery:1I<'(RT I<TO Persons :8irst<ame, Last<ame, Age;
?ALU(' :&Peter&, &Lriffin&,UI;1;2
mysHlDHuery:1I<'(RT I<TO Persons :8irst<ame, Last<ame, Age;
?ALU(' :&Llenn&, &=uagmire&,UU;1;2
mysHlDclose:@con;2
0/
77
Insert ,ata 8rom a 8orm Into a ,ata!ase
<ow we will create an HT%L form t$at can !e used to add new records to t$e 1Persons1
ta!le"
Here is t$e HT%L form6
*$tml/
*!ody/
*form actionE1insert"p$p1 met$odE1post1/
8irstname6 *input typeE1te)t1 nameE1firstname1/
Lastname6 *input typeE1te)t1 nameE1lastname1/
Age6 *input typeE1te)t1 nameE1age1/
*input typeE1su!mit1/
*3form/
*3!ody/
*3$tml/
$en a user clicks t$e su!mit !utton in t$e HT%L form in t$e e)ample a!ove, t$e form data
is sent to 1insert"p$p1"
T$e 1insert"p$p1 file connects to a data!ase, and retrieves t$e values from t$e form wit$ t$e
PHP @DPO'T varia!les"
T$en, t$e mysHlDHuery:; function e)ecutes t$e I<'(RT I<TO statement, and a new record
will !e added to t$e 1Persons1 ta!le"
Here is t$e 1insert"p$p1 page6
*0p$p
@con E mysHlDconnect:1local$ost1,1peter1,1a!cFPU1;2
if :+@con;
J
die:&-ould not connect6 & " mysHlDerror:;;2
K
mysHlDselectDd!:1myDd!1, @con;2
@sHlE1I<'(RT I<TO Persons :8irst<ame, Last<ame, Age;
?ALU('
:&@DPO'TNfirstnameO&,&@DPO'TNlastnameO&,&@DPO'TNageO&;12
if :+mysHlDHuery:@sHl,@con;;
J
die:&(rror6 & " mysHlDerror:;;2
K
ec$o 1F record added12
78
mysHlDclose:@con;2
0/
'elect ,ata 8rom a ,ata!ase Ta!le
T$e '(L(-T statement is used to select data from a data!ase"
'ynta)
'(L(-T columnDname:s;
8RO% ta!leDname
To get PHP to e)ecute t$e statement a!ove we must use t$e mysHlDHuery:; function" T$is
function is used to send a Huery or command to a %y'=L connection"
()ample
T$e following e)ample selects all t$e data stored in t$e 1Persons1 ta!le :T$e > c$aracter
selects all t$e data in t$e ta!le;6
*0p$p
@con E mysHlDconnect:1local$ost1,1peter1,1a!cFPU1;2
if :+@con;
J
die:&-ould not connect6 & " mysHlDerror:;;2
K
mysHlDselectDd!:1myDd!1, @con;2
@result E mysHlDHuery:1'(L(-T > 8RO% Persons1;2
w$ile:@row E mysHlDfetc$Darray:@result;;
J
ec$o @rowN&8irst<ame&O " 1 1 " @rowN&Last<ame&O2
ec$o 1*!r 3/12
K
mysHlDclose:@con;2
0/
T$e e)ample a!ove stores t$e data returned !y t$e mysHlDHuery:; function in t$e @result
varia!le"
<e)t, we use t$e mysHlDfetc$Darray:; function to return t$e first row from t$e recordset as an
array" (ac$ call to mysHlDfetc$Darray:; returns t$e ne)t row in t$e recordset" T$e w$ile loop
loops t$roug$ all t$e records in t$e recordset" To print t$e value of eac$ row, we use t$e PHP
@row varia!le :@rowN&8irst<ame&O and @rowN&Last<ame&O;"
T$e output of t$e code a!ove will !e6
Peter Lriffin
Llenn =uagmire
79
,isplay t$e Result in an HT%L Ta!le
T$e following e)ample selects t$e same data as t$e e)ample a!ove, !ut will display t$e data
in an HT%L ta!le6
*0p$p
@con E mysHlDconnect:1local$ost1,1peter1,1a!cFPU1;2
if :+@con;
J
die:&-ould not connect6 & " mysHlDerror:;;2
K
mysHlDselectDd!:1myDd!1, @con;2
@result E mysHlDHuery:1'(L(-T > 8RO% Persons1;2
ec$o 1*ta!le !orderE&F&/
*tr/
*t$/8irstname*3t$/
*t$/Lastname*3t$/
*3tr/12
w$ile:@row E mysHlDfetc$Darray:@result;;
J
ec$o 1*tr/12
ec$o 1*td/1 " @rowN&8irst<ame&O " 1*3td/12
ec$o 1*td/1 " @rowN&Last<ame&O " 1*3td/12
ec$o 1*3tr/12
K
ec$o 1*3ta!le/12
mysHlDclose:@con;2
0/
T$e output of t$e code a!ove will !e6
Llenn
Peter
T$e H(R( clause
T$e H(R( clause is used to e)tract only t$ose records t$at fulfill a specified criterion"
'ynta)
'(L(-T columnDname:s;
8RO% ta!leDname
H(R( columnDname operator value
80
To get PHP to e)ecute t$e statement a!ove we must use t$e mysHlDHuery:; function" T$is
function is used to send a Huery or command to a %y'=L connection"
()ample
T$e following e)ample selects all rows from t$e 1Persons1 ta!le w$ere 18irst<ameE&Peter&16
*0p$p
@con E mysHlDconnect:1local$ost1,1peter1,1a!cFPU1;2
if :+@con;
J
die:&-ould not connect6 & " mysHlDerror:;;2
K
mysHlDselectDd!:1myDd!1, @con;2
@result E mysHlDHuery:1'(L(-T > 8RO% Persons
H(R( 8irst<ameE&Peter&1;2
w$ile:@row E mysHlDfetc$Darray:@result;;
J
ec$o @rowN&8irst<ame&O " 1 1 " @rowN&Last<ame&O2
ec$o 1*!r/12
K
0/
T$e output of t$e code a!ove will !e6
Peter Lriffin
T$e OR,(R 5. 4eyword
T$e OR,(R 5. keyword is used to sort t$e data in a recordset"
T$e OR,(R 5. keyword sort t$e records in ascending order !y default"
If you want to sort t$e records in a descending order, you can use t$e ,('- keyword"
'ynta)
'(L(-T columnDname:s;
8RO% ta!leDname
OR,(R 5. columnDname:s; A'-T,('-
81
()ample
T$e following e)ample selects all t$e data stored in t$e 1Persons1 ta!le, and sorts t$e result
!y t$e 1Age1 column6
*0p$p
@con E mysHlDconnect:1local$ost1,1peter1,1a!cFPU1;2
if :+@con;
J
die:&-ould not connect6 & " mysHlDerror:;;2
K
mysHlDselectDd!:1myDd!1, @con;2
@result E mysHlDHuery:1'(L(-T > 8RO% Persons OR,(R 5. age1;2
w$ile:@row E mysHlDfetc$Darray:@result;;
J
ec$o @rowN&8irst<ame&O2
ec$o 1 1 " @rowN&Last<ame&O2
ec$o 1 1 " @rowN&Age&O2
ec$o 1*!r/12
K
mysHlDclose:@con;2
0/
T$e output of t$e code a!ove will !e6
Llenn =uagmire UU
Peter Lriffin UI
Order !y Two -olumns
It is also possi!le to order !y more t$an one column" $en ordering !y more t$an one
column, t$e second column is only used if t$e values in t$e first column are eHual6
'(L(-T columnDname:s;
8RO% ta!leDname
OR,(R 5. columnF, columnP
Update ,ata In a ,ata!ase
T$e UP,AT( statement is used to update e)isting records in a ta!le"
82
'ynta)
UP,AT( ta!leDname
'(T columnFEvalue, columnPEvalueP,"""
H(R( someDcolumnEsomeDvalue
<ote6 <otice t$e H(R( clause in t$e UP,AT( synta)" T$e H(R( clause specifies w$ic$ record
or records t$at s$ould !e updated" If you omit t$e H(R( clause, all records will !e updated+
To get PHP to e)ecute t$e statement a!ove we must use t$e mysHlDHuery:; function" T$is
function is used to send a Huery or command to a %y'=L connection"
()ample
(arlier in t$e tutorial we created a ta!le named 1Persons1" Here is $ow it looks6
8irst<ame
Peter
Llenn
T$e following e)ample updates some data in t$e 1Persons1 ta!le6
*0p$p
@con E mysHlDconnect:1local$ost1,1peter1,1a!cFPU1;2
if :+@con;
J
die:&-ould not connect6 & " mysHlDerror:;;2
K
mysHlDselectDd!:1myDd!1, @con;2
mysHlDHuery:1UP,AT( Persons '(T AgeEUG
H(R( 8irst<ameE&Peter& A<, Last<ameE&Lriffin&1;2
mysHlDclose:@con;2
0/
After t$e update, t$e 1Persons1 ta!le will look like t$is6
8irst<ame
Peter
Llenn
83
,elete ,ata In a ,ata!ase
T$e ,(L(T( 8RO% statement is used to delete records from a data!ase ta!le"
'ynta)
,(L(T( 8RO% ta!leDname
H(R( someDcolumn E someDvalue
<ote6 <otice t$e H(R( clause in t$e ,(L(T( synta)" T$e H(R( clause specifies w$ic$ record
or records t$at s$ould !e deleted" If you omit t$e H(R( clause, all records will !e deleted+
To get PHP to e)ecute t$e statement a!ove we must use t$e mysHlDHuery:; function" T$is
function is used to send a Huery or command to a %y'=L connection"
()ample
Look at t$e following 1Persons1 ta!le6
8irst<ame
Peter
Llenn
T$e following e)ample deletes all t$e records in t$e 1Persons1 ta!le w$ere
Last<ameE&Lriffin&6
*0p$p
@con E mysHlDconnect:1local$ost1,1peter1,1a!cFPU1;2
if :+@con;
J
die:&-ould not connect6 & " mysHlDerror:;;2
K
mysHlDselectDd!:1myDd!1, @con;2
mysHlDHuery:1,(L(T( 8RO% Persons H(R( Last<ameE&Lriffin&1;2
mysHlDclose:@con;2
0/
After t$e deletion, t$e ta!le will look like t$is6
8irst<ame
Llenn
84
PHP ,ata!ase O,5-
-reate an O,5- -onnection
it$ an O,5- connection, you can connect to any data!ase, on any computer in your
network, as long as an O,5- connection is availa!le"
Here is $ow to create an O,5- connection to a %' Access ,ata!ase6
1. Open t$e Administrative Tools icon in your -ontrol Panel"
2. ,ou!le#click on t$e ,ata 'ources :O,5-; icon inside"
3. -$oose t$e 'ystem ,'< ta!"
4. -lick on Add in t$e 'ystem ,'< ta!"
5. 'elect t$e %icrosoft Access ,river" -lick 8inis$"
6. In t$e ne)t screen, click 'elect to locate t$e data!ase"
7. Live t$e data!ase a ,ata 'ource <ame :,'<;"
8. -lick O4"
<ote t$at t$is configuration $as to !e done on t$e computer w$ere your we! site is located" If
you are running Internet Information 'erver :II'; on your own computer, t$e instructions
a!ove will work, !ut if your we! site is located on a remote server, you $ave to $ave p$ysical
access to t$at server, or ask your we! $ost to to set up a ,'< for you to use"
-onnecting to an O,5-
T$e od!cDconnect:; function is used to connect to an O,5- data source" T$e function takes
four parameters6 t$e data source name, username, password, and an optional cursor type"
T$e od!cDe)ec:; function is used to e)ecute an '=L statement"
()ample
T$e following e)ample creates a connection to a ,'< called nort$wind, wit$ no username
and no password" It t$en creates an '=L and e)ecutes it6
@connEod!cDconnect:&nort$wind&,&&,&&;2
@sHlE1'(L(-T > 8RO% customers12
@rsEod!cDe)ec:@conn,@sHl;2
85
Retrieving Records
T$e od!cDfetc$Drow:; function is used to return records from t$e result#set" T$is function
returns true if it is a!le to return rows, ot$erwise false"
T$e function takes two parameters6 t$e O,5- result identifier and an optional row num!er6
od!cDfetc$Drow:@rs;
Retrieving 8ields from a Record
T$e od!cDresult:; function is used to read fields from a record" T$is function takes two
parameters6 t$e O,5- result identifier and a field num!er or name"
T$e code line !elow returns t$e value of t$e first field from t$e record6
@compnameEod!cDresult:@rs,F;2
T$e code line !elow returns t$e value of a field called 1-ompany<ame16
@compnameEod!cDresult:@rs,1-ompany<ame1;2
-losing an O,5- -onnection
T$e od!cDclose:; function is used to close an O,5- connection"
od!cDclose:@conn;2
An O,5- ()ample
T$e following e)ample s$ows $ow to first create a data!ase connection, t$en a result#set, and
t$en display t$e data in an HT%L ta!le"
*$tml/
*!ody/
*0p$p
@connEod!cDconnect:&nort$wind&,&&,&&;2
if :+@conn;
Je)it:1-onnection 8ailed6 1 " @conn;2K
@sHlE1'(L(-T > 8RO% customers12
86
@rsEod!cDe)ec:@conn,@sHl;2
if :+@rs;
Je)it:1(rror in '=L1;2K
ec$o 1*ta!le/*tr/12
ec$o 1*t$/-ompanyname*3t$/12
ec$o 1*t$/-ontactname*3t$/*3tr/12
w$ile :od!cDfetc$Drow:@rs;;
J
@compnameEod!cDresult:@rs,1-ompany<ame1;2
@connameEod!cDresult:@rs,1-ontact<ame1;2
ec$o 1*tr/*td/@compname*3td/12
ec$o 1*td/@conname*3td/*3tr/12
K
od!cDclose:@conn;2
ec$o 1*3ta!le/12
0/
*3!ody/
*3$tml/
$at is 9%L0
9%L is used to descri!e data and to focus on w$at data is" An 9%L file descri!es t$e
structure of t$e data"
In 9%L, no tags are predefined" .ou must define your own tags"
$at is ()pat0
To read and update # create and manipulate # an 9%L document, you will need an 9%L
parser"
T$ere are two !asic types of 9%L parsers6
Tree#!ased parser6 T$is parser transforms an 9%L document into a tree structure" It analyAes
t$e w$ole document, and provides access to t$e tree elements" e"g" t$e ,ocument O!Wect
%odel :,O%;
(vent#!ased parser6 ?iews an 9%L document as a series of events" $en a specific event
occurs, it calls a function to $andle it
T$e ()pat parser is an event#!ased parser"
(vent#!ased parsers focus on t$e content of t$e 9%L documents, not t$eir structure" 5ecause
of t$is, event#!ased parsers can access data faster t$an tree#!ased parsers"
Look at t$e following 9%L fraction6
*from/7ani*3from/
87
An event#!ased parser reports t$e 9%L a!ove as a series of t$ree events6
'tart element6 from
'tart -,ATA section, value6 7ani
-lose element6 from
T$e 9%L e)ample a!ove contains well#formed 9%L" However, t$e e)ample is not valid
9%L, !ecause t$ere is no ,ocument Type ,efinition :,T,; associated wit$ it"
However, t$is makes no difference w$en using t$e ()pat parser" ()pat is a non#validating
parser, and ignores any ,T,s"
As an event#!ased, non#validating 9%L parser, ()pat is fast and small, and a perfect matc$
for PHP we! applications"
<ote6 9%L documents must !e well#formed or ()pat will generate an error"
Installation
T$e 9%L ()pat parser functions are part of t$e PHP core" T$ere is no installation needed to
use t$ese functions"
An 9%L 8ile
T$e 9%L file !elow will !e used in our e)ample6
*0)ml versionE1F"B1 encodingE1I'O#YYIC#F10/
*note/
*to/Tove*3to/
*from/7ani*3from/
*$eading/Reminder*3$eading/
*!ody/,on&t forget me t$is weekend+*3!ody/
*3note/
InitialiAing t$e 9%L Parser
e want to initialiAe t$e 9%L parser in PHP, define some $andlers for different 9%L events,
and t$en parse t$e 9%L file"
()ample
*0p$p
33InitialiAe t$e 9%L parser
88
@parserE)mlDparserDcreate:;2
338unction to use at t$e start of an element
function start:@parser,@elementDname,@elementDattrs;
J
switc$:@elementDname;
J
case 1<OT(16
ec$o 1## <ote ##*!r/12
!reak2
case 1TO16
ec$o 1To6 12
!reak2
case 18RO%16
ec$o 18rom6 12
!reak2
case 1H(A,I<L16
ec$o 1Heading6 12
!reak2
case 15O,.16
ec$o 1%essage6 12
K
K
338unction to use at t$e end of an element
function stop:@parser,@elementDname;
J
ec$o 1*!r/12
K
338unction to use w$en finding c$aracter data
function c$ar:@parser,@data;
J
ec$o @data2
K
33'pecify element $andler
)mlDsetDelementD$andler:@parser,1start1,1stop1;2
33'pecify data $andler
)mlDsetDc$aracterDdataD$andler:@parser,1c$ar1;2
33Open 9%L file
@fpEfopen:1test")ml1,1r1;2
33Read data
w$ile :@dataEfread:@fp,VBCG;;
J
)mlDparse:@parser,@data,feof:@fp;; or
die :sprintf:19%L (rror6 Rs at line Rd1,
)mlDerrorDstring:)mlDgetDerrorDcode:@parser;;,
)mlDgetDcurrentDlineDnum!er:@parser;;;2
K
89
338ree t$e 9%L parser
)mlDparserDfree:@parser;2
0/
T$e output of t$e code a!ove will !e6
## <ote ##
To6 Tove
8rom6 7ani
Heading6 Reminder
%essage6 ,on&t forget me t$is weekend+
How it works6
1. InitialiAe t$e 9%L parser wit$ t$e )mlDparserDcreate:; function
2. -reate functions to use wit$ t$e different event $andlers
3. Add t$e )mlDsetDelementD$andler:; function to specify w$ic$ function will !e e)ecuted w$en
t$e parser encounters t$e opening and closing tags
4. Add t$e )mlDsetDc$aracterDdataD$andler:; function to specify w$ic$ function will e)ecute
w$en t$e parser encounters c$aracter data
5. Parse t$e file 1test")ml1 wit$ t$e )mlDparse:; function
6. In case of an error, add )mlDerrorDstring:; function to convert an 9%L error to a te)tual
description
7. -all t$e )mlDparserDfree:; function to release t$e memory allocated wit$ t$e
)mlDparserDcreate:; function
$at is ,O%0
T$e U- ,O% provides a standard set of o!Wects for HT%L and 9%L documents, and a
standard interface for accessing and manipulating t$em"
T$e U- ,O% is separated into different parts :-ore, 9%L, and HT%L; and different
levels :,O% Level F3P3U;6
> -ore ,O% # defines a standard set of o!Wects for any structured document
> 9%L ,O% # defines a standard set of o!Wects for 9%L documents
> HT%L ,O% # defines a standard set of o!Wects for HT%L documents
If you want to learn more a!out t$e 9%L ,O%, please visit our 9%L ,O% tutorial"
9%L Parsing
To read and update # create and manipulate # an 9%L document, you will need an 9%L
parser"
90
T$ere are two !asic types of 9%L parsers6
Tree#!ased parser6 T$is parser transforms an 9%L document into a tree structure" It analyAes
t$e w$ole document, and provides access to t$e tree elements
(vent#!ased parser6 ?iews an 9%L document as a series of events" $en a specific event
occurs, it calls a function to $andle it
T$e ,O% parser is an tree#!ased parser"
Look at t$e following 9%L document fraction6
*0)ml versionE1F"B1 encodingE1I'O#YYIC#F10/
*from/7ani*3from/
T$e 9%L ,O% sees t$e 9%L a!ove as a tree structure6
Level F6 9%L ,ocument
Level P6 Root element6 *from/
Level U6 Te)t element6 17ani1
Installation
T$e ,O% 9%L parser functions are part of t$e PHP core" T$ere is no installation needed to
use t$ese functions"
An 9%L 8ile
T$e 9%L file !elow will !e used in our e)ample6
*0)ml versionE1F"B1 encodingE1I'O#YYIC#F10/
*note/
*to/Tove*3to/
*from/7ani*3from/
*$eading/Reminder*3$eading/
*!ody/,on&t forget me t$is weekend+*3!ody/
*3note/
Load and Output 9%L
e want to initialiAe t$e 9%L parser, load t$e )ml, and output it6
91
()ample
*0p$p
@)ml,oc E new ,O%,ocument:;2
@)ml,oc#/load:1note")ml1;2
print @)ml,oc#/save9%L:;2
0/
T$e output of t$e code a!ove will !e6
Tove 7ani Reminder ,on&t forget me t$is weekend+
If you select 1?iew source1 in t$e !rowser window, you will see t$e following HT%L6
*0)ml versionE1F"B1 encodingE1I'O#YYIC#F10/
*note/
*to/Tove*3to/
*from/7ani*3from/
*$eading/Reminder*3$eading/
*!ody/,on&t forget me t$is weekend+*3!ody/
*3note/
T$e e)ample a!ove creates a ,O%,ocument#O!Wect and loads t$e 9%L from 1note")ml1
into it"
T$en t$e save9%L:; function puts t$e internal 9%L document into a string, so we can
output it"
Looping t$roug$ 9%L
e want to initialiAe t$e 9%L parser, load t$e 9%L, and loop t$roug$ all elements of t$e
*note/ element6
()ample
*0p$p
@)ml,oc E new ,O%,ocument:;2
@)ml,oc#/load:1note")ml1;2
@) E @)ml,oc#/document(lement2
foreac$ :@)#/c$ild<odes A' @item;
J
print @item#/node<ame " 1 E 1 " @item#/node?alue " 1*!r/12
K
0/
T$e output of t$e code a!ove will !e6
]te)t E
to E Tove
]te)t E
92
from E 7ani
]te)t E
$eading E Reminder
]te)t E
!ody E ,on&t forget me t$is weekend+
]te)t E
In t$e e)ample a!ove you see t$at t$ere are empty te)t nodes !etween eac$ element"
$en 9%L generates, it often contains w$ite#spaces !etween t$e nodes" T$e 9%L ,O%
parser treats t$ese as ordinary elements, and if you are not aware of t$em, t$ey sometimes
cause pro!lems"
93
$at is 'imple9%L0
'imple9%L is new in PHP I" It is an easy way of getting an element&s attri!utes and te)t, if
you know t$e 9%L document&s layout"
-ompared to ,O% or t$e ()pat parser, 'imple9%L Wust takes a few lines of code to read
te)t data from an element"
'imple9%L converts t$e 9%L document into an o!Wect, like t$is6
(lements # Are converted to single attri!utes of t$e 'imple9%L(lement o!Wect" $en
t$ere&s more t$an one element on one level, t$ey&re placed inside an array
Attri!utes # Are accessed using associative arrays, w$ere an inde) corresponds to t$e
attri!ute name
(lement ,ata # Te)t data from elements are converted to strings" If an element $as
more t$an one te)t node, t$ey will !e arranged in t$e order t$ey are found
'imple9%L is fast and easy to use w$en performing !asic tasks like6
Reading 9%L files
()tracting data from 9%L strings
(diting te)t nodes or attri!utes
However, w$en dealing wit$ advanced 9%L, like namespaces, you are !etter off using t$e
()pat parser or t$e 9%L ,O%"
Installation
As of PHP I"B, t$e 'imple9%L functions are part of t$e PHP core" T$ere is no installation
needed to use t$ese functions"
Using 'imple9%L
5elow is an 9%L file6
*0)ml versionE1F"B1 encodingE1I'O#YYIC#F10/
*note/
*to/Tove*3to/
*from/7ani*3from/
*$eading/Reminder*3$eading/
*!ody/,on&t forget me t$is weekend+*3!ody/
*3note/
94
e want to output t$e element names and data from t$e 9%L file a!ove"
Here&s w$at to do6
1. Load t$e 9%L file
2. Let t$e name of t$e first element
3. -reate a loop t$at will trigger on eac$ c$ild node, using t$e c$ildren:; function
4. Output t$e element name and data for eac$ c$ild node
()ample
*0p$p
@)ml E simple)mlDloadDfile:1test")ml1;2
ec$o @)ml#/get<ame:; " 1*!r/12
foreac$:@)ml#/c$ildren:; as @c$ild;
J
ec$o @c$ild#/get<ame:; " 16 1 " @c$ild " 1*!r/12
K
0/
T$e output of t$e code a!ove will !e6
note
to6 Tove
from6 7ani
$eading6 Reminder
!ody6 ,on&t forget me t$is weekend+
95