Vous êtes sur la page 1sur 146

PHP Dummies

Introduction
PHP is a server-side scripting language.
What You Should Already Know
Before you continue you should have a basic understanding of the following:
HTML/HTML
!ava"cript
#f you want to study these sub$ects first% find the tutorials on our Ho&e page.
What is PHP?
PHP stands for PHP: Hyperte't Preprocessor
PHP is a server-side scripting language% li(e )"P
PHP scripts are e'ecuted on the server
PHP supports &any databases *My"+L% #nfor&i'% ,racle% "ybase% "olid% Postgre"+L%
-eneric ,.B/% etc.0
PHP is an open source software
PHP is free to download and use
What is a PHP File?
PHP files can contain te't% HTML tags and scripts
PHP files are returned to the browser as plain HTML
PHP files have a file e'tension of 1.php1% 1.php21% or 1.pht&l1
What is MySQL?
My"+L is a database server
My"+L is ideal for both s&all and large applications
My"+L supports standard "+L
My"+L co&piles on a nu&ber of platfor&s
My"+L is free to download and use
PHP MySQL
PHP co&bined with My"+L are cross-platfor& *you can develop in 3indows and serve on a
4ni' platfor&0
Why PHP?
PHP runs on different platfor&s *3indows% Linu'% 4ni'% etc.0
PHP is co&patible with al&ost all servers used today *)pache% ##"% etc.0
PHP is 5677 to download fro& the official PHP resource: www.php.net
PHP is easy to learn and runs efficiently on the server side
Where to Start?
To get access to a web server with PHP support% you can:
#nstall )pache *or ##"0 on your own server% install PHP% and My"+L
,r find a web hosting plan with PHP and My"+L support
PHP Installation
What do you !eed?
#f your server supports PHP you don8t need to do anything.
!ust create so&e .php files in your web directory% and the server will parse the& for you. Because it
is free% &ost web hosts offer PHP support.
However% if your server does not support PHP% you &ust install PHP.
Here is a lin( to a good tutorial fro& PHP.net on how to install PHP9:
http://www.php.net/&anual/en/install.php
Download PHP
.ownload PHP for free here: http://www.php.net/downloads.php
Download MySQL Data"ase
.ownload My"+L for free here: http://www.&ys:l.co&/downloads/
Download A#ache Ser$er
.ownload )pache for free here: http://httpd.apache.org/download.cgi
PHP Synta%
The PHP script is e'ecuted on the server% and the plain HTML result is sent bac( to the browser.
&asic PHP Synta%
) PHP script always starts with '?#h# and ends with ?(. ) PHP script can be placed anywhere in
the docu&ent.
,n servers with shorthand-support% you can start a PHP script with ;< and end with <=.
5or &a'i&u& co&patibility% we reco&&end that you use the standard for& *;<php0 rather than the
shorthand for&.
;<php
<=
) PHP file &ust have a .php e'tension.
) PHP file nor&ally contains HTML tags% and so&e PHP scripting code.
Below% we have an e'a&ple of a si&ple PHP script that sends the te't 1Hello 3orld1 bac( to the
browser:
;ht&l=
;body=
;<php
echo 1Hello 3orld1>
<=
;/body=
;/ht&l=
7ach code line in PHP &ust end with a se&icolon. The se&icolon is a separator and is used to
distinguish one set of instructions fro& another.
There are two basic state&ents to output te't with PHP: echo and #rint.
#n the e'a&ple above we have used the echo state&ent to output the te't 1Hello 3orld1.
)omments in PHP
#n PHP% we use ** to &a(e a one-line co&&ent or *+ and +* to &a(e a co&&ent bloc(:
;ht&l=
;body=
;<php
//This is a co&&ent
/?
This is
a co&&ent
bloc(
?/
<=
;/body=
;/ht&l=
PHP ,aria"les
@ariables are 1containers1 for storing infor&ation.
Do You -emem"er Al.e"ra From School?
.o you re&e&ber algebra fro& school< 'A9% yAB% CA'Dy
.o you re&e&ber that a letter *li(e '0 could be used to hold a value *li(e 90% and that you could use
the infor&ation above to calculate the value of C to be EE<
These letters are called $aria"les% and variables can be used to hold values *'A90 or e'pressions
*CA'Dy0.
PHP ,aria"les
)s with algebra% PHP variables are used to hold values or e'pressions.
) variable can have a short na&e% li(e '% or a &ore descriptive na&e% li(e carFa&e.
6ules for PHP variable na&es:
@ariables in PHP starts with a G sign% followed by the na&e of the variable
The variable na&e &ust begin with a letter or the underscore character
) variable na&e can only contain alpha-nu&eric characters and underscores *)-C% H-I% and
J 0
) variable na&e should not contain spaces
@ariable na&es are case sensitive *y and K are two different variables0
)reatin. /Declarin.0 PHP ,aria"les
PHP has no co&&and for declaring a variable.
) variable is created the &o&ent you first assign a value to it:
G&y/arA1@olvo1>
)fter the e'ecution of the state&ent above% the variable my)ar will hold the value ,ol$o.
1i#2 #f you want to create a variable without assigning it a value% then you assign it the value of null.
Let8s create a variable containing a string% and a variable containing a nu&ber:
;<php
Gt'tA1Hello 3orldL1>
G'AEB>
<=
!ote2 3hen you assign a te't value to a variable% put :uotes around the value.
PHP is a Loosely 1y#ed Lan.ua.e
#n PHP% a variable does not need to be declared before adding a value to it.
#n the e'a&ple above% notice that we did not have to tell PHP which data type the variable is.
PHP auto&atically converts the variable to the correct data type% depending on its value.
#n a strongly typed progra&&ing language% you have to declare *define0 the type and na&e of the
variable before using it.
PHP ,aria"le Sco#e
The scope of a variable is the portion of the script in which the variable can be referenced.
PHP has four different variable scopes:
local
global
static
para&eter
Local Sco#e
) variable declared within a PHP function is local and can only be accessed within that function.
*the variable has local scope0:
;<php
Ga A 9> // global scope
function &yTest*0
M
echo Ga> // local scope
N
&yTest*0>
<=
The script above will not produce any output because the echo state&ent refers to the local scope
variable Ga% which has not been assigned a value within this scope.
Kou can have local variables with the sa&e na&e in different functions% because local variables are
only recogniCed by the function in which they are declared.
Local variables are deleted as soon as the function is co&pleted.
3lo"al Sco#e
-lobal scope refers to any variable that is defined outside of any function.
-lobal variables can be accessed fro& any part of the script that is not inside a function.
To access a global variable fro& within a function% use the .lo"al (eyword:
;<php
Ga A 9>
Gb A EH>
function &yTest*0
M
global Ga% Gb>
Gb A Ga D Gb>
N
&yTest*0>
echo Gb>
<=
The script above will output E9.
PHP also stores all global variables in an array called G-L,B)L"OindexP. #ts inde' is the na&e of
the variable. This array is also accessible fro& within functions and can be used to update global
variables directly.
The e'a&ple above can be rewritten as this:
;<php
Ga A 9>
Gb A EH>
function &yTest*0
M
G-L,B)L"O8b8P A G-L,B)L"O8a8P D G-L,B)L"O8b8P>
N
&yTest*0>
echo Gb>
<=
Static Sco#e
3hen a function is co&pleted% all of its variables are nor&ally deleted. However% so&eti&es you
want a local variable to not be deleted.
To do this% use the static (eyword when you first declare the variable:
static Gre&e&berMe>
Then% each ti&e the function is called% that variable will still have the infor&ation it contained fro&
the last ti&e the function was called.
!ote2 The variable is still local to the function.
Parameters
) para&eter is a local variable whose value is passed to the function by the calling code.
Para&eters are declared in a para&eter list as part of the function declaration:
function &yTest*GparaE%GparaQ%...0
M
// function code
N
Para&eters are also called argu&ents. 3e will discuss the& in &ore detail when we tal( about
functions.
PHP Strin. ,aria"les
) string variable is used to store and &anipulate te't.
Strin. ,aria"les in PHP
"tring variables are used for values that contain characters.
#n this chapter we are going to loo( at the &ost co&&on functions and operators used to &anipulate
strings in PHP.
)fter we create a string we can &anipulate it. ) string can be used directly in a function or it can be
stored in a variable.
Below% the PHP script assigns the te't 1Hello 3orld1 to a string variable called Gt't:
;<php
Gt'tA1Hello 3orld1>
echo Gt't>
<=
The output of the code above will be:
Hello 3orld
Fow% lets try to use so&e different functions and operators to &anipulate the string.
1he )oncatenation 4#erator
There is only one string operator in PHP.
The concatenation operator *.0 is used to put two string values together.
To concatenate two string variables together% use the concatenation operator:
;<php
Gt'tEA1Hello 3orldL1>
Gt'tQA13hat a nice dayL1>
echo Gt'tE . 1 1 . Gt'tQ>
<=
The output of the code above will be:
Hello 3orldL 3hat a nice dayL
#f we loo( at the code above you see that we used the concatenation operator two ti&es. This is
because we had to insert a third string *a space character0% to separate the two strings.
1he strlen/0 5unction
The strlen*0 function is used to return the length of a string.
Let8s find the length of a string:
;<php
echo strlen*1Hello worldL10>
<=
The output of the code above will be:
EQ
The length of a string is often used in loops or other functions% when it is i&portant to (now when
the string ends. *i.e. in a loop% we would want to stop the loop after the last character in the string0.
1he str#os/0 5unction
The strpos*0 function is used to search for a character/te't within a string.
#f a &atch is found% this function will return the character position of the first &atch. #f no &atch is
found% it will return 5)L"7.
Let8s see if we can find the string 1world1 in our string:
;<php
echo strpos*1Hello worldL1%1world10>
<=
The output of the code above will be:
B
The position of the string 1world1 in the e'a&ple above is B. The reason that it is B *and not R0% is
that the first character position in the string is H% and not E.
)om#lete PHP Strin. -e5erence
5or a co&plete reference of all string functions% go to our co&plete PHP "tring 6eference.
The reference contains a brief description% and e'a&ples of use% for each functionL
PHP 4#erators
The assign&ent operator A is used to assign values to variables in PHP.
The arith&etic operator D is used to add values together.
Arithmetic 4#erators
The table below lists the arith&etic operators in PHP:
4#erator !ame Descri#tion 6%am#le -esult
' D y )ddition "u& of ' and y Q D Q S
' - y "ubtraction .ifference of ' and y 9 - Q 2
' ? y Multiplication Product of ' and y 9 ? Q EH
' / y .ivision +uotient of ' and y E9 / 9 2
' T y Modulus 6e&ainder of ' divided by y
9 T Q
EH T U
EH T Q
E
Q
H
- ' Fegation ,pposite of ' - Q
a . b /oncatenation /oncatenate two strings 1Hi1 . 1Ha1 HiHa
Assi.nment 4#erators
The basic assign&ent operator in PHP is 1A1. #t &eans that the left operand gets set to the value of
the e'pression on the right. That is% the value of 1G' A 91 is 9.
Assi.nment Same as777 Descri#tion
' A y ' A y The left operand gets set to the value of the e'pression on the right
' DA y ' A ' D y )ddition
' -A y ' A ' - y "ubtraction
' ?A y ' A ' ? y Multiplication
' /A y ' A ' / y .ivision
' TA y ' A ' T y Modulus
a .A b a A a . b /oncatenate two strings
Incrementin.*Decrementin. 4#erators
4#erator !ame Descri#tion
DD ' Pre-incre&ent #ncre&ents ' by one% then returns '
' DD Post-incre&ent 6eturns '% then incre&ents ' by one
-- ' Pre-decre&ent .ecre&ents ' by one% then returns '
' -- Post-decre&ent 6eturns '% then decre&ents ' by one
)om#arison 4#erators
/o&parison operators allows you to co&pare two values:
4#erator !ame Descri#tion 6%am#le
' AA y 7:ual True if ' is e:ual to y 9AAU returns false
' AAA y #dentical
True if ' is e:ual to y% and they are
of sa&e type
9AAA191 returns false
' LA y Fot e:ual True if ' is not e:ual to y 9LAU returns true
' ;= y Fot e:ual True if ' is not e:ual to y 9;=U returns true
' LAA y Fot identical
True if ' is not e:ual to y% or they are
not of sa&e type
9LAA191 returns true
' = y -reater than True if ' is greater than y 9=U returns false
' ; y Less than True if ' is less than y 9;U returns true
' =A y
-reater than or
e:ual to
True if ' is greater than or e:ual to y 9=AU returns false
' ;A y
Less than or e:ual
to
True if ' is less than or e:ual to y 9;AU returns true
Lo.ical 4#erators
4#erator !ame Descri#tion 6%am#le
' and y )nd True if both ' and y are true
'AB
yA2
*' ; EH and y = E0 returns true
' or y ,r True if either or both ' and y are true
'AB
yA2
*'AAB or yAA90 returns true
' 'or y or
True if either ' or y is true% but not
both
'AB
yA2
*'AAB 'or yAA20 returns false
' VV y )nd True if both ' and y are true
'AB
yA2
*' ; EH VV y = E0 returns
true
' WW y ,r True if either or both ' and y are true
'AB
yA2
*'AA9 WW yAA90 returns false
L ' Fot True if ' is not true
'AB
yA2
L*'AAy0 returns true
Array 4#erators
4#erator !ame Descri#tion
' D y 4nion 4nion of ' and y
' AA y 7:uality True if ' and y have the sa&e (ey/value pairs
' AAA y #dentity
True if ' and y have the sa&e (ey/value pairs in the sa&e order and
of the sa&e types
' LA y #ne:uality True if ' is not e:ual to y
' ;= y #ne:uality True if ' is not e:ual to y
' LAA y Fon-identity True if ' is not identical to y
PHP I57776lse Statements
/onditional state&ents are used to perfor& different actions based on different conditions.
)onditional Statements
@ery often when you write code% you want to perfor& different actions for different decisions.
Kou can use conditional state&ents in your code to do this.
#n PHP we have the following conditional state&ents:
i5 statement - use this state&ent to e'ecute so&e code only if a specified condition is true
i5777else statement - use this state&ent to e'ecute so&e code if a condition is true and another
code if the condition is false
i5777elsei57777else statement - use this state&ent to select one of several bloc(s of code to be
e'ecuted
switch statement - use this state&ent to select one of &any bloc(s of code to be e'ecuted
1he i5 Statement
4se the if state&ent to e'ecute so&e code only if a specified condition is true.
Syntax
if *condition0 code to be executed if condition is true;
The following e'a&ple will output 1Have a nice wee(endL1 if the current day is 5riday:
;ht&l=
;body=
;<php
GdAdate*1.10>
if *GdAA15ri10 echo 1Have a nice wee(endL1>
<=
;/body=
;/ht&l=
Fotice that there is no ..else.. in this synta'. The code is e'ecuted only i5 the s#eci5ied condition is
true.
1he i5777else Statement
4se the if....else state&ent to e'ecute so&e code if a condition is true and another code if a condition
is false.
Syntax
if *condition0
M
code to be executed if condition is true;
N
else
M
code to be executed if condition is false;
N
Example
The following e'a&ple will output 1Have a nice wee(endL1 if the current day is 5riday% otherwise it
will output 1Have a nice dayL1:
;ht&l=
;body=
;<php
GdAdate*1.10>
if *GdAA15ri10
M
echo 1Have a nice wee(endL1>
N
else
M
echo 1Have a nice dayL1>
N
<=
;/body=
;/ht&l=
1he i5777elsei57777else Statement
4se the if....elseif...else state&ent to select one of several bloc(s of code to be e'ecuted.
Syntax
if *condition0
M
code to be executed if condition is true;
N
elseif *condition0
M
code to be executed if condition is true;
N
else
M
code to be executed if condition is false;
N
Example
The following e'a&ple will output 1Have a nice wee(endL1 if the current day is 5riday% and 1Have a
nice "undayL1 if the current day is "unday. ,therwise it will output 1Have a nice dayL1:
;ht&l=
;body=
;<php
GdAdate*1.10>
if *GdAA15ri10
M
echo 1Have a nice wee(endL1>
N
elseif *GdAA1"un10
M
echo 1Have a nice "undayL1>
N
else
M
echo 1Have a nice dayL1>
N
<=
;/body=
;/ht&l=
PHP Switch Statement
/onditional state&ents are used to perfor& different actions based on different conditions.
1he PHP Switch Statement
4se the switch state&ent to select one of &any bloc(s of code to be e'ecuted.
Syntax
switch *n0
M
case label1:
code to be executed if n=label1;
brea(>
case label2:
code to be executed if n=label2;
brea(>
default:
code to be executed if n is different from both label1 and label2;
N
This is how it wor(s: 5irst we have a single e'pression n *&ost often a variable0% that is evaluated
once. The value of the e'pression is then co&pared with the values for each case in the structure. #f
there is a &atch% the bloc( of code associated with that case is e'ecuted. 4se "rea8 to prevent the
code fro& running into the ne't case auto&atically. The default state&ent is used if no &atch is
found.
Example
;ht&l=
;body=
;<php
G'AE>
switch *G'0
M
case E:
echo 1Fu&ber E1>
brea(>
case Q:
echo 1Fu&ber Q1>
brea(>
case 2:
echo 1Fu&ber 21>
brea(>
default:
echo 1Fo nu&ber between E and 21>
N
<=
;/body=
;/ht&l=
PHP Arrays
)n array stores &ultiple values in one single variable.
What is an Array?
) variable is a storage area holding a nu&ber or te't. The proble& is% a variable will hold only one
value.
)n array is a special variable% which can store &ultiple values in one single variable.
#f you have a list of ite&s *a list of car na&es% for e'a&ple0% storing the cars in single variables could
loo( li(e this:
GcarsEA1"aab1>
GcarsQA1@olvo1>
Gcars2A1BM31>
However% what if you want to loop through the cars and find a specific one< )nd what if you had not
2 cars% but 2HH<
The best solution here is to use an arrayL
)n array can hold all your variable values under a single na&e. )nd you can access the values by
referring to the array na&e.
7ach ele&ent in the array has its own inde' so that it can be easily accessed.
#n PHP% there are three (ind of arrays:
!umeric array - )n array with a nu&eric inde'
Associati$e array - )n array where each #. (ey is associated with a value
Multidimensional array - )n array containing one or &ore arrays
!umeric Arrays
) nu&eric array stores each array ele&ent with a nu&eric inde'.
There are two &ethods to create a nu&eric array.
E. #n the following e'a&ple the inde' are auto&atically assigned *the inde' starts at H0:
GcarsAarray*1"aab1%1@olvo1%1BM31%1Toyota10>
Q. #n the following e'a&ple we assign the inde' &anually:
GcarsOHPA1"aab1>
GcarsOEPA1@olvo1>
GcarsOQPA1BM31>
GcarsO2PA1Toyota1>
Example
#n the following e'a&ple you access the variable values by referring to the array na&e and inde':
;<php
GcarsOHPA1"aab1>
GcarsOEPA1@olvo1>
GcarsOQPA1BM31>
GcarsO2PA1Toyota1>
echo GcarsOHP . 1 and 1 . GcarsOEP . 1 are "wedish cars.1>
<=
The code above will output:
"aab and @olvo are "wedish cars.
Associati$e Arrays
)n associative array% each #. (ey is associated with a value.
3hen storing data about specific na&ed values% a nu&erical array is not always the best way to do it.
3ith associative arrays we can use the values as (eys and assign values to the&.
Example 1
#n this e'a&ple we use an array to assign ages to the different persons:
Gages A array*1Peter1A=2Q% 1+uag&ire1A=2H% 1!oe1A=2S0>
Example 2
This e'a&ple is the sa&e as e'a&ple E% but shows a different way of creating the array:
GagesO8Peter8P A 12Q1>
GagesO8+uag&ire8P A 12H1>
GagesO8!oe8P A 12S1>
The #. (eys can be used in a script:
;<php
GagesO8Peter8P A 12Q1>
GagesO8+uag&ire8P A 12H1>
GagesO8!oe8P A 12S1>
echo 1Peter is 1 . GagesO8Peter8P . 1 years old.1>
<=
The code above will output:
Peter is 2Q years old.
Multidimensional Arrays
#n a &ultidi&ensional array% each ele&ent in the &ain array can also be an array. )nd each ele&ent
in the sub-array can be an array% and so on.
Example
#n this e'a&ple we create a &ultidi&ensional array% with auto&atically assigned #. (eys:
Gfa&ilies A array
*
1-riffin1A=array
*
1Peter1%
1Lois1%
1Megan1
0%
1+uag&ire1A=array
*
1-lenn1
0%
1Brown1A=array
*
1/leveland1%
1Loretta1%
1!unior1
0
0>
The array above would loo( li(e this if written to the output:
)rray
*
O-riffinP A= )rray
*
OHP A= Peter
OEP A= Lois
OQP A= Megan
0
O+uag&ireP A= )rray
*
OHP A= -lenn
0
OBrownP A= )rray
*
OHP A= /leveland
OEP A= Loretta
OQP A= !unior
0
0
Example 2
Lets try displaying a single value fro& the array above:
echo 1#s 1 . Gfa&iliesO8-riffin8POQP .
1 a part of the -riffin fa&ily<1>
The code above will output:
#s Megan a part of the -riffin fa&ily<
)om#lete PHP Array -e5erence
5or a co&plete reference of all array functions% go to our co&plete PHP )rray 6eference.
The reference contains a brief description% and e'a&ples of use% for each functionL
PHP Loo#in. 9 While Loo#s
Loops e'ecute a bloc( of code a specified nu&ber of ti&es% or while a specified condition is true.
PHP Loo#s
,ften when you write code% you want the sa&e bloc( of code to run over and over again in a row.
#nstead of adding several al&ost e:ual lines in a script we can use loops to perfor& a tas( li(e this.
#n PHP% we have the following looping state&ents:
while - loops through a bloc( of code while a specified condition is true
do777while - loops through a bloc( of code once% and then repeats the loop as long as a
specified condition is true
5or - loops through a bloc( of code a specified nu&ber of ti&es
5oreach - loops through a bloc( of code for each ele&ent in an array
1he while Loo#
The while loop e'ecutes a bloc( of code while a condition is true.
Syntax
while *condition0
M
code to be executed>
N
Example
The e'a&ple below defines a loop that starts with iAE. The loop will continue to run as long as i is
less than% or e:ual to 9. i will increase by E each ti&e the loop runs:
;ht&l=
;body=
;<php
GiAE>
while*Gi;A90
M
echo 1The nu&ber is 1 . Gi . 1;br /=1>
GiDD>
N
<=
;/body=
;/ht&l=
,utput:
The nu&ber is E
The nu&ber is Q
The nu&ber is 2
The nu&ber is S
The nu&ber is 9
1he do777while Statement
The do...while state&ent will always e'ecute the bloc( of code once% it will then chec( the condition%
and repeat the loop while the condition is true.
Syntax
do
M
code to be executed;
N
while *condition0>
Example
The e'a&ple below defines a loop that starts with iAE. #t will then incre&ent i with E% and write
so&e output. Then the condition is chec(ed% and the loop will continue to run as long as i is less
than% or e:ual to 9:
;ht&l=
;body=
;<php
GiAE>
do
M
GiDD>
echo 1The nu&ber is 1 . Gi . 1;br /=1>
N
while *Gi;A90>
<=
;/body=
;/ht&l=
,utput:
The nu&ber is Q
The nu&ber is 2
The nu&ber is S
The nu&ber is 9
The nu&ber is B
The for loop and the foreach loop will be e'plained in the ne't chapter.
PHP Loo#in. 9 For Loo#s
Loops e'ecute a bloc( of code a specified nu&ber of ti&es% or while a specified condition is true.
1he 5or Loo#
The for loop is used when you (now in advance how &any ti&es the script should run.
Syntax
for *init; condition; increment0
M
code to be executed;
N
Para&eters:
init: Mostly used to set a counter *but can be any code to be e'ecuted once at the beginning
of the loop0
condition: 7valuated for each loop iteration. #f it evaluates to T647% the loop continues. #f it
evaluates to 5)L"7% the loop ends.
increment: Mostly used to incre&ent a counter *but can be any code to be e'ecuted at the end
of the iteration0
!ote2 The init and increment para&eters above can be e&pty or have &ultiple e'pressions
*separated by co&&as0.
Example
The e'a&ple below defines a loop that starts with iAE. The loop will continue to run as long as the
variable i is less than% or e:ual to 9. The variable i will increase by E each ti&e the loop runs:
;ht&l=
;body=
;<php
for *GiAE> Gi;A9> GiDD0
M
echo 1The nu&ber is 1 . Gi . 1;br /=1>
N
<=
;/body=
;/ht&l=
,utput:
The nu&ber is E
The nu&ber is Q
The nu&ber is 2
The nu&ber is S
The nu&ber is 9
1he 5oreach Loo#
The foreach loop is used to loop through arrays.
Syntax
foreach *Garray as Gvalue0
M
code to be executed;
N
5or every loop iteration% the value of the current array ele&ent is assigned to Gvalue *and the array
pointer is &oved by one0 - so on the ne't loop iteration% you8ll be loo(ing at the ne't array value.
Example
The following e'a&ple de&onstrates a loop that will print the values of the given array:
;ht&l=
;body=
;<php
G'Aarray*1one1%1two1%1three10>
foreach *G' as Gvalue0
M
echo Gvalue . 1;br /=1>
N
<=
;/body=
;/ht&l=
,utput:
one
two
three
PHP Functions
The real power of PHP co&es fro& its functions.
#n PHP% there are &ore than RHH built-in functions.
PHP &uilt9in Functions
5or a co&plete reference and e'a&ples of the built-in functions% please visit our PHP 6eference.
PHP Functions
#n this chapter we will show you how to create your own functions.
To (eep the script fro& being e'ecuted when the page loads% you can put it into a function.
) function will be e'ecuted by a call to the function.
Kou &ay call a function fro& anywhere within a page.
)reate a PHP Function
) function will be e'ecuted by a call to the function.
Syntax
function functionName*0
M
code to be executed>
N
PHP function guidelines:
-ive the function a na&e that reflects what the function does
The function na&e can start with a letter or underscore *not a nu&ber0
Example
) si&ple function that writes &y na&e when it is called:
;ht&l=
;body=
;<php
function writeFa&e*0
M
echo 1Xai !i& 6efsnes1>
N
echo 1My na&e is 1>
writeFa&e*0>
<=
;/body=
;/ht&l=
,utput:
My na&e is Xai !i& 6efsnes
PHP Functions 9 Addin. #arameters
To add &ore functionality to a function% we can add para&eters. ) para&eter is $ust li(e a variable.
Para&eters are specified after the function na&e% inside the parentheses.
Example 1
The following e'a&ple will write different first na&es% but e:ual last na&e:
;ht&l=
;body=
;<php
function writeFa&e*Gfna&e0
M
echo Gfna&e . 1 6efsnes.;br /=1>
N
echo 1My na&e is 1>
writeFa&e*1Xai !i&10>
echo 1My sister8s na&e is 1>
writeFa&e*1Hege10>
echo 1My brother8s na&e is 1>
writeFa&e*1"tale10>
<=
;/body=
;/ht&l=
,utput:
My na&e is Xai !i& 6efsnes.
My sister8s na&e is Hege 6efsnes.
My brother8s na&e is "tale 6efsnes.
Example 2
The following function has two para&eters:
;ht&l=
;body=
;<php
function writeFa&e*Gfna&e%Gpunctuation0
M
echo Gfna&e . 1 6efsnes1 . Gpunctuation . 1;br /=1>
N
echo 1My na&e is 1>
writeFa&e*1Xai !i&1%1.10>
echo 1My sister8s na&e is 1>
writeFa&e*1Hege1%1L10>
echo 1My brother8s na&e is 1>
writeFa&e*1"tYle1%1<10>
<=
;/body=
;/ht&l=
,utput:
My na&e is Xai !i& 6efsnes.
My sister8s na&e is Hege 6efsnesL
My brother8s na&e is "tYle 6efsnes<

PHP Functions 9 -eturn $alues
To let a function return a value% use the return state&ent.
Example
;ht&l=
;body=
;<php
function add*G'%Gy0
M
GtotalAG'DGy>
return Gtotal>
N
echo 1E D EB A 1 . add*E%EB0>
<=
;/body=
;/ht&l=
,utput:
E D EB A ER
PHP Forms and :ser In#ut
The PHP GJ-7T and GJP,"T variables are used to retrieve infor&ation fro& for&s% li(e user input.
PHP Form Handlin.
The &ost i&portant thing to notice when dealing with HTML for&s and PHP is that any for&
ele&ent in an HTML page will automatically be available to your PHP scripts.
Example
The e'a&ple below contains an HTML for& with two input fields and a sub&it button:
;ht&l=
;body=
;for& actionA1welco&e.php1 &ethodA1post1=
Fa&e: ;input typeA1te't1 na&eA1fna&e1 /=
)ge: ;input typeA1te't1 na&eA1age1 /=
;input typeA1sub&it1 /=
;/for&=
;/body=
;/ht&l=
3hen a user fills out the for& above and clic(s on the sub&it button% the for& data is sent to a PHP
file% called 1welco&e.php1:
1welco&e.php1 loo(s li(e this:
;ht&l=
;body=
3elco&e ;<php echo GJP,"TO1fna&e1P> <=L;br /=
Kou are ;<php echo GJP,"TO1age1P> <= years old.
;/body=
;/ht&l=
,utput could be so&ething li(e this:
3elco&e !ohnL
Kou are QU years old.
The PHP GJ-7T and GJP,"T variables will be e'plained in the ne't chapters.
Form ,alidation
4ser input should be validated on the browser whenever possible *by client scripts0. Browser
validation is faster and reduces the server load.
Kou should consider server validation if the user input will be inserted into a database. ) good way
to validate a for& on the server is to post the for& to itself% instead of $u&ping to a different page.
The user will then get the error &essages on the sa&e page as the for&. This &a(es it easier to
discover the error.
PHP ;<361 ,aria"le
#n PHP% the predefined GJ-7T variable is used to collect values in a for& with &ethodA1get1.
1he ;<361 ,aria"le
The predefined GJ-7T variable is used to collect values in a for& with &ethodA1get1
#nfor&ation sent fro& a for& with the -7T &ethod is visible to everyone *it will be displayed in the
browser8s address bar0 and has li&its on the a&ount of infor&ation to send.
Example
;for& actionA1welco&e.php1 &ethodA1get1=
Fa&e: ;input typeA1te't1 na&eA1fna&e1 /=
)ge: ;input typeA1te't1 na&eA1age1 /=
;input typeA1sub&it1 /=
;/for&=
3hen the user clic(s the 1"ub&it1 button% the 46L sent to the server could loo( so&ething li(e this:
http://www.w2schools.co&/welco&e.php<fna&eAPeterVageA2R
The 1welco&e.php1 file can now use the GJ-7T variable to collect for& data *the na&es of the for&
fields will auto&atically be the (eys in the GJ-7T array0:
3elco&e ;<php echo GJ-7TO1fna&e1P> <=.;br /=
Kou are ;<php echo GJ-7TO1age1P> <= years oldL
When to use method=>.et>?
3hen using &ethodA1get1 in HTML for&s% all variable na&es and values are displayed in the 46L.
!ote2 This &ethod should not be used when sending passwords or other sensitive infor&ationL
However% because the variables are displayed in the 46L% it is possible to boo(&ar( the page. This
can be useful in so&e cases.
!ote2 The get &ethod is not suitable for very large variable values. #t should not be used with values
e'ceeding QHHH characters.
PHP ;<P4S1 Function
#n PHP% the predefined GJP,"T variable is used to collect values in a for& with &ethodA1post1.
1he ;<P4S1 ,aria"le
The predefined GJP,"T variable is used to collect values fro& a for& sent with &ethodA1post1.
#nfor&ation sent fro& a for& with the P,"T &ethod is invisible to others and has no li&its on the
a&ount of infor&ation to send.
!ote2 However% there is an U Mb &a' siCe for the P,"T &ethod% by default *can be changed by
setting the postJ&a'JsiCe in the php.ini file0.
Example
;for& actionA1welco&e.php1 &ethodA1post1=
Fa&e: ;input typeA1te't1 na&eA1fna&e1 /=
)ge: ;input typeA1te't1 na&eA1age1 /=
;input typeA1sub&it1 /=
;/for&=
3hen the user clic(s the 1"ub&it1 button% the 46L will loo( li(e this:
http://www.w2schools.co&/welco&e.php
The 1welco&e.php1 file can now use the GJP,"T variable to collect for& data *the na&es of the
for& fields will auto&atically be the (eys in the GJP,"T array0:
3elco&e ;<php echo GJP,"TO1fna&e1P> <=L;br /=
Kou are ;<php echo GJP,"TO1age1P> <= years old.
When to use method=>#ost>?
#nfor&ation sent fro& a for& with the P,"T &ethod is invisible to others and has no li&its on the
a&ount of infor&ation to send.
However% because the variables are not displayed in the 46L% it is not possible to boo(&ar( the
page.
1he PHP ;<-6Q:6S1 ,aria"le
The predefined GJ67+47"T variable contains the contents of both GJ-7T% GJP,"T% and
GJ/,,X#7.
The GJ67+47"T variable can be used to collect for& data sent with both the -7T and P,"T
&ethods.
Example
3elco&e ;<php echo GJ67+47"TO1fna&e1P> <=L;br /=
Kou are ;<php echo GJ67+47"TO1age1P> <= years old.
PHP Ad$ance
PHP Date/0 Function
The PHP date*0 function is used to for&at a ti&e and/or date.
1he PHP Date/0 Function
The PHP date*0 function for&ats a ti&esta&p to a &ore readable date and ti&e.
) ti&esta&p is a se:uence of characters% denoting the date and/or ti&e at which a certain event
occurred.
Syntax
date*format%timestamp0
Parameter Descri#tion
for&at 6e:uired. "pecifies the for&at of the ti&esta&p
ti&esta&p ,ptional. "pecifies a ti&esta&p. .efault is the current date and ti&e
PHP Date/0 9 Format the Date
The re:uired format para&eter in the date*0 function specifies how to for&at the date/ti&e.
Here are so&e characters that can be used:
d - 6epresents the day of the &onth *HE to 2E0
& - 6epresents a &onth *HE to EQ0
K - 6epresents a year *in four digits0
) list of all the characters that can be used in the format para&eter% can be found in our PHP .ate
reference.
,ther characters% li(e1/1% 1.1% or 1-1 can also be inserted between the letters to add additional
for&atting:
;<php
echo date*1K/&/d10 . 1;br /=1>
echo date*1K.&.d10 . 1;br /=1>
echo date*1K-&-d10>
<=
The output of the code above could be so&ething li(e this:
QHHI/H9/EE
QHHI.H9.EE
QHHI-H9-EE
PHP Date/0 9 Addin. a 1imestam#
The optional timestamp para&eter in the date*0 function specifies a ti&esta&p. #f you do not specify
a ti&esta&p% the current date and ti&e will be used.
The &(ti&e*0 function returns the 4ni' ti&esta&p for a date.
The 4ni' ti&esta&p contains the nu&ber of seconds between the 4ni' 7poch *!anuary E EIRH
HH:HH:HH -MT0 and the ti&e specified.
Syntax for mktime()
&(ti&e*hour%&inute%second%&onth%day%year%isJdst0
To go one day in the future we si&ply add one to the day argu&ent of &(ti&e*0:
;<php
Gto&orrow A &(ti&e*H%H%H%date*1&10%date*1d10DE%date*1K100>
echo 1To&orrow is 1.date*1K/&/d1% Gto&orrow0>
<=
The output of the code above could be so&ething li(e this:
To&orrow is QHHI/H9/EQ
)om#lete PHP Date -e5erence
5or a co&plete reference of all date functions% go to our co&plete PHP .ate 6eference.
The reference contains a brief description% and e'a&ples of use% for each functionL
PHP Include Files
PHP include and re?uire Statements
#n PHP% you can insert the content of one PHP file into another PHP file before the server e'ecutes it.
The include and re:uire state&ents are used to insert useful codes written in other files% in the flow
of e'ecution.
Include and re?uire are identical@ e%ce#t u#on 5ailure2
re:uire will produce a fatal error *7J/,MP#L7J766,60 and stop the script
include will only produce a warning *7J3)6F#F-0 and the script will continue
"o% if you want the e'ecution to go on and show users the output% even if the include file is &issing%
use include. ,therwise% in case of 5ra&e3or(% /M" or a co&ple' PHP application coding% always
use re:uire to include a (ey file to the flow of e'ecution. This will help avoid co&pro&ising your
application8s security and integrity% $ust in-case one (ey file is accidentally &issing.
#ncluding files saves a lot of wor(. This &eans that you can create a standard header% footer% or &enu
file for all your web pages. Then% when the header needs to be updated% you can only update the
header include file.
Synta%
include 8filename8>
or
re:uire 8filename8>
PHP include and re?uire Statement
Basic Example
)ssu&e that you have a standard header file% called 1header.php1. To include the header file in a
page% use include/re:uire:
;ht&l=
;body=
;<php include 8header.php8> <=
;hE=3elco&e to &y ho&e pageL;/hE=
;p="o&e te't.;/p=
;/body=
;/ht&l=
Example 2
)ssu&e we have a standard &enu file that should be used on all pages.
1&enu.php1:
echo 8;a hrefA1/default.php1=Ho&e;/a=
;a hrefA1/tutorials.php1=Tutorials;/a=
;a hrefA1/references.php1=6eferences;/a=
;a hrefA1/e'a&ples.php1=7'a&ples;/a=
;a hrefA1/about.php1=)bout 4s;/a=
;a hrefA1/contact.php1=/ontact 4s;/a=8>
)ll pages in the 3eb site should include this &enu file. Here is how it can be done:
;ht&l=
;body=
;div classA1left&enu1=
;<php include 8&enu.php8> <=
;/div=
;hE=3elco&e to &y ho&e page.;/hE=
;p="o&e te't.;/p=
;/body=
;/ht&l=
Example 3
)ssu&e we have an include file with so&e variables defined *1vars.php10:
;<php
GcolorA8red8>
GcarA8BM38>
<=
Then the variables can be used in the calling file:
;ht&l=
;body=
;hE=3elco&e to &y ho&e page.;/hE=
;<php include 8vars.php8>
echo 1# have a Gcolor Gcar1> // # have a red BM3
<=
;/body=
;/ht&l=
PHP File Handlin.
The fopen*0 function is used to open files in PHP.
4#enin. a File
The fopen*0 function is used to open files in PHP.
The first para&eter of this function contains the na&e of the file to be opened and the second
para&eter specifies in which &ode the file should be opened:
;ht&l=
;body=
;<php
GfileAfopen*1welco&e.t't1%1r10>
<=
;/body=
;/ht&l=
The file &ay be opened in one of the following &odes:
Modes Descri#tion
r 6ead only. "tarts at the beginning of the file
rD 6ead/3rite. "tarts at the beginning of the file
w 3rite only. ,pens and clears the contents of file> or creates a new file if it
doesn8t e'ist
wD 6ead/3rite. ,pens and clears the contents of file> or creates a new file if it
doesn8t e'ist
a )ppend. ,pens and writes to the end of the file or creates a new file if it doesn8t
e'ist
aD 6ead/)ppend. Preserves file content by writing to the end of the file
' 3rite only. /reates a new file. 6eturns 5)L"7 and an error if file already e'ists
'D 6ead/3rite. /reates a new file. 6eturns 5)L"7 and an error if file already e'ists
!ote2 #f the fopen*0 function is unable to open the specified file% it returns H *false0.
Example
The following e'a&ple generates a &essage if the fopen*0 function is unable to open the specified
file:
;ht&l=
;body=
;<php
GfileAfopen*1welco&e.t't1%1r10 or e'it*14nable to open fileL10>
<=
;/body=
;/ht&l=
)losin. a File
The fclose*0 function is used to close an open file:
;<php
Gfile A fopen*1test.t't1%1r10>
//so&e code to be e'ecuted
fclose*Gfile0>
<=
)hec8 6nd9o595ile
The feof*0 function chec(s if the 1end-of-file1 *7,50 has been reached.
The feof*0 function is useful for looping through data of un(nown length.
!ote2 Kou cannot read fro& files opened in w% a% and ' &odeL
if *feof*Gfile00 echo 17nd of file1>
-eadin. a File Line "y Line
The fgets*0 function is used to read a single line fro& a file.
!ote2 )fter a call to this function the file pointer has &oved to the ne't line.
Example
The e'a&ple below reads a file line by line% until the end of file is reached:
;<php
Gfile A fopen*1welco&e.t't1% 1r10 or e'it*14nable to open fileL10>
//,utput a line of the file until the end is reached
while*Lfeof*Gfile00
M
echo fgets*Gfile0. 1;br /=1>
N
fclose*Gfile0>
<=
-eadin. a File )haracter "y )haracter
The fgetc*0 function is used to read a single character fro& a file.
!ote2 )fter a call to this function the file pointer &oves to the ne't character.
Example
The e'a&ple below reads a file character by character% until the end of file is reached:
;<php
GfileAfopen*1welco&e.t't1%1r10 or e'it*14nable to open fileL10>
while *Lfeof*Gfile00
M
echo fgetc*Gfile0>
N
fclose*Gfile0>
<=
PHP Filesystem -e5erence
5or a full reference of the PHP filesyste& functions% visit our PHP 5ilesyste& 6eference.
PHP File :#load
3ith PHP% it is possible to upload files to the server.
)reate an :#load9File Form
To allow users to upload files fro& a for& can be very useful.
Loo( at the following HTML for& for uploading files:
;ht&l=
;body=
;for& actionA1uploadJfile.php1 &ethodA1post1
enctypeA1&ultipart/for&-data1=
;label forA1file1=5ilena&e:;/label=
;input typeA1file1 na&eA1file1 idA1file1 /=
;br /=
;input typeA1sub&it1 na&eA1sub&it1 valueA1"ub&it1 /=
;/for&=
;/body=
;/ht&l=
Fotice the following about the HTML for& above:
The enctype attribute of the ;for&= tag specifies which content-type to use when sub&itting
the for&. 1&ultipart/for&-data1 is used when a for& re:uires binary data% li(e the contents of
a file% to be uploaded
The typeA1file1 attribute of the ;input= tag specifies that the input should be processed as a
file. 5or e'a&ple% when viewed in a browser% there will be a browse-button ne't to the input
field
!ote2 )llowing users to upload files is a big security ris(. ,nly per&it trusted users to perfor& file
uploads.
)reate 1he :#load Scri#t
The 1uploadJfile.php1 file contains the code for uploading a file:
;<php
if *GJ5#L7"O1file1PO1error1P = H0
M
echo 17rror: 1 . GJ5#L7"O1file1PO1error1P . 1;br /=1>
N
else
M
echo 14pload: 1 . GJ5#L7"O1file1PO1na&e1P . 1;br /=1>
echo 1Type: 1 . GJ5#L7"O1file1PO1type1P . 1;br /=1>
echo 1"iCe: 1 . *GJ5#L7"O1file1PO1siCe1P / EHQS0 . 1 Xb;br /=1>
echo 1"tored in: 1 . GJ5#L7"O1file1PO1t&pJna&e1P>
N
<=
By using the global PHP GJ5#L7" array you can upload files fro& a client co&puter to the re&ote
server.
The first para&eter is the for&8s input na&e and the second inde' can be either 1na&e1% 1type1%
1siCe1% 1t&pJna&e1 or 1error1. Li(e this:
GJ5#L7"O1file1PO1na&e1P - the na&e of the uploaded file
GJ5#L7"O1file1PO1type1P - the type of the uploaded file
GJ5#L7"O1file1PO1siCe1P - the siCe in bytes of the uploaded file
GJ5#L7"O1file1PO1t&pJna&e1P - the na&e of the te&porary copy of the file stored on the
server
GJ5#L7"O1file1PO1error1P - the error code resulting fro& the file upload
This is a very si&ple way of uploading files. 5or security reasons% you should add restrictions on
what the user is allowed to upload.
-estrictions on :#load
#n this script we add so&e restrictions to the file upload. The user &ay only upload .gif or .$peg files
and the file siCe &ust be under QH (b:
;<php
Gallowed7'ts A array*1$pg1% 1$peg1% 1gif1% 1png10>
Ge'tension A end*e'plode*1.1% GJ5#L7"O1file1PO1na&e1P00>
if ***GJ5#L7"O1file1PO1type1P AA 1i&age/gif10
WW *GJ5#L7"O1file1PO1type1P AA 1i&age/$peg10
WW *GJ5#L7"O1file1PO1type1P AA 1i&age/p$peg100
VV *GJ5#L7"O1file1PO1siCe1P ; QHHHH0
VV inJarray*Ge'tension% Gallowed7'ts00
M
if *GJ5#L7"O1file1PO1error1P = H0
M
echo 17rror: 1 . GJ5#L7"O1file1PO1error1P . 1;br /=1>
N
else
M
echo 14pload: 1 . GJ5#L7"O1file1PO1na&e1P . 1;br /=1>
echo 1Type: 1 . GJ5#L7"O1file1PO1type1P . 1;br /=1>
echo 1"iCe: 1 . *GJ5#L7"O1file1PO1siCe1P / EHQS0 . 1 Xb;br /=1>
echo 1"tored in: 1 . GJ5#L7"O1file1PO1t&pJna&e1P>
N
N
else
M
echo 1#nvalid file1>
N
<=
!ote2 5or #7 to recogniCe $pg files the type &ust be p$peg% for 5ire5o' it &ust be $peg.
Sa$in. the :#loaded File
The e'a&ples above create a te&porary copy of the uploaded files in the PHP te&p folder on the
server.
The te&porary copied files disappears when the script ends. To store the uploaded file we need to
copy it to a different location:
;<php
Gallowed7'ts A array*1$pg1% 1$peg1% 1gif1% 1png10>
Ge'tension A end*e'plode*1.1% GJ5#L7"O1file1PO1na&e1P00>
if ***GJ5#L7"O1file1PO1type1P AA 1i&age/gif10
WW *GJ5#L7"O1file1PO1type1P AA 1i&age/$peg10
WW *GJ5#L7"O1file1PO1type1P AA 1i&age/p$peg100
VV *GJ5#L7"O1file1PO1siCe1P ; QHHHH0
VV inJarray*Ge'tension% Gallowed7'ts00
M
if *GJ5#L7"O1file1PO1error1P = H0
M
echo 16eturn /ode: 1 . GJ5#L7"O1file1PO1error1P . 1;br /=1>
N
else
M
echo 14pload: 1 . GJ5#L7"O1file1PO1na&e1P . 1;br /=1>
echo 1Type: 1 . GJ5#L7"O1file1PO1type1P . 1;br /=1>
echo 1"iCe: 1 . *GJ5#L7"O1file1PO1siCe1P / EHQS0 . 1 Xb;br /=1>
echo 1Te&p file: 1 . GJ5#L7"O1file1PO1t&pJna&e1P . 1;br /=1>
if *fileJe'ists*1upload/1 . GJ5#L7"O1file1PO1na&e1P00
M
echo GJ5#L7"O1file1PO1na&e1P . 1 already e'ists. 1>
N
else
M
&oveJuploadedJfile*GJ5#L7"O1file1PO1t&pJna&e1P%
1upload/1 . GJ5#L7"O1file1PO1na&e1P0>
echo 1"tored in: 1 . 1upload/1 . GJ5#L7"O1file1PO1na&e1P>
N
N
N
else
M
echo 1#nvalid file1>
N
<=
The script above chec(s if the file already e'ists% if it does not% it copies the file to the specified
folder.
!ote2 This e'a&ple saves the file to a new folder called 1upload1
PHP )oo8ies
) coo(ie is often used to identify a user.
What is a )oo8ie?
) coo(ie is often used to identify a user. ) coo(ie is a s&all file that the server e&beds on the user8s
co&puter. 7ach ti&e the sa&e co&puter re:uests a page with a browser% it will send the coo(ie too.
3ith PHP% you can both create and retrieve coo(ie values.
How to )reate a )oo8ie?
The setcoo(ie*0 function is used to set a coo(ie.
!ote2 The setcoo(ie*0 function &ust appear B75,67 the ;ht&l= tag.
Syntax
setcoo(ie*na&e% value% e'pire% path% do&ain0>
Example 1
#n the e'a&ple below% we will create a coo(ie na&ed 1user1 and assign the value 1)le' Porter1 to it.
3e also specify that the coo(ie should e'pire after one hour:
;<php
setcoo(ie*1user1% 1)le' Porter1% ti&e*0D2BHH0>
<=
;ht&l=
.....
!ote2 The value of the coo(ie is auto&atically 46Lencoded when sending the coo(ie% and
auto&atically decoded when received *to prevent 46Lencoding% use setrawcoo(ie*0 instead0.
Example 2
Kou can also set the e'piration ti&e of the coo(ie in another way. #t &ay be easier than using
seconds.
;<php
Ge'pireAti&e*0DBH?BH?QS?2H>
setcoo(ie*1user1% 1)le' Porter1% Ge'pire0>
<=
;ht&l=
.....
#n the e'a&ple above the e'piration ti&e is set to a &onth *60 sec * 60 min * 24 hours * 0 days0.
How to -etrie$e a )oo8ie ,alue?
The PHP GJ/,,X#7 variable is used to retrieve a coo(ie value.
#n the e'a&ple below% we retrieve the value of the coo(ie na&ed 1user1 and display it on a page:
;<php
// Print a coo(ie
echo GJ/,,X#7O1user1P>
// ) way to view all coo(ies
printJr*GJ/,,X#70>
<=
#n the following e'a&ple we use the isset*0 function to find out if a coo(ie has been set:
;ht&l=
;body=
;<php
if *isset*GJ/,,X#7O1user1P00
echo 13elco&e 1 . GJ/,,X#7O1user1P . 1L;br /=1>
else
echo 13elco&e guestL;br /=1>
<=
;/body=
;/ht&l=
How to Delete a )oo8ie?
3hen deleting a coo(ie you should assure that the e'piration date is in the past.
.elete e'a&ple:
;<php
// set the e'piration date to one hour ago
setcoo(ie*1user1% 11% ti&e*0-2BHH0>
<=
What i5 a &rowser Does !41 Su##ort )oo8ies?
#f your application deals with browsers that do not support coo(ies% you will have to use other
&ethods to pass infor&ation fro& one page to another in your application. ,ne &ethod is to pass the
data through for&s *for&s and user input are described earlier in this tutorial0.
The for& below passes the user input to 1welco&e.php1 when the user clic(s on the 1"ub&it1
button:
;ht&l=
;body=
;for& actionA1welco&e.php1 &ethodA1post1=
Fa&e: ;input typeA1te't1 na&eA1na&e1 /=
)ge: ;input typeA1te't1 na&eA1age1 /=
;input typeA1sub&it1 /=
;/for&=
;/body=
;/ht&l=
6etrieve the values in the 1welco&e.php1 file li(e this:
;ht&l=
;body=
3elco&e ;<php echo GJP,"TO1na&e1P> <=.;br /=
Kou are ;<php echo GJP,"TO1age1P> <= years old.
;/body=
;/ht&l=
PHP Sessions
) PHP session variable is used to store infor&ation about% or change settings for a user session.
"ession variables hold infor&ation about one single user% and are available to all pages in one
application.
PHP Session ,aria"les
3hen you are wor(ing with an application% you open it% do so&e changes and then you close it. This
is &uch li(e a "ession. The co&puter (nows who you are. #t (nows when you start the application
and when you end. But on the internet there is one proble&: the web server does not (now who you
are and what you do because the HTTP address doesn8t &aintain state.
) PHP session solves this proble& by allowing you to store user infor&ation on the server for later
use *i.e. userna&e% shopping ite&s% etc0. However% session infor&ation is te&porary and will be
deleted after the user has left the website. #f you need a per&anent storage you &ay want to store the
data in a database.
"essions wor( by creating a uni:ue id *4#.0 for each visitor and store variables based on this 4#..
The 4#. is either stored in a coo(ie or is propagated in the 46L.
Startin. a PHP Session
Before you can store user infor&ation in your PHP session% you &ust first start up the session.
!ote2 The sessionJstart*0 function &ust appear B75,67 the ;ht&l= tag:
;<php sessionJstart*0> <=
;ht&l=
;body=
;/body=
;/ht&l=
The code above will register the user8s session with the server% allow you to start saving user
infor&ation% and assign a 4#. for that user8s session.
Storin. a Session ,aria"le
The correct way to store and retrieve session variables is to use the PHP GJ"7""#,F variable:
;<php
sessionJstart*0>
// store session data
GJ"7""#,FO8views8PAE>
<=
;ht&l=
;body=
;<php
//retrieve session data
echo 1PageviewsA1. GJ"7""#,FO8views8P>
<=
;/body=
;/ht&l=
,utput:
PageviewsAE
#n the e'a&ple below% we create a si&ple page-views counter. The isset*0 function chec(s if the
1views1 variable has already been set. #f 1views1 has been set% we can incre&ent our counter. #f
1views1 doesn8t e'ist% we create a 1views1 variable% and set it to E:
;<php
sessionJstart*0>
if*isset*GJ"7""#,FO8views8P00
GJ"7""#,FO8views8PAGJ"7""#,FO8views8PDE>
else
GJ"7""#,FO8views8PAE>
echo 1@iewsA1. GJ"7""#,FO8views8P>
<=
Destroyin. a Session
#f you wish to delete so&e session data% you can use the unset*0 or the sessionJdestroy*0 function.
The unset*0 function is used to free the specified session variable:
;<php
sessionJstart*0>
if*isset*GJ"7""#,FO8views8P00
unset*GJ"7""#,FO8views8P0>
<=
Kou can also co&pletely destroy the session by calling the sessionJdestroy*0 function:
;<php
sessionJdestroy*0>
<=
!ote2 sessionJdestroy*0 will reset your session and you will lose all your stored session data.
PHP Sendin. 69mails
PHP allows you to send e-&ails directly fro& a script.
1he PHP mail/0 Function
The PHP &ail*0 function is used to send e&ails fro& inside a script.
Synta%
&ail*to%sub$ect%&essage%headers%para&eters0
Parameter Descri#tion
to 6e:uired. "pecifies the receiver / receivers of the e&ail
sub$ect 6e:uired. "pecifies the sub$ect of the e&ail. !ote2 This para&eter cannot
contain any newline characters
&essage 6e:uired. .efines the &essage to be sent. 7ach line should be separated with a
L5 *Zn0. Lines should not e'ceed RH characters
headers ,ptional. "pecifies additional headers% li(e 5ro&% /c% and Bcc. The additional
headers should be separated with a /6L5 *ZrZn0
para&eters ,ptional. "pecifies an additional para&eter to the send&ail progra&
!ote2 5or the &ail functions to be available% PHP re:uires an installed and wor(ing e&ail syste&.
The progra& to be used is defined by the configuration settings in the php.ini file. 6ead &ore in our
PHP Mail reference.
PHP Sim#le 69Mail
The si&plest way to send an e&ail with PHP is to send a te't e&ail.
#n the e'a&ple below we first declare the variables *Gto% Gsub$ect% G&essage% Gfro&% Gheaders0% then
we use the variables in the &ail*0 function to send an e-&ail:
;<php
Gto A 1so&eone[e'a&ple.co&1>
Gsub$ect A 1Test &ail1>
G&essage A 1HelloL This is a si&ple e&ail &essage.1>
Gfro& A 1so&eonelse[e'a&ple.co&1>
Gheaders A 15ro&:1 . Gfro&>
&ail*Gto%Gsub$ect%G&essage%Gheaders0>
echo 1Mail "ent.1>
<=
PHP Mail Form
3ith PHP% you can create a feedbac(-for& on your website. The e'a&ple below sends a te't
&essage to a specified e-&ail address:
;ht&l=
;body=
;<php
if *isset*GJ67+47"TO8e&ail8P00
//if 1e&ail1 is filled out% send e&ail
M
//send e&ail
Ge&ail A GJ67+47"TO8e&ail8P >
Gsub$ect A GJ67+47"TO8sub$ect8P >
G&essage A GJ67+47"TO8&essage8P >
&ail*1so&eone[e'a&ple.co&1% Gsub$ect%
G&essage% 15ro&:1 . Ge&ail0>
echo 1Than( you for using our &ail for&1>
N
else
//if 1e&ail1 is not filled out% display the for&
M
echo 1;for& &ethodA8post8 actionA8&ailfor&.php8=
7&ail: ;input na&eA8e&ail8 typeA8te't8 /=;br /=
"ub$ect: ;input na&eA8sub$ect8 typeA8te't8 /=;br /=
Message:;br /=
;te'tarea na&eA8&essage8 rowsA8E98 colsA8SH8=
;/te'tarea=;br /=
;input typeA8sub&it8 /=
;/for&=1>
N
<=
;/body=
;/ht&l=
This is how the e'a&ple above wor(s:
5irst% chec( if the e&ail input field is filled out
#f it is not set *li(e when the page is first visited0> output the HTML for&
#f it is set *after the for& is filled out0> send the e&ail fro& the for&
3hen sub&it is pressed after the for& is filled out% the page reloads% sees that the e&ail input
is set% and sends the e&ail
!ote2 This is the si&plest way to send e-&ail% but it is not secure. #n the ne't chapter of this tutorial
you can read &ore about vulnerabilities in e-&ail scripts% and how to validate user input to &a(e it
&ore secure.
PHP Mail -e5erence
5or &ore infor&ation about the PHP &ail*0 function% visit our PHP Mail 6eference.
PHP Secure 69mails
There is a wea(ness in the PHP e-&ail script in the previous chapter.
PHP 69mail InAections
5irst% loo( at the PHP code fro& the previous chapter:
;ht&l=
;body=
;<php
if *isset*GJ67+47"TO8e&ail8P00
//if 1e&ail1 is filled out% send e&ail
M
//send e&ail
Ge&ail A GJ67+47"TO8e&ail8P >
Gsub$ect A GJ67+47"TO8sub$ect8P >
G&essage A GJ67+47"TO8&essage8P >
&ail*1so&eone[e'a&ple.co&1% 1"ub$ect: Gsub$ect1%
G&essage% 15ro&: Ge&ail1 0>
echo 1Than( you for using our &ail for&1>
N
else
//if 1e&ail1 is not filled out% display the for&
M
echo 1;for& &ethodA8post8 actionA8&ailfor&.php8=
7&ail: ;input na&eA8e&ail8 typeA8te't8 /=;br /=
"ub$ect: ;input na&eA8sub$ect8 typeA8te't8 /=;br /=
Message:;br /=
;te'tarea na&eA8&essage8 rowsA8E98 colsA8SH8=
;/te'tarea=;br /=
;input typeA8sub&it8 /=
;/for&=1>
N
<=
;/body=
;/ht&l=
The proble& with the code above is that unauthoriCed users can insert data into the &ail headers via
the input for&.
3hat happens if the user adds the following te't to the e&ail input field in the for&<
so&eone[e'a&ple.co&TH)/c:personQ[e'a&ple.co&
TH)Bcc:person2[e'a&ple.co&%person2[e'a&ple.co&%
anotherpersonS[e'a&ple.co&%person9[e'a&ple.co&
TH)BTo:personB[e'a&ple.co&
The &ail*0 function puts the te't above into the &ail headers as usual% and now the header has an
e'tra /c:% Bcc:% and To: field. 3hen the user clic(s the sub&it button% the e-&ail will be sent to all of
the addresses aboveL
PHP Sto##in. 69mail InAections
The best way to stop e-&ail in$ections is to validate the input.
The code below is the sa&e as in the previous chapter% but now we have added an input validator that
chec(s the e&ail field in the for&:
;ht&l=
;body=
;<php
function spa&chec(*Gfield0
M
//filterJvar*0 sanitiCes the e-&ail
//address using 5#LT76J")F#T#\7J7M)#L
GfieldAfilterJvar*Gfield% 5#LT76J")F#T#\7J7M)#L0>
//filterJvar*0 validates the e-&ail
//address using 5#LT76J@)L#.)T7J7M)#L
if*filterJvar*Gfield% 5#LT76J@)L#.)T7J7M)#L00
M
return T647>
N
else
M
return 5)L"7>
N
N
if *isset*GJ67+47"TO8e&ail8P00
M//if 1e&ail1 is filled out% proceed
//chec( if the e&ail address is invalid
G&ailchec( A spa&chec(*GJ67+47"TO8e&ail8P0>
if *G&ailchec(AA5)L"70
M
echo 1#nvalid input1>
N
else
M//send e&ail
Ge&ail A GJ67+47"TO8e&ail8P >
Gsub$ect A GJ67+47"TO8sub$ect8P >
G&essage A GJ67+47"TO8&essage8P >
&ail*1so&eone[e'a&ple.co&1% 1"ub$ect: Gsub$ect1%
G&essage% 15ro&: Ge&ail1 0>
echo 1Than( you for using our &ail for&1>
N
N
else
M//if 1e&ail1 is not filled out% display the for&
echo 1;for& &ethodA8post8 actionA8&ailfor&.php8=
7&ail: ;input na&eA8e&ail8 typeA8te't8 /=;br /=
"ub$ect: ;input na&eA8sub$ect8 typeA8te't8 /=;br /=
Message:;br /=
;te'tarea na&eA8&essage8 rowsA8E98 colsA8SH8=
;/te'tarea=;br /=
;input typeA8sub&it8 /=
;/for&=1>
N
<=
;/body=
;/ht&l=
#n the code above we use PHP filters to validate input:
The 5#LT76J")F#T#\7J7M)#L filter re&oves all illegal e-&ail characters fro& a string
The 5#LT76J@)L#.)T7J7M)#L filter validates value as an e-&ail address
Kou can read &ore about filters in our PHP 5ilter chapter.
PHP 6rror Handlin.
The default error handling in PHP is very si&ple. )n error &essage with filena&e% line nu&ber and a
&essage describing the error is sent to the browser.
PHP 6rror Handlin.
3hen creating scripts and web applications% error handling is an i&portant part. #f your code lac(s
error chec(ing code% your progra& &ay loo( very unprofessional and you &ay be open to security
ris(s.
This tutorial contains so&e of the &ost co&&on error chec(ing &ethods in PHP.
3e will show different error handling &ethods:
"i&ple 1die*01 state&ents
/usto& errors and error triggers
7rror reporting
&asic 6rror Handlin.2 :sin. the die/0 5unction
The first e'a&ple shows a si&ple script that opens a te't file:
;<php
GfileAfopen*1welco&e.t't1%1r10>
<=
#f the file does not e'ist you &ight get an error li(e this:
Warnin.: fopen*welco&e.t't0 Ofunction.fopenP: failed to open strea&:
Fo such file or directory in )2Bwe"5olderBtest7#h# on line C
To avoid that the user gets an error &essage li(e the one above% we test if the file e'ist before we try
to access it:
;<php
if*LfileJe'ists*1welco&e.t't100
M
die*15ile not found10>
N
else
M
GfileAfopen*1welco&e.t't1%1r10>
N
<=
Fow if the file does not e'ist you get an error li(e this:
5ile not found
The code above is &ore efficient than the earlier code% because it uses a si&ple error handling
&echanis& to stop the script after the error.
However% si&ply stopping the script is not always the right way to go. Let8s ta(e a loo( at alternative
PHP functions for handling errors.
)reatin. a )ustom 6rror Handler
/reating a custo& error handler is :uite si&ple. 3e si&ply create a special function that can be
called when an error occurs in PHP.
This function &ust be able to handle a &ini&u& of two para&eters *error level and error &essage0
but can accept up to five para&eters *optionally: file% line-nu&ber% and the error conte't0:
Synta%
errorJfunction*errorJlevel%errorJ&essage%
errorJfile%errorJline%errorJconte't0
Parameter Descri#tion
errorJlevel 6e:uired. "pecifies the error report level for the user-defined error. Must be a
value nu&ber. "ee table below for possible error report levels
errorJ&essage 6e:uired. "pecifies the error &essage for the user-defined error
errorJfile ,ptional. "pecifies the filena&e in which the error occurred
errorJline ,ptional. "pecifies the line nu&ber in which the error occurred
errorJconte't ,ptional. "pecifies an array containing every variable% and their values% in use
when the error occurred
6rror -e#ort le$els
These error report levels are the different types of error the user-defined error handler can be used
for:
,alue )onstant Descri#tion
Q 7J3)6F#F- Fon-fatal run-ti&e errors. 7'ecution of the script is not halted
U 7JF,T#/7 6un-ti&e notices. The script found so&ething that &ight be an
error% but could also happen when running a script nor&ally
Q9B 7J4"76J766,6 5atal user-generated error. This is li(e an 7J766,6 set by the
progra&&er using the PHP function triggerJerror*0
9EQ 7J4"76J3)6F#F- Fon-fatal user-generated warning. This is li(e an
7J3)6F#F- set by the progra&&er using the PHP function
triggerJerror*0
EHQS 7J4"76JF,T#/7 4ser-generated notice. This is li(e an 7JF,T#/7 set by the
progra&&er using the PHP function triggerJerror*0
SHIB 7J67/,@76)BL7J766,6 /atchable fatal error. This is li(e an 7J766,6 but can be
caught by a user defined handle *see also setJerrorJhandler*00
UEIE 7J)LL )ll errors and warnings *7J"T6#/T beca&e a part of 7J)LL
in PHP 9.S0
Fow lets create a function to handle errors:
function custo&7rror*Gerrno% Gerrstr0
M
echo 1;b=7rror:;/b= OGerrnoP Gerrstr;br /=1>
echo 17nding "cript1>
die*0>
N
The code above is a si&ple error handling function. 3hen it is triggered% it gets the error level and an
error &essage. #t then outputs the error level and &essage and ter&inates the script.
Fow that we have created an error handling function we need to decide when it should be triggered.
Set 6rror Handler
The default error handler for PHP is the built in error handler. 3e are going to &a(e the function
above the default error handler for the duration of the script.
#t is possible to change the error handler to apply for only so&e errors% that way the script can handle
different errors in different ways. However% in this e'a&ple we are going to use our custo& error
handler for all errors:
setJerrorJhandler*1custo&7rror10>
"ince we want our custo& function to handle all errors% the setJerrorJhandler*0 only needed one
para&eter% a second para&eter could be added to specify an error level.
6%am#le
Testing the error handler by trying to output variable that does not e'ist:
;<php
//error handler function
function custo&7rror*Gerrno% Gerrstr0
M
echo 1;b=7rror:;/b= OGerrnoP Gerrstr1>
N
//set error handler
setJerrorJhandler*1custo&7rror10>
//trigger error
echo*Gtest0>
<=
The output of the code above should be so&ething li(e this:
6rror2 OUP 4ndefined variable: test
1ri..er an 6rror
#n a script where users can input data it is useful to trigger errors when an illegal input occurs. #n
PHP% this is done by the triggerJerror*0 function.
6%am#le
#n this e'a&ple an error occurs if the 1test1 variable is bigger than 1E1:
;<php
GtestAQ>
if *Gtest=E0
M
triggerJerror*1@alue &ust be E or below10>
N
<=
The output of the code above should be so&ething li(e this:
!otice: @alue &ust be E or below
in )2Bwe"5olderBtest7#h# on line D
)n error can be triggered anywhere you wish in a script% and by adding a second para&eter% you can
specify what error level is triggered.
Possible error types:
7J4"76J766,6 - 5atal user-generated run-ti&e error. 7rrors that can not be recovered
fro&. 7'ecution of the script is halted
7J4"76J3)6F#F- - Fon-fatal user-generated run-ti&e warning. 7'ecution of the script is
not halted
7J4"76JF,T#/7 - .efault. 4ser-generated run-ti&e notice. The script found so&ething
that &ight be an error% but could also happen when running a script nor&ally
6%am#le
#n this e'a&ple an 7J4"76J3)6F#F- occurs if the 1test1 variable is bigger than 1E1. #f an
7J4"76J3)6F#F- occurs we will use our custo& error handler and end the script:
;<php
//error handler function
function custo&7rror*Gerrno% Gerrstr0
M
echo 1;b=7rror:;/b= OGerrnoP Gerrstr;br /=1>
echo 17nding "cript1>
die*0>
N
//set error handler
setJerrorJhandler*1custo&7rror1%7J4"76J3)6F#F-0>
//trigger error
GtestAQ>
if *Gtest=E0
M
triggerJerror*1@alue &ust be E or below1%7J4"76J3)6F#F-0>
N
<=
The output of the code above should be so&ething li(e this:
6rror2 O9EQP @alue &ust be E or below
7nding "cript
Fow that we have learned to create our own errors and how to trigger the&% lets ta(e a loo( at error
logging.
6rror Lo..in.
By default% PHP sends an error log to the server8s logging syste& or a file% depending on how the
errorJlog configuration is set in the php.ini file. By using the errorJlog*0 function you can send error
logs to a specified file or a re&ote destination.
"ending error &essages to yourself by e-&ail can be a good way of getting notified of specific
errors.
Send an 6rror Messa.e "y 69Mail
#n the e'a&ple below we will send an e-&ail with an error &essage and end the script% if a specific
error occurs:
;<php
//error handler function
function custo&7rror*Gerrno% Gerrstr0
M
echo 1;b=7rror:;/b= OGerrnoP Gerrstr;br /=1>
echo 13eb&aster has been notified1>
errorJlog*17rror: OGerrnoP Gerrstr1%E%
1so&eone[e'a&ple.co&1%15ro&: web&aster[e'a&ple.co&10>
N
//set error handler
setJerrorJhandler*1custo&7rror1%7J4"76J3)6F#F-0>
//trigger error
GtestAQ>
if *Gtest=E0
M
triggerJerror*1@alue &ust be E or below1%7J4"76J3)6F#F-0>
N
<=
The output of the code above should be so&ething li(e this:
6rror2 O9EQP @alue &ust be E or below
3eb&aster has been notified
)nd the &ail received fro& the code above loo(s li(e this:
7rror: O9EQP @alue &ust be E or below
This should not be used with all errors. 6egular errors should be logged on the server using the
default PHP logging syste&.
PHP 6%ce#tion Handlin.
7'ceptions are used to change the nor&al flow of a script if a specified error occurs.
What is an 6%ce#tion
3ith PHP 9 ca&e a new ob$ect oriented way of dealing with errors.
7'ception handling is used to change the nor&al flow of the code e'ecution if a specified error
*e'ceptional0 condition occurs. This condition is called an e'ception.
This is what nor&ally happens when an e'ception is triggered:
The current code state is saved
The code e'ecution will switch to a predefined *custo&0 e'ception handler function
.epending on the situation% the handler &ay then resu&e the e'ecution fro& the saved code
state% ter&inate the script e'ecution or continue the script fro& a different location in the
code
3e will show different error handling &ethods:
Basic use of 7'ceptions
/reating a custo& e'ception handler
Multiple e'ceptions
6e-throwing an e'ception
"etting a top level e'ception handler
!ote2 7'ceptions should only be used with error conditions% and should not be used to $u&p to
another place in the code at a specified point.
&asic :se o5 6%ce#tions
3hen an e'ception is thrown% the code following it will not be e'ecuted% and PHP will try to find the
&atching 1catch1 bloc(.
#f an e'ception is not caught% a fatal error will be issued with an 14ncaught 7'ception1 &essage.
Lets try to throw an e'ception without catching it:
;<php
//create function with an e'ception
function chec(Fu&*Gnu&ber0
M
if*Gnu&ber=E0
M
throw new 7'ception*1@alue &ust be E or below10>
N
return true>
N
//trigger e'ception
chec(Fu&*Q0>
<=
The code above will get an error li(e this:
Fatal error: 4ncaught e'ception 87'ception8
with &essage 8@alue &ust be E or below8 in /:ZwebfolderZtest.php:B
"tac( trace: ]H /:ZwebfolderZtest.php*EQ0:
chec(Fu&*QU0 ]E M&ainN thrown in )2Bwe"5olderBtest7#h# on line D
1ry@ throw and catch
To avoid the error fro& the e'a&ple above% we need to create the proper code to handle an
e'ception.
Proper e'ception code should include:
E. Try - ) function using an e'ception should be in a 1try1 bloc(. #f the e'ception does not
trigger% the code will continue as nor&al. However if the e'ception triggers% an e'ception is
1thrown1
Q. Throw - This is how you trigger an e'ception. 7ach 1throw1 &ust have at least one 1catch1
2. /atch - ) 1catch1 bloc( retrieves an e'ception and creates an ob$ect containing the e'ception
infor&ation
Lets try to trigger an e'ception with valid code:
;<php
//create function with an e'ception
function chec(Fu&*Gnu&ber0
M
if*Gnu&ber=E0
M
throw new 7'ception*1@alue &ust be E or below10>
N
return true>
N
//trigger e'ception in a 1try1 bloc(
try
M
chec(Fu&*Q0>
//#f the e'ception is thrown% this te't will not be shown
echo 8#f you see this% the nu&ber is E or below8>
N
//catch e'ception
catch*7'ception Ge0
M
echo 8Message: 8 .Ge-=getMessage*0>
N
<=
The code above will get an error li(e this:
Message: @alue &ust be E or below
6%am#le e%#lained2
The code above throws an e'ception and catches it:
E. The chec(Fu&*0 function is created. #t chec(s if a nu&ber is greater than E. #f it is% an
e'ception is thrown
Q. The chec(Fu&*0 function is called in a 1try1 bloc(
2. The e'ception within the chec(Fu&*0 function is thrown
S. The 1catch1 bloc( retrives the e'ception and creates an ob$ect *Ge0 containing the e'ception
infor&ation
9. The error &essage fro& the e'ception is echoed by calling Ge-=getMessage*0 fro& the
e'ception ob$ect
However% one way to get around the 1every throw &ust have a catch1 rule is to set a top level
e'ception handler to handle errors that slip through.
)reatin. a )ustom 6%ce#tion )lass
/reating a custo& e'ception handler is :uite si&ple. 3e si&ply create a special class with functions
that can be called when an e'ception occurs in PHP. The class &ust be an e'tension of the e'ception
class.
The custo& e'ception class inherits the properties fro& PHP8s e'ception class and you can add
custo& functions to it.
Lets create an e'ception class:
;<php
class custo&7'ception e'tends 7'ception
M
public function errorMessage*0
M
//error &essage
GerrorMsg A 87rror on line 8.Gthis-=getLine*0.8 in 8.Gthis-=get5ile*0
.8: ;b=8.Gthis-=getMessage*0.8;/b= is not a valid 7-Mail address8>
return GerrorMsg>
N
N
Ge&ail A 1so&eone[e'a&ple...co&1>
try
M
//chec( if
if*filterJvar*Ge&ail% 5#LT76J@)L#.)T7J7M)#L0 AAA 5)L"70
M
//throw e'ception if e&ail is not valid
throw new custo&7'ception*Ge&ail0>
N
N
catch *custo&7'ception Ge0
M
//display custo& &essage
echo Ge-=errorMessage*0>
N
<=
The new class is a copy of the old e'ception class with an addition of the errorMessage*0 function.
"ince it is a copy of the old class% and it inherits the properties and &ethods fro& the old class% we
can use the e'ception class &ethods li(e getLine*0 and get5ile*0 and getMessage*0.
6%am#le e%#lained2
The code above throws an e'ception and catches it with a custo& e'ception class:
E. The custo&7'ception*0 class is created as an e'tension of the old e'ception class. This way it
inherits all &ethods and properties fro& the old e'ception class
Q. The errorMessage*0 function is created. This function returns an error &essage if an e-&ail
address is invalid
2. The Ge&ail variable is set to a string that is not a valid e-&ail address
S. The 1try1 bloc( is e'ecuted and an e'ception is thrown since the e-&ail address is invalid
9. The 1catch1 bloc( catches the e'ception and displays the error &essage
Multi#le 6%ce#tions
#t is possible for a script to use &ultiple e'ceptions to chec( for &ultiple conditions.
#t is possible to use several if..else bloc(s% a switch% or nest &ultiple e'ceptions. These e'ceptions
can use different e'ception classes and return different error &essages:
;<php
class custo&7'ception e'tends 7'ception
M
public function errorMessage*0
M
//error &essage
GerrorMsg A 87rror on line 8.Gthis-=getLine*0.8 in 8.Gthis-=get5ile*0
.8: ;b=8.Gthis-=getMessage*0.8;/b= is not a valid 7-Mail address8>
return GerrorMsg>
N
N
Ge&ail A 1so&eone[e'a&ple.co&1>
try
M
//chec( if
if*filterJvar*Ge&ail% 5#LT76J@)L#.)T7J7M)#L0 AAA 5)L"70
M
//throw e'ception if e&ail is not valid
throw new custo&7'ception*Ge&ail0>
N
//chec( for 1e'a&ple1 in &ail address
if*strpos*Ge&ail% 1e'a&ple10 LAA 5)L"70
M
throw new 7'ception*1Ge&ail is an e'a&ple e-&ail10>
N
N
catch *custo&7'ception Ge0
M
echo Ge-=errorMessage*0>
N
catch*7'ception Ge0
M
echo Ge-=getMessage*0>
N
<=
6%am#le e%#lained2
The code above tests two conditions and throws an e'ception if any of the conditions are not &et:
E. The custo&7'ception*0 class is created as an e'tension of the old e'ception class. This way it
inherits all &ethods and properties fro& the old e'ception class
Q. The errorMessage*0 function is created. This function returns an error &essage if an e-&ail
address is invalid
2. The Ge&ail variable is set to a string that is a valid e-&ail address% but contains the string
1e'a&ple1
S. The 1try1 bloc( is e'ecuted and an e'ception is not thrown on the first condition
9. The second condition triggers an e'ception since the e-&ail contains the string 1e'a&ple1
B. The 1catch1 bloc( catches the e'ception and displays the correct error &essage
#f the e'ception thrown were of the class custo&7'ception and there were no custo&7'ception
catch% only the base e'ception catch% the e'ception would be handled there.
-e9throwin. 6%ce#tions
"o&eti&es% when an e'ception is thrown% you &ay wish to handle it differently than the standard
way. #t is possible to throw an e'ception a second ti&e within a 1catch1 bloc(.
) script should hide syste& errors fro& users. "yste& errors &ay be i&portant for the coder% but is
of no interest to the user. To &a(e things easier for the user you can re-throw the e'ception with a
user friendly &essage:
;<php
class custo&7'ception e'tends 7'ception
M
public function errorMessage*0
M
//error &essage
GerrorMsg A Gthis-=getMessage*0.8 is not a valid 7-Mail address.8>
return GerrorMsg>
N
N
Ge&ail A 1so&eone[e'a&ple.co&1>
try
M
try
M
//chec( for 1e'a&ple1 in &ail address
if*strpos*Ge&ail% 1e'a&ple10 LAA 5)L"70
M
//throw e'ception if e&ail is not valid
throw new 7'ception*Ge&ail0>
N
N
catch*7'ception Ge0
M
//re-throw e'ception
throw new custo&7'ception*Ge&ail0>
N
N
catch *custo&7'ception Ge0
M
//display custo& &essage
echo Ge-=errorMessage*0>
N
<=
6%am#le e%#lained2
The code above tests if the e&ail-address contains the string 1e'a&ple1 in it% if it does% the e'ception
is re-thrown:
E. The custo&7'ception*0 class is created as an e'tension of the old e'ception class. This way it
inherits all &ethods and properties fro& the old e'ception class
Q. The errorMessage*0 function is created. This function returns an error &essage if an e-&ail
address is invalid
2. The Ge&ail variable is set to a string that is a valid e-&ail address% but contains the string
1e'a&ple1
S. The 1try1 bloc( contains another 1try1 bloc( to &a(e it possible to re-throw the e'ception
9. The e'ception is triggered since the e-&ail contains the string 1e'a&ple1
B. The 1catch1 bloc( catches the e'ception and re-throws a 1custo&7'ception1
R. The 1custo&7'ception1 is caught and displays an error &essage
#f the e'ception is not caught in its current 1try1 bloc(% it will search for a catch bloc( on 1higher
levels1.
Set a 1o# Le$el 6%ce#tion Handler
The setJe'ceptionJhandler*0 function sets a user-defined function to handle all uncaught e'ceptions.
;<php
function &y7'ception*Ge'ception0
M
echo 1;b=7'ception:;/b= 1 % Ge'ception-=getMessage*0>
N
setJe'ceptionJhandler*8&y7'ception80>
throw new 7'ception*84ncaught 7'ception occurred80>
<=
The output of the code above should be so&ething li(e this:
6%ce#tion2 4ncaught 7'ception occurred
#n the code above there was no 1catch1 bloc(. #nstead% the top level e'ception handler triggered. This
function should be used to catch uncaught e'ceptions.
-ules 5or e%ce#tions
/ode &ay be surrounded in a try bloc(% to help catch potential e'ceptions
7ach try bloc( or 1throw1 &ust have at least one corresponding catch bloc(
Multiple catch bloc(s can be used to catch different classes of e'ceptions
7'ceptions can be thrown *or re-thrown0 in a catch bloc( within a try bloc(
) si&ple rule: #f you throw so&ething% you have to catch it.
PHP Filter
PHP filters are used to validate and filter data co&ing fro& insecure sources% li(e user input.
What is a PHP Filter?
) PHP filter is used to validate and filter data co&ing fro& insecure sources.
To test% validate and filter user input or custo& data is an i&portant part of any web application.
The PHP filter e'tension is designed to &a(e data filtering easier and :uic(er.
Why use a Filter?
)l&ost all web applications depend on e'ternal input. 4sually this co&es fro& a user or another
application *li(e a web service0. By using filters you can be sure your application gets the correct
input type.
You should always 5ilter all e%ternal dataE
#nput filtering is one of the &ost i&portant application security issues.
3hat is e'ternal data<
#nput data fro& a for&
/oo(ies
3eb services data
"erver variables
.atabase :uery results
Functions and Filters
To filter a variable% use one of the following filter functions:
filterJvar*0 - 5ilters a single variable with a specified filter
filterJvarJarray*0 - 5ilter several variables with the sa&e or different filters
filterJinput - -et one input variable and filter it
filterJinputJarray - -et several input variables and filter the& with the sa&e or different
filters
#n the e'a&ple below% we validate an integer using the filterJvar*0 function:
;<php
Gint A EQ2>
if*LfilterJvar*Gint% 5#LT76J@)L#.)T7J#FT00
M
echo*1#nteger is not valid10>
N
else
M
echo*1#nteger is valid10>
N
<=
The code above uses the 15#LT76J@)L#.)T7J#FT1 filter to filter the variable. "ince the integer is
valid% the output of the code above will be: 1#nteger is valid1.
#f we try with a variable that is not an integer *li(e 1EQ2abc10% the output will be: 1#nteger is not
valid1.
5or a co&plete list of functions and filters% visit our PHP 5ilter 6eference.
,alidatin. and SanitiFin.
There are two (inds of filters:
@alidating filters:
)re used to validate user input
"trict for&at rules *li(e 46L or 7-Mail validating0
6eturns the e'pected type on success or 5)L"7 on failure
"anitiCing filters:
)re used to allow or disallow specified characters in a string
Fo data for&at rules
)lways return the string
4#tions and Fla.s
,ptions and flags are used to add additional filtering options to the specified filters.
.ifferent filters have different options and flags.
#n the e'a&ple below% we validate an integer using the filterJvar*0 and the 1&inJrange1 and
1&a'Jrange1 options:
;<php
GvarA2HH>
GintJoptions A array*
1options1A=array
*
1&inJrange1A=H%
1&a'Jrange1A=Q9B
0
0>
if*LfilterJvar*Gvar% 5#LT76J@)L#.)T7J#FT% GintJoptions00
M
echo*1#nteger is not valid10>
N
else
M
echo*1#nteger is valid10>
N
<=
Li(e the code above% options &ust be put in an associative array with the na&e 1options1. #f a flag is
used it does not need to be in an array.
"ince the integer is 12HH1 it is not in the specified range% and the output of the code above will be:
1#nteger is not valid1.
5or a co&plete list of functions and filters% visit our PHP 5ilter 6eference. /hec( each filter to see
what options and flags are available.
,alidate In#ut
Let8s try validating input fro& a for&.
The first thing we need to do is to confir& that the input data we are loo(ing for e'ists.
Then we filter the input data using the filterJinput*0 function.
#n the e'a&ple below% the input variable 1e&ail1 is sent to the PHP page:
;<php
if*LfilterJhasJvar*#FP4TJ-7T% 1e&ail100
M
echo*1#nput type does not e'ist10>
N
else
M
if *LfilterJinput*#FP4TJ-7T% 1e&ail1% 5#LT76J@)L#.)T7J7M)#L00
M
echo 17-Mail is not valid1>
N
else
M
echo 17-Mail is valid1>
N
N
<=
6%am#le 6%#lained
The e'a&ple above has an input *e&ail0 sent to it using the 1-7T1 &ethod:
E. /hec( if an 1e&ail1 input variable of the 1-7T1 type e'ist
Q. #f the input variable e'ists% chec( if it is a valid e-&ail address
SanitiFe In#ut
Let8s try cleaning up an 46L sent fro& a for&.
5irst we confir& that the input data we are loo(ing for e'ists.
Then we sanitiCe the input data using the filterJinput*0 function.
#n the e'a&ple below% the input variable 1url1 is sent to the PHP page:
;<php
if*LfilterJhasJvar*#FP4TJP,"T% 1url100
M
echo*1#nput type does not e'ist10>
N
else
M
Gurl A filterJinput*#FP4TJP,"T%
1url1% 5#LT76J")F#T#\7J46L0>
N
<=
6%am#le 6%#lained
The e'a&ple above has an input *url0 sent to it using the 1P,"T1 &ethod:
E. /hec( if the 1url1 input of the 1P,"T1 type e'ists
Q. #f the input variable e'ists% sanitiCe *ta(e away invalid characters0 and store it in the Gurl
variable
#f the input variable is a string li(e this 1http://www.32YY"ch^^ools.co&/1% the Gurl variable after
the sanitiCing will loo( li(e this:
http://www.32"chools.co&/
Filter Multi#le In#uts
) for& al&ost always consist of &ore than one input field. To avoid calling the filterJvar or
filterJinput functions over and over% we can use the filterJvarJarray or the filterJinputJarray
functions.
#n this e'a&ple we use the filterJinputJarray*0 function to filter three -7T variables. The received
-7T variables is a na&e% an age and an e-&ail address:
;<php
Gfilters A array
*
1na&e1 A= array
*
1filter1A=5#LT76J")F#T#\7J"T6#F-
0%
1age1 A= array
*
1filter1A=5#LT76J@)L#.)T7J#FT%
1options1A=array
*
1&inJrange1A=E%
1&a'Jrange1A=EQH
0
0%
1e&ail1A= 5#LT76J@)L#.)T7J7M)#L
0>
Gresult A filterJinputJarray*#FP4TJ-7T% Gfilters0>
if *LGresultO1age1P0
M
echo*1)ge &ust be a nu&ber between E and EQH.;br /=10>
N
elseif*LGresultO1e&ail1P0
M
echo*17-Mail is not valid.;br /=10>
N
else
M
echo*14ser input is valid10>
N
<=
6%am#le 6%#lained
The e'a&ple above has three inputs *na&e% age and e&ail0 sent to it using the 1-7T1 &ethod:
E. "et an array containing the na&e of input variables and the filters used on the specified input
variables
Q. /all the filterJinputJarray*0 function with the -7T input variables and the array we $ust set
2. /hec( the 1age1 and 1e&ail1 variables in the Gresult variable for invalid inputs. *#f any of the
input variables are invalid% that input variable will be 5)L"7 after the filterJinputJarray*0
function0
The second para&eter of the filterJinputJarray*0 function can be an array or a single filter #..#f the
para&eter is a single filter #. all values in the input array are filtered by the specified filter.#f the
para&eter is an array it &ust follow these rules:
Must be an associative array containing an input variable as an array (ey *li(e the 1age1 input
variable0
The array value &ust be a filter #. or an array specifying the filter% flags and options
:sin. Filter )all"ac8
#t is possible to call a user defined function and use it as a filter using the 5#LT76J/)LLB)/X
filter. This way% we have full control of the data filtering.
Kou can create your own user defined function or use an e'isting PHP function
The function you wish to use to filter is specified the sa&e way as an option is specified. #n an
associative array with the na&e 1options1
#n the e'a&ple below% we use a user created function to convert all 1J1 to whitespaces:
;<php
function convert"pace*Gstring0
M
return strJreplace*1J1% 1 1% Gstring0>
N
Gstring A 1PeterJisJaJgreatJguyL1>
echo filterJvar*Gstring% 5#LT76J/)LLB)/X%
array*1options1A=1convert"pace100>
<=
The result fro& the code above should loo( li(e this:
Peter is a great guyL
6%am#le 6%#lained
The e'a&ple above converts all 1J1 to whitespaces:
E. /reate a function to replace 1J1 to whitespaces
Q. /all the filterJvar*0 function with the 5#LT76J/)LLB)/X filter and an array containing
our function
PHP DA1A&AS6
PHP MySQL Introduction
My"+L is the &ost popular open-source database syste&.
What is MySQL?
My"+L is a database.
The data in My"+L is stored in database ob$ects called tables.
) table is a collection of related data entries and it consists of colu&ns and rows.
.atabases are useful when storing infor&ation categorically. ) co&pany &ay have a database with
the following tables: 17&ployees1% 1Products1% 1/usto&ers1 and 1,rders1.
Data"ase 1a"les
) database &ost often contains one or &ore tables. 7ach table is identified by a na&e *e.g.
1/usto&ers1 or 1,rders10. Tables contain records *rows0 with data.
Below is an e'a&ple of a table called 1Persons1:
Last!ame First!ame Address )ity
Hansen ,la Ti&oteivn EH "andnes
"vendson Tove Borgvn Q2 "andnes
Pettersen Xari "torgt QH "tavanger
The table above contains three records *one for each person0 and four colu&ns *LastFa&e%
5irstFa&e% )ddress% and /ity0.
Queries
) :uery is a :uestion or a re:uest.
3ith My"+L% we can :uery a database for specific infor&ation and have a recordset returned.
Loo( at the following :uery:
"7L7/T LastFa&e 56,M Persons
The :uery above selects all the data in the 1LastFa&e1 colu&n fro& the 1Persons1 table% and will
return a recordset li(e this:
Last!ame
Hansen
"vendson
Pettersen
Download MySQL Data"ase
#f you don8t have a PHP server with a My"+L .atabase% you can download My"+L for free here:
http://www.&ys:l.co&/downloads/
Facts A"out MySQL Data"ase
,ne great thing about My"+L is that it can be scaled down to support e&bedded database
applications. Perhaps it is because of this reputation that &any people believe that My"+L can only
handle s&all to &ediu&-siCed syste&s.
The truth is that My"+L is the de-facto standard database for web sites that support huge volu&es of
both data and end users *li(e 5riendster% Kahoo% -oogle0.
Loo( at http://www.&ys:l.co&/custo&ers/ for an overview of co&panies using My"+L.
PHP MySQL )onnect to a Data"ase
_ Previous
Fe't /hapter `
The free My"+L database is very often used with PHP.
)reate a )onnection to a MySQL Data"ase
Before you can access data in a database% you &ust create a connection to the database.
#n PHP% this is done with the &ys:lJconnect*0 function.
Syntax
&ys:lJconnect*serverna&e%userna&e%password0>
Parameter Descri#tion
serverna&e ,ptional. "pecifies the server to connect to. .efault value is 1localhost:22HB1
userna&e ,ptional. "pecifies the userna&e to log in with. .efault value is the na&e of the
user that owns the server process
password ,ptional. "pecifies the password to log in with. .efault is 11
!ote2 There are &ore available para&eters% but the ones listed above are the &ost i&portant. @isit
our full PHP My"+L 6eference for &ore details.
Example
#n the following e'a&ple we store the connection in a variable *Gcon0 for later use in the script. The
1die1 part will be e'ecuted if the connection fails:
;<php
Gcon A &ys:lJconnect*1localhost1%1peter1%1abcEQ210>
if *LGcon0
M
die*8/ould not connect: 8 . &ys:lJerror*00>
N
// so&e code
<=
)losin. a )onnection
The connection will be closed auto&atically when the script ends. To close the connection before%
use the &ys:lJclose*0 function:
;<php
Gcon A &ys:lJconnect*1localhost1%1peter1%1abcEQ210>
if *LGcon0
M
die*8/ould not connect: 8 . &ys:lJerror*00>
N
// so&e code
&ys:lJclose*Gcon0>
<=
PHP MySQL )reate Data"ase and 1a"les
) database holds one or &ultiple tables.
)reate a Data"ase
The /67)T7 .)T)B)"7 state&ent is used to create a database in My"+L.
Syntax
/67)T7 .)T)B)"7 databaseJna&e
To learn &ore about "+L% please visit our "+L tutorial.
To get PHP to e'ecute the state&ent above we &ust use the &ys:lJ:uery*0 function. This function is
used to send a :uery or co&&and to a My"+L connection.
Example
The following e'a&ple creates a database called 1&yJdb1:
;<php
Gcon A &ys:lJconnect*1localhost1%1peter1%1abcEQ210>
if *LGcon0
M
die*8/ould not connect: 8 . &ys:lJerror*00>
N
if *&ys:lJ:uery*1/67)T7 .)T)B)"7 &yJdb1%Gcon00
M
echo 1.atabase created1>
N
else
M
echo 17rror creating database: 1 . &ys:lJerror*0>
N
&ys:lJclose*Gcon0>
<=
)reate a 1a"le
The /67)T7 T)BL7 state&ent is used to create a table in My"+L.
Syntax
/67)T7 T)BL7 tableJna&e
*
colu&nJna&eE dataJtype%
colu&nJna&eQ dataJtype%
colu&nJna&e2 dataJtype%
!!!!
0
To learn &ore about "+L% please visit our "+L tutorial.
3e &ust add the /67)T7 T)BL7 state&ent to the &ys:lJ:uery*0 function to e'ecute the
co&&and.
Example
The following e'a&ple creates a table na&ed 1Persons1% with three colu&ns. The colu&n na&es will
be 15irstFa&e1% 1LastFa&e1 and 1)ge1:
;<php
Gcon A &ys:lJconnect*1localhost1%1peter1%1abcEQ210>
if *LGcon0
M
die*8/ould not connect: 8 . &ys:lJerror*00>
N
// /reate database
if *&ys:lJ:uery*1/67)T7 .)T)B)"7 &yJdb1%Gcon00
M
echo 1.atabase created1>
N
else
M
echo 17rror creating database: 1 . &ys:lJerror*0>
N
// /reate table
&ys:lJselectJdb*1&yJdb1% Gcon0>
Gs:l A 1/67)T7 T)BL7 Persons
*
5irstFa&e varchar*E90%
LastFa&e varchar*E90%
)ge int
01>
// 7'ecute :uery
&ys:lJ:uery*Gs:l%Gcon0>
&ys:lJclose*Gcon0>
<=
Im#ortant2 ) database &ust be selected before a table can be created. The database is selected with
the &ys:lJselectJdb*0 function.
!ote2 3hen you create a database field of type varchar% you &ust specify the &a'i&u& length of the
field% e.g. varchar*E90.
The data type specifies what type of data the colu&n can hold. 5or a co&plete reference of all the
data types available in My"+L% go to our co&plete .ata Types reference.
Primary Keys and Auto Increment Fields
7ach table should have a pri&ary (ey field.
) pri&ary (ey is used to uni:uely identify the rows in a table. 7ach pri&ary (ey value &ust be
uni:ue within the table. 5urther&ore% the pri&ary (ey field cannot be null because the database
engine re:uires a value to locate the record.
The following e'a&ple sets the person#. field as the pri&ary (ey field. The pri&ary (ey field is
often an #. nu&ber% and is often used with the )4T,J#F/67M7FT setting. )4T,J#F/67M7FT
auto&atically increases the value of the field by E each ti&e a new record is added. To ensure that
the pri&ary (ey field cannot be null% we &ust add the F,T F4LL setting to the field.
Example
Gs:l A 1/67)T7 T)BL7 Persons
*
person#. int F,T F4LL )4T,J#F/67M7FT%
P6#M)6K X7K*person#.0%
5irstFa&e varchar*E90%
LastFa&e varchar*E90%
)ge int
01>
&ys:lJ:uery*Gs:l%Gcon0>
PHP MySQL Insert Into
The #F"76T #FT, state&ent is used to insert new records in a table.
Insert Data Into a Data"ase 1a"le
The #F"76T #FT, state&ent is used to add new records to a database table.
Syntax
#t is possible to write the #F"76T #FT, state&ent in two for&s.
The first for& doesn8t specify the colu&n na&es where the data will be inserted% only their values:
#F"76T #FT, tableJna&e
@)L47" *valueE% valueQ% value2%...0
The second for& specifies both the colu&n na&es and the values to be inserted:
#F"76T #FT, tableJna&e *colu&nE% colu&nQ% colu&n2%...0
@)L47" *valueE% valueQ% value2%...0
To learn &ore about "+L% please visit our "+L tutorial.
To get PHP to e'ecute the state&ents above we &ust use the &ys:lJ:uery*0 function. This function
is used to send a :uery or co&&and to a My"+L connection.
Example
#n the previous chapter we created a table na&ed 1Persons1% with three colu&ns> 15irstna&e1%
1Lastna&e1 and 1)ge1. 3e will use the sa&e table in this e'a&ple. The following e'a&ple adds two
new records to the 1Persons1 table:
;<php
Gcon A &ys:lJconnect*1localhost1%1peter1%1abcEQ210>
if *LGcon0
M
die*8/ould not connect: 8 . &ys:lJerror*00>
N
&ys:lJselectJdb*1&yJdb1% Gcon0>
&ys:lJ:uery*1#F"76T #FT, Persons *5irstFa&e% LastFa&e% )ge0
@)L47" *8Peter8% 8-riffin8%29010>
&ys:lJ:uery*1#F"76T #FT, Persons *5irstFa&e% LastFa&e% )ge0
@)L47" *8-lenn8% 8+uag&ire8%22010>
&ys:lJclose*Gcon0>
<=
Insert Data From a Form Into a Data"ase
Fow we will create an HTML for& that can be used to add new records to the 1Persons1 table.
Here is the HTML for&:
;ht&l=
;body=
;for& actionA1insert.php1 &ethodA1post1=
5irstna&e: ;input typeA1te't1 na&eA1firstna&e1 /=
Lastna&e: ;input typeA1te't1 na&eA1lastna&e1 /=
)ge: ;input typeA1te't1 na&eA1age1 /=
;input typeA1sub&it1 /=
;/for&=
;/body=
;/ht&l=
3hen a user clic(s the sub&it button in the HTML for& in the e'a&ple above% the for& data is sent
to 1insert.php1.
The 1insert.php1 file connects to a database% and retrieves the values fro& the for& with the PHP
GJP,"T variables.
Then% the &ys:lJ:uery*0 function e'ecutes the #F"76T #FT, state&ent% and a new record will be
added to the 1Persons1 table.
Here is the 1insert.php1 page:
;<php
Gcon A &ys:lJconnect*1localhost1%1peter1%1abcEQ210>
if *LGcon0
M
die*8/ould not connect: 8 . &ys:lJerror*00>
N
&ys:lJselectJdb*1&yJdb1% Gcon0>
Gs:lA1#F"76T #FT, Persons *5irstFa&e% LastFa&e% )ge0
@)L47"
*8GJP,"TOfirstna&eP8%8GJP,"TOlastna&eP8%8GJP,"TOageP801>
if *L&ys:lJ:uery*Gs:l%Gcon00
M
die*87rror: 8 . &ys:lJerror*00>
N
echo 1E record added1>
&ys:lJclose*Gcon0>
<=
PHP MySQL Select
The "7L7/T state&ent is used to select data fro& a database.
Select Data From a Data"ase 1a"le
The "7L7/T state&ent is used to select data fro& a database.
Syntax
"7L7/T colu&nJna&e*s0
56,M tableJna&e
To learn &ore about "+L% please visit our "+L tutorial.
To get PHP to e'ecute the state&ent above we &ust use the &ys:lJ:uery*0 function. This function is
used to send a :uery or co&&and to a My"+L connection.
Example
The following e'a&ple selects all the data stored in the 1Persons1 table *The ? character selects all
the data in the table0:
;<php
Gcon A &ys:lJconnect*1localhost1%1peter1%1abcEQ210>
if *LGcon0
M
die*8/ould not connect: 8 . &ys:lJerror*00>
N
&ys:lJselectJdb*1&yJdb1% Gcon0>
Gresult A &ys:lJ:uery*1"7L7/T ? 56,M Persons10>
while*Grow A &ys:lJfetchJarray*Gresult00
M
echo GrowO85irstFa&e8P . 1 1 . GrowO8LastFa&e8P>
echo 1;br /=1>
N
&ys:lJclose*Gcon0>
<=
The e'a&ple above stores the data returned by the &ys:lJ:uery*0 function in the Gresult variable.
Fe't% we use the &ys:lJfetchJarray*0 function to return the first row fro& the recordset as an array.
7ach call to &ys:lJfetchJarray*0 returns the ne't row in the recordset. The while loop loops through
all the records in the recordset. To print the value of each row% we use the PHP Grow variable
*GrowO85irstFa&e8P and GrowO8LastFa&e8P0.
The output of the code above will be:
Peter -riffin
-lenn +uag&ire
Dis#lay the -esult in an H1ML 1a"le
The following e'a&ple selects the sa&e data as the e'a&ple above% but will display the data in an
HTML table:
;<php
Gcon A &ys:lJconnect*1localhost1%1peter1%1abcEQ210>
if *LGcon0
M
die*8/ould not connect: 8 . &ys:lJerror*00>
N
&ys:lJselectJdb*1&yJdb1% Gcon0>
Gresult A &ys:lJ:uery*1"7L7/T ? 56,M Persons10>
echo >;table borderA8E8=
'tr=
;th=5irstna&e;/th=
;th=Lastna&e;/th=
;/tr=1>
while*Grow A &ys:lJfetchJarray*Gresult00
M
echo 1;tr=1>
echo 1;td=1 . GrowO85irstFa&e8P . 1;/td=1>
echo 1;td=1 . GrowO8LastFa&e8P . 1;/td=1>
echo 1;/tr=1>
N
echo 1;/table=1>
&ys:lJclose*Gcon0>
<=
The output of the code above will be:
Firstname Lastname
-lenn +uag&ire
Peter -riffin
PHP MySQL 1he Where )lause
The 3H767 clause is used to filter records.
1he WH6-6 clause
The 3H767 clause is used to e'tract only those records that fulfill a specified criterion.
Syntax
"7L7/T colu&nJna&e*s0
56,M tableJna&e
3H767 colu&nJna&e operator value
To learn &ore about "+L% please visit our "+L tutorial.
To get PHP to e'ecute the state&ent above we &ust use the &ys:lJ:uery*0 function. This function is
used to send a :uery or co&&and to a My"+L connection.
Example
The following e'a&ple selects all rows fro& the 1Persons1 table where 15irstFa&eA8Peter81:
;<php
Gcon A &ys:lJconnect*1localhost1%1peter1%1abcEQ210>
if *LGcon0
M
die*8/ould not connect: 8 . &ys:lJerror*00>
N
&ys:lJselectJdb*1&yJdb1% Gcon0>
Gresult A &ys:lJ:uery*1"7L7/T ? 56,M Persons
3H767 5irstFa&eA8Peter810>
while*Grow A &ys:lJfetchJarray*Gresult00
M
echo GrowO85irstFa&e8P . 1 1 . GrowO8LastFa&e8P>
echo 1;br /=1>
N
<=
The output of the code above will be:
Peter -riffin
PHP MySQL 4rder &y Keyword
The ,6.76 BK (eyword is used to sort the data in a recordset.
1he 4-D6- &Y Keyword
The ,6.76 BK (eyword is used to sort the data in a recordset.
The ,6.76 BK (eyword sort the records in ascending order by default.
#f you want to sort the records in a descending order% you can use the .7"/ (eyword.
Syntax
"7L7/T colu&nJna&e*s0
56,M tableJna&e
,6.76 BK colu&nJna&e*s0 )"/W.7"/
To learn &ore about "+L% please visit our "+L tutorial.
Example
The following e'a&ple selects all the data stored in the 1Persons1 table% and sorts the result by the
1)ge1 colu&n:
;<php
Gcon A &ys:lJconnect*1localhost1%1peter1%1abcEQ210>
if *LGcon0
M
die*8/ould not connect: 8 . &ys:lJerror*00>
N
&ys:lJselectJdb*1&yJdb1% Gcon0>
Gresult A &ys:lJ:uery*1"7L7/T ? 56,M Persons ,6.76 BK age10>
while*Grow A &ys:lJfetchJarray*Gresult00
M
echo GrowO85irstFa&e8P>
echo 1 1 . GrowO8LastFa&e8P>
echo 1 1 . GrowO8)ge8P>
echo 1;br /=1>
N
&ys:lJclose*Gcon0>
<=
The output of the code above will be:
-lenn +uag&ire 22
Peter -riffin 29
4rder "y 1wo )olumns
#t is also possible to order by &ore than one colu&n. 3hen ordering by &ore than one colu&n% the
second colu&n is only used if the values in the first colu&n are e:ual:
"7L7/T colu&nJna&e*s0
56,M tableJna&e
,6.76 BK colu&nE% colu&nQ
PHP MySQL :#date
The 4P.)T7 state&ent is used to &odify data in a table.
:#date Data In a Data"ase
The 4P.)T7 state&ent is used to update e'isting records in a table.
Syntax
4P.)T7 tableJna&e
"7T colu&nEAvalue% colu&nQAvalueQ%...
3H767 so&eJcolu&nAso&eJvalue
!ote2 Fotice the 3H767 clause in the 4P.)T7 synta'. The 3H767 clause specifies which
record or records that should be updated. #f you o&it the 3H767 clause% all records will be
updatedL
To learn &ore about "+L% please visit our "+L tutorial.
To get PHP to e'ecute the state&ent above we &ust use the &ys:lJ:uery*0 function. This function is
used to send a :uery or co&&and to a My"+L connection.
Example
7arlier in the tutorial we created a table na&ed 1Persons1. Here is how it loo(s:
First!ame Last!ame A.e
Peter -riffin 29
-lenn +uag&ire 22
The following e'a&ple updates so&e data in the 1Persons1 table:
;<php
Gcon A &ys:lJconnect*1localhost1%1peter1%1abcEQ210>
if *LGcon0
M
die*8/ould not connect: 8 . &ys:lJerror*00>
N
&ys:lJselectJdb*1&yJdb1% Gcon0>
&ys:lJ:uery*14P.)T7 Persons "7T )geA2B
3H767 5irstFa&eA8Peter8 )F. LastFa&eA8-riffin810>
&ys:lJclose*Gcon0>
<=
)fter the update% the 1Persons1 table will loo( li(e this:
First!ame Last!ame A.e
Peter -riffin 2B
-lenn +uag&ire 22
PHP MySQL Delete
The .7L7T7 state&ent is used to delete records in a table.
Delete Data In a Data"ase
The .7L7T7 56,M state&ent is used to delete records fro& a database table.
Syntax
.7L7T7 56,M tableJna&e
3H767 so&eJcolu&n A so&eJvalue
!ote2 Fotice the 3H767 clause in the .7L7T7 synta'. The 3H767 clause specifies which record
or records that should be deleted. #f you o&it the 3H767 clause% all records will be deletedL
To learn &ore about "+L% please visit our "+L tutorial.
To get PHP to e'ecute the state&ent above we &ust use the &ys:lJ:uery*0 function. This function is
used to send a :uery or co&&and to a My"+L connection.
Example
Loo( at the following 1Persons1 table:
First!ame Last!ame A.e
Peter -riffin 29
-lenn +uag&ire 22
The following e'a&ple deletes all the records in the 1Persons1 table where LastFa&eA8-riffin8:
;<php
Gcon A &ys:lJconnect*1localhost1%1peter1%1abcEQ210>
if *LGcon0
M
die*8/ould not connect: 8 . &ys:lJerror*00>
N
&ys:lJselectJdb*1&yJdb1% Gcon0>
&ys:lJ:uery*1.7L7T7 56,M Persons 3H767 LastFa&eA8-riffin810>
&ys:lJclose*Gcon0>
<=
)fter the deletion% the table will loo( li(e this:
First!ame Last!ame A.e
-lenn +uag&ire 22
PHP Data"ase 4D&)
,.B/ is an )pplication Progra&&ing #nterface *)P#0 that allows you to connect to a data source
*e.g. an M" )ccess database0.
)reate an 4D&) )onnection
3ith an ,.B/ connection% you can connect to any database% on any co&puter in your networ(% as
long as an ,.B/ connection is available.
Here is how to create an ,.B/ connection to a M" )ccess .atabase:
E. ,pen the Administrati$e 1ools icon in your /ontrol Panel.
Q. .ouble-clic( on the Data Sources /4D&)0 icon inside.
2. /hoose the System DS! tab.
S. /lic( on Add in the "yste& ."F tab.
9. "elect the Microso5t Access Dri$er. /lic( Finish7
B. #n the ne't screen% clic( Select to locate the database.
R. -ive the database a Data Source !ame /DS!0.
U. /lic( 4K.
Fote that this configuration has to be done on the co&puter where your web site is located. #f you
are running #nternet #nfor&ation "erver *##"0 on your own co&puter% the instructions above will
wor(% but if your web site is located on a re&ote server% you have to have physical access to that
server% or as( your web host to to set up a ."F for you to use.
)onnectin. to an 4D&)
The odbcJconnect*0 function is used to connect to an ,.B/ data source. The function ta(es four
para&eters: the data source na&e% userna&e% password% and an optional cursor type.
The odbcJe'ec*0 function is used to e'ecute an "+L state&ent.
Example
The following e'a&ple creates a connection to a ."F called northwind% with no userna&e and no
password. #t then creates an "+L and e'ecutes it:
GconnAodbcJconnect*8northwind8%88%880>
Gs:lA1"7L7/T ? 56,M custo&ers1>
GrsAodbcJe'ec*Gconn%Gs:l0>
-etrie$in. -ecords
The odbcJfetchJrow*0 function is used to return records fro& the result-set. This function returns
true if it is able to return rows% otherwise false.
The function ta(es two para&eters: the ,.B/ result identifier and an optional row nu&ber:
odbcJfetchJrow*Grs0
-etrie$in. Fields 5rom a -ecord
The odbcJresult*0 function is used to read fields fro& a record. This function ta(es two para&eters:
the ,.B/ result identifier and a field nu&ber or na&e.
The code line below returns the value of the first field fro& the record:
Gco&pna&eAodbcJresult*Grs%E0>
The code line below returns the value of a field called 1/o&panyFa&e1:
Gco&pna&eAodbcJresult*Grs%1/o&panyFa&e10>
)losin. an 4D&) )onnection
The odbcJclose*0 function is used to close an ,.B/ connection.
odbcJclose*Gconn0>
An 4D&) 6%am#le
The following e'a&ple shows how to first create a database connection% then a result-set% and then
display the data in an HTML table.
;ht&l=
;body=
;<php
GconnAodbcJconnect*8northwind8%88%880>
if *LGconn0
Me'it*1/onnection 5ailed: 1 . Gconn0>N
Gs:lA1"7L7/T ? 56,M custo&ers1>
GrsAodbcJe'ec*Gconn%Gs:l0>
if *LGrs0
Me'it*17rror in "+L10>N
echo 1;table=;tr=1>
echo 1;th=/o&panyna&e;/th=1>
echo 1;th=/ontactna&e;/th=;/tr=1>
while *odbcJfetchJrow*Grs00
M
Gco&pna&eAodbcJresult*Grs%1/o&panyFa&e10>
Gconna&eAodbcJresult*Grs%1/ontactFa&e10>
echo 1;tr=;td=Gco&pna&e;/td=1>
echo 1;td=Gconna&e;/td=;/tr=1>
N
odbcJclose*Gconn0>
echo 1;/table=1>
<=
;/body=
;/ht&l=
PHP GML
PHP GML 6%#at Parser
The built-in 7'pat parser &a(es it possible to process ML docu&ents in PHP.
What is GML?
ML is used to describe data and to focus on what data is. )n ML file describes the structure of
the data.
#n ML% no tags are predefined. Kou &ust define your own tags.
#f you want to learn &ore about ML% please visit our ML tutorial.
What is 6%#at?
To read and update - create and &anipulate - an ML docu&ent% you will need an ML parser.
There are two basic types of ML parsers:
Tree-based parser: This parser transfor&s an ML docu&ent into a tree structure. #t analyCes
the whole docu&ent% and provides access to the tree ele&ents. e.g. the .ocu&ent ,b$ect
Model *.,M0
7vent-based parser: @iews an ML docu&ent as a series of events. 3hen a specific event
occurs% it calls a function to handle it
The 7'pat parser is an event-based parser.
7vent-based parsers focus on the content of the ML docu&ents% not their structure. Because of this%
event-based parsers can access data faster than tree-based parsers.
Loo( at the following ML fraction:
;fro&=!ani;/fro&=
)n event-based parser reports the ML above as a series of three events:
"tart ele&ent: fro&
"tart /.)T) section% value: !ani
/lose ele&ent: fro&
The ML e'a&ple above contains well-for&ed ML. However% the e'a&ple is not valid ML%
because there is no .ocu&ent Type .efinition *.T.0 associated with it.
However% this &a(es no difference when using the 7'pat parser. 7'pat is a non-validating parser%
and ignores any .T.s.
)s an event-based% non-validating ML parser% 7'pat is fast and s&all% and a perfect &atch for PHP
web applications.
!ote2 ML docu&ents &ust be well-for&ed or 7'pat will generate an error.
Installation
The ML 7'pat parser functions are part of the PHP core. There is no installation needed to use
these functions.
An GML File
The ML file below will be used in our e'a&ple:
;<'&l versionA1E.H1 encodingA1#",-UU9I-E1<=
;note=
;to=Tove;/to=
;fro&=!ani;/fro&=
;heading=6e&inder;/heading=
;body=.on8t forget &e this wee(endL;/body=
;/note=
InitialiFin. the GML Parser
3e want to initialiCe the ML parser in PHP% define so&e handlers for different ML events% and
then parse the ML file.
Example
;<php
//#nitialiCe the ML parser
GparserA'&lJparserJcreate*0>
//5unction to use at the start of an ele&ent
function start*Gparser%Gele&entJna&e%Gele&entJattrs0
M
switch*Gele&entJna&e0
M
case 1F,T71:
echo 1-- Fote --;br /=1>
brea(>
case 1T,1:
echo 1To: 1>
brea(>
case 156,M1:
echo 15ro&: 1>
brea(>
case 1H7).#F-1:
echo 1Heading: 1>
brea(>
case 1B,.K1:
echo 1Message: 1>
N
N
//5unction to use at the end of an ele&ent
function stop*Gparser%Gele&entJna&e0
M
echo 1;br /=1>
N
//5unction to use when finding character data
function char*Gparser%Gdata0
M
echo Gdata>
N
//"pecify ele&ent handler
'&lJsetJele&entJhandler*Gparser%1start1%1stop10>
//"pecify data handler
'&lJsetJcharacterJdataJhandler*Gparser%1char10>
//,pen ML file
GfpAfopen*1test.'&l1%1r10>
//6ead data
while *GdataAfread*Gfp%SHIB00
M
'&lJparse*Gparser%Gdata%feof*Gfp00 or
die *sprintf*1ML 7rror: Ts at line Td1%
'&lJerrorJstring*'&lJgetJerrorJcode*Gparser00%
'&lJgetJcurrentJlineJnu&ber*Gparser000>
N
//5ree the ML parser
'&lJparserJfree*Gparser0>
<=
The output of the code above will be:
-- Fote --
To: Tove
5ro&: !ani
Heading: 6e&inder
Message: .on8t forget &e this wee(endL
How it wor(s:
E. #nitialiCe the ML parser with the '&lJparserJcreate*0 function
Q. /reate functions to use with the different event handlers
2. )dd the '&lJsetJele&entJhandler*0 function to specify which function will be e'ecuted
when the parser encounters the opening and closing tags
S. )dd the '&lJsetJcharacterJdataJhandler*0 function to specify which function will e'ecute
when the parser encounters character data
9. Parse the file 1test.'&l1 with the '&lJparse*0 function
B. #n case of an error% add '&lJerrorJstring*0 function to convert an ML error to a te'tual
description
R. /all the '&lJparserJfree*0 function to release the &e&ory allocated with the
'&lJparserJcreate*0 function
More PHP 6%#at Parser
5or &ore infor&ation about the PHP 7'pat functions% visit our PHP ML Parser 6eference.
PHP GML D4M
The built-in .,M parser &a(es it possible to process ML docu&ents in PHP.
What is D4M?
The 32/ .,M provides a standard set of ob$ects for HTML and ML docu&ents% and a standard
interface for accessing and &anipulating the&.
The 32/ .,M is separated into different parts */ore% ML% and HTML0 and different levels
*.,M Level E/Q/20:
? /ore .,M - defines a standard set of ob$ects for any structured docu&ent
? ML .,M - defines a standard set of ob$ects for ML docu&ents
? HTML .,M - defines a standard set of ob$ects for HTML docu&ents
#f you want to learn &ore about the ML .,M% please visit our ML .,M tutorial.
GML Parsin.
To read and update - create and &anipulate - an ML docu&ent% you will need an ML parser.
There are two basic types of ML parsers:
Tree-based parser: This parser transfor&s an ML docu&ent into a tree structure. #t analyCes
the whole docu&ent% and provides access to the tree ele&ents
7vent-based parser: @iews an ML docu&ent as a series of events. 3hen a specific event
occurs% it calls a function to handle it
The .,M parser is an tree-based parser.
Loo( at the following ML docu&ent fraction:
;<'&l versionA1E.H1 encodingA1#",-UU9I-E1<=
;fro&=!ani;/fro&=
The ML .,M sees the ML above as a tree structure:
Level E: ML .ocu&ent
Level Q: 6oot ele&ent: ;fro&=
Level 2: Te't ele&ent: 1!ani1
Installation
The .,M ML parser functions are part of the PHP core. There is no installation needed to use
these functions.
An GML File
The ML file below will be used in our e'a&ple:
;<'&l versionA1E.H1 encodingA1#",-UU9I-E1<=
;note=
;to=Tove;/to=
;fro&=!ani;/fro&=
;heading=6e&inder;/heading=
;body=.on8t forget &e this wee(endL;/body=
;/note=
Load and 4ut#ut GML
3e want to initialiCe the ML parser% load the '&l% and output it:
Example
;<php
G'&l.oc A new .,M.ocu&ent*0>
G'&l.oc-=load*1note.'&l10>
print G'&l.oc-=saveML*0>
<=
The output of the code above will be:
Tove !ani 6e&inder .on8t forget &e this wee(endL
#f you select 1@iew source1 in the browser window% you will see the following HTML:
;<'&l versionA1E.H1 encodingA1#",-UU9I-E1<=
;note=
;to=Tove;/to=
;fro&=!ani;/fro&=
;heading=6e&inder;/heading=
;body=.on8t forget &e this wee(endL;/body=
;/note=
The e'a&ple above creates a .,M.ocu&ent-,b$ect and loads the ML fro& 1note.'&l1 into it.
Then the saveML*0 function puts the internal ML docu&ent into a string% so we can output it.
Loo#in. throu.h GML
3e want to initialiCe the ML parser% load the ML% and loop through all ele&ents of the ;note=
ele&ent:
Example
;<php
G'&l.oc A new .,M.ocu&ent*0>
G'&l.oc-=load*1note.'&l10>
G' A G'&l.oc-=docu&ent7le&ent>
foreach *G'-=childFodes )" Gite&0
M
print Gite&-=nodeFa&e . 1 A 1 . Gite&-=node@alue . 1;br /=1>
N
<=
The output of the code above will be:
]te't A
to A Tove
]te't A
fro& A !ani
]te't A
heading A 6e&inder
]te't A
body A .on8t forget &e this wee(endL
]te't A
#n the e'a&ple above you see that there are e&pty te't nodes between each ele&ent.
3hen ML generates% it often contains white-spaces between the nodes. The ML .,M parser
treats these as ordinary ele&ents% and if you are not aware of the&% they so&eti&es cause proble&s.
#f you want to learn &ore about the ML .,M% please visit our ML .,M tutorial.
PHP Sim#leGML
"i&pleML handles the &ost co&&on ML tas(s and leaves the rest for other e'tensions.
What is Sim#leGML?
"i&pleML is new in PHP 9. #t is an easy way of getting an ele&ent8s attributes and te't% if you
(now the ML docu&ent8s layout.
/o&pared to .,M or the 7'pat parser% "i&pleML $ust ta(es a few lines of code to read te't data
fro& an ele&ent.
"i&pleML converts the ML docu&ent into an ob$ect% li(e this:
7le&ents - )re converted to single attributes of the "i&pleML7le&ent ob$ect. 3hen there8s
&ore than one ele&ent on one level% they8re placed inside an array
)ttributes - )re accessed using associative arrays% where an inde' corresponds to the
attribute na&e
7le&ent .ata - Te't data fro& ele&ents are converted to strings. #f an ele&ent has &ore than
one te't node% they will be arranged in the order they are found
"i&pleML is fast and easy to use when perfor&ing basic tas(s li(e:
6eading ML files
7'tracting data fro& ML strings
7diting te't nodes or attributes
However% when dealing with advanced ML% li(e na&espaces% you are better off using the 7'pat
parser or the ML .,M.
Installation
)s of PHP 9.H% the "i&pleML functions are part of the PHP core. There is no installation needed to
use these functions.
:sin. Sim#leGML
Below is an ML file:
;<'&l versionA1E.H1 encodingA1#",-UU9I-E1<=
;note=
;to=Tove;/to=
;fro&=!ani;/fro&=
;heading=6e&inder;/heading=
;body=.on8t forget &e this wee(endL;/body=
;/note=
3e want to output the ele&ent na&es and data fro& the ML file above.
Here8s what to do:
E. Load the ML file
Q. -et the na&e of the first ele&ent
2. /reate a loop that will trigger on each child node% using the children*0 function
S. ,utput the ele&ent na&e and data for each child node
6%am#le
;<php
G'&l A si&ple'&lJloadJfile*1test.'&l10>
echo G'&l-=getFa&e*0 . 1;br /=1>
foreach*G'&l-=children*0 as Gchild0
M
echo Gchild-=getFa&e*0 . 1: 1 . Gchild . 1;br /=1>
N
<=
The output of the code above will be:
note
to: Tove
fro&: !ani
heading: 6e&inder
body: .on8t forget &e this wee(endL
More PHP Sim#leGML
5or &ore infor&ation about the PHP "i&pleML functions% visit our PHP "i&pleML 6eference.
PHP and AHAG
AHAG Introduction
)!) is about updating parts of a web page% without reloading the whole page.
What is AHAG?
)!) A )synchronous !ava"cript and ML.
)!) is a techni:ue for creating fast and dyna&ic web pages.
)!) allows web pages to be updated asynchronously by e'changing s&all a&ounts of data with
the server behind the scenes. This &eans that it is possible to update parts of a web page% without
reloading the whole page.
/lassic web pages% *which do not use )!)0 &ust reload the entire page if the content should
change.
7'a&ples of applications using )!): -oogle Maps% -&ail% Koutube% and 5aceboo( tabs.
How AHAG Wor8s
AHAG is &ased on Internet Standards
)!) is based on internet standards% and uses a co&bination of:
MLHttp6e:uest ob$ect *to e'change data asynchronously with a server0
!ava"cript/.,M *to display/interact with the infor&ation0
/"" *to style the data0
ML *often used as the for&at for transferring data0
)!) applications are browser- and platfor&-independentL
3oo.le Su..est
)!) was &ade popular in QHH9 by -oogle% with -oogle "uggest.
-oogle "uggest is using )!) to create a very dyna&ic web interface: 3hen you start typing in
-oogle8s search bo'% a !ava"cript sends the letters off to a server and the server returns a list of
suggestions.
Start :sin. AHAG 1oday
#n our PHP tutorial% we will de&onstrate how )!) can update parts of a web page% without
reloading the whole page. The server script will be written in PHP.
#f you want to learn &ore about )!)% visit our )!) tutorial.
PHP 9 AHAG and PHP
)!) is used to create &ore interactive applications.
AHAG PHP 6%am#le
The following e'a&ple will de&onstrate how a web page can co&&unicate with a web server while
a user type characters in an input field:
6%am#le
Start ty#in. a name in the in#ut 5ield "elow2
5irst na&e:
"uggestions:
6%am#le 6%#lained 9 1he H1ML Pa.e
3hen a user types a character in the input field above% the function 1showHint*01 is e'ecuted. The
function is triggered by the 1on(eyup1 event:
;ht&l=
;head=
;script typeA1te't/$avascript1=
function showHint*str0
M
if *str.lengthAAH0
M
docu&ent.get7le&entBy#d*1t'tHint10.innerHTMLA11>
return>
N
if *window.MLHttp6e:uest0
M// code for #7RD% 5irefo'% /hro&e% ,pera% "afari
'&lhttpAnew MLHttp6e:uest*0>
N
else
M// code for #7B% #79
'&lhttpAnew )ctive,b$ect*1Microsoft.MLHTTP10>
N
'&lhttp.onreadystatechangeAfunction*0
M
if *'&lhttp.ready"tateAAS VV '&lhttp.statusAAQHH0
M
docu&ent.get7le&entBy#d*1t'tHint10.innerHTMLA'&lhttp.responseTe't>
N
N
'&lhttp.open*1-7T1%1gethint.php<:A1Dstr%true0>
'&lhttp.send*0>
N
;/script=
;/head=
;body=
;p=;b="tart typing a na&e in the input field below:;/b=;/p=
;for&=
5irst na&e: ;input typeA1te't1 on(eyupA1showHint*this.value01 siCeA1QH1 /=
;/for&=
;p="uggestions: ;span idA1t'tHint1=;/span=;/p=
;/body=
;/ht&l=
"ource code e'planation:
#f the input field is e&pty *str.lengthAAH0% the function clears the content of the t'tHint placeholder
and e'its the function.
#f the input field is not e&pty% the showHint*0 function e'ecutes the following:
/reate an MLHttp6e:uest ob$ect
/reate the function to be e'ecuted when the server response is ready
"end the re:uest off to a file on the server
Fotice that a para&eter *:0 is added to the 46L *with the content of the input field0
1he PHP File
The page on the server called by the !ava"cript above is a PHP file called 1gethint.php1.
The source code in 1gethint.php1 chec(s an array of na&es% and returns the corresponding na&e*s0 to
the browser:
;<php
// 5ill up array with na&es
GaOPA1)nna1>
GaOPA1Brittany1>
GaOPA1/inderella1>
GaOPA1.iana1>
GaOPA17va1>
GaOPA15iona1>
GaOPA1-unda1>
GaOPA1Hege1>
GaOPA1#nga1>
GaOPA1!ohanna1>
GaOPA1Xitty1>
GaOPA1Linda1>
GaOPA1Fina1>
GaOPA1,phelia1>
GaOPA1Petunia1>
GaOPA1)&anda1>
GaOPA16a:uel1>
GaOPA1/indy1>
GaOPA1.oris1>
GaOPA17ve1>
GaOPA17vita1>
GaOPA1"unniva1>
GaOPA1Tove1>
GaOPA14nni1>
GaOPA1@iolet1>
GaOPA1LiCa1>
GaOPA17liCabeth1>
GaOPA17llen1>
GaOPA13enche1>
GaOPA1@ic(y1>
//get the : para&eter fro& 46L
G:AGJ-7TO1:1P>
//loo(up all hints fro& array if length of :=H
if *strlen*G:0 = H0
M
GhintA11>
for*GiAH> Gi;count*Ga0> GiDD0
M
if *strtolower*G:0AAstrtolower*substr*GaOGiP%H%strlen*G:0000
M
if *GhintAA110
M
GhintAGaOGiP>
N
else
M
GhintAGhint.1 % 1.GaOGiP>
N
N
N
N
// "et output to 1no suggestion1 if no hint were found
// or to the correct values
if *Ghint AA 110
M
GresponseA1no suggestion1>
N
else
M
GresponseAGhint>
N
//output the response
echo Gresponse>
<=
7'planation: #f there is any te't sent fro& the !ava"cript *strlen*G:0 = H0% the following happens:
E. 5ind a na&e &atching the characters sent fro& the !ava"cript
Q. #f no &atch were found% set the response string to 1no suggestion1
2. #f one or &ore &atching na&es were found% set the response string to all these na&es
S. The response is sent to the 1t'tHint1 placeholder
PHP 9 AHAG and MySQL
)!) can be used for interactive co&&unication with a database.
AHAG Data"ase 6%am#le
The following e'a&ple will de&onstrate how a web page can fetch infor&ation fro& a database with
)!):
6%am#le
Person info will be listed here...
6%am#le 6%#lained 9 1he MySQL Data"ase
The database table we use in the e'a&ple above loo(s li(e this:
id First!ame Last!ame A.e Hometown Ho"
E Peter -riffin SE +uahog Brewery
Q Lois -riffin SH Fewport Piano Teacher
2 !oseph "wanson 2I +uahog Police ,fficer
S -lenn +uag&ire SE +uahog Pilot
6%am#le 6%#lained 9 1he H1ML Pa.e
3hen a user selects a user in the dropdown list above% a function called 1show4ser*01 is e'ecuted.
The function is triggered by the 1onchange1 event:
;ht&l=
;head=
;script typeA1te't/$avascript1=
function show4ser*str0
M
if *strAA110
M
docu&ent.get7le&entBy#d*1t'tHint10.innerHTMLA11>
return>
N
if *window.MLHttp6e:uest0
M// code for #7RD% 5irefo'% /hro&e% ,pera% "afari
'&lhttpAnew MLHttp6e:uest*0>
N
else
M// code for #7B% #79
'&lhttpAnew )ctive,b$ect*1Microsoft.MLHTTP10>
N
'&lhttp.onreadystatechangeAfunction*0
M
if *'&lhttp.ready"tateAAS VV '&lhttp.statusAAQHH0
M
docu&ent.get7le&entBy#d*1t'tHint10.innerHTMLA'&lhttp.responseTe't>
N
N
'&lhttp.open*1-7T1%1getuser.php<:A1Dstr%true0>
'&lhttp.send*0>
N
;/script=
;/head=
;body=
;for&=
;select na&eA1users1 onchangeA1show4ser*this.value01=
;option valueA11="elect a person:;/option=
;option valueA1E1=Peter -riffin;/option=
;option valueA1Q1=Lois -riffin;/option=
;option valueA121=-lenn +uag&ire;/option=
;option valueA1S1=!oseph "wanson;/option=
;/select=
;/for&=
;br /=
;div idA1t'tHint1=;b=Person info will be listed here.;/b=;/div=
;/body=
;/ht&l=
The show4ser*0 function does the following:
/hec( if a person is selected
/reate an MLHttp6e:uest ob$ect
/reate the function to be e'ecuted when the server response is ready
"end the re:uest off to a file on the server
Fotice that a para&eter *:0 is added to the 46L *with the content of the dropdown list0
1he PHP File
The page on the server called by the !ava"cript above is a PHP file called 1getuser.php1.
The source code in 1getuser.php1 runs a :uery against a My"+L database% and returns the result in
an HTML table:
;<php
G:AGJ-7TO1:1P>
Gcon A &ys:lJconnect*8localhost8% 8peter8% 8abcEQ280>
if *LGcon0
M
die*8/ould not connect: 8 . &ys:lJerror*00>
N
&ys:lJselectJdb*1a$a'Jde&o1% Gcon0>
Gs:lA1"7L7/T ? 56,M user 3H767 id A 81.G:.181>
Gresult A &ys:lJ:uery*Gs:l0>
echo 1;table borderA8E8=
;tr=
;th=5irstna&e;/th=
;th=Lastna&e;/th=
;th=)ge;/th=
;th=Ho&etown;/th=
;th=!ob;/th=
;/tr=1>
while*Grow A &ys:lJfetchJarray*Gresult00
M
echo 1;tr=1>
echo 1;td=1 . GrowO85irstFa&e8P . 1;/td=1>
echo 1;td=1 . GrowO8LastFa&e8P . 1;/td=1>
echo 1;td=1 . GrowO8)ge8P . 1;/td=1>
echo 1;td=1 . GrowO8Ho&etown8P . 1;/td=1>
echo 1;td=1 . GrowO8!ob8P . 1;/td=1>
echo 1;/tr=1>
N
echo 1;/table=1>
&ys:lJclose*Gcon0>
<=
7'planation: 3hen the :uery is sent fro& the !ava"cript to the PHP file% the following happens:
E. PHP opens a connection to a My"+L server
Q. The correct person is found
2. )n HTML table is created% filled with data% and sent bac( to the 1t'tHint1 placeholder
PHP 6%am#le 9 AHAG and GML
)!) can be used for interactive co&&unication with an ML file.
AHAG GML 6%am#le
The following e'a&ple will de&onstrate how a web page can fetch infor&ation fro& an ML file
with )!):
6%am#le
/. info will be listed here...
6%am#le 6%#lained 9 1he H1ML Pa.e
3hen a user selects a /. in the dropdown list above% a function called 1show/.*01 is e'ecuted. The
function is triggered by the 1onchange1 event:
;ht&l=
;head=
;script typeA1te't/$avascript1=
function show/.*str0
M
if *strAA110
M
docu&ent.get7le&entBy#d*1t'tHint10.innerHTMLA11>
return>
N
if *window.MLHttp6e:uest0
M// code for #7RD% 5irefo'% /hro&e% ,pera% "afari
'&lhttpAnew MLHttp6e:uest*0>
N
else
M// code for #7B% #79
'&lhttpAnew )ctive,b$ect*1Microsoft.MLHTTP10>
N
'&lhttp.onreadystatechangeAfunction*0
M
if *'&lhttp.ready"tateAAS VV '&lhttp.statusAAQHH0
M
docu&ent.get7le&entBy#d*1t'tHint10.innerHTMLA'&lhttp.responseTe't>
N
N
'&lhttp.open*1-7T1%1getcd.php<:A1Dstr%true0>
'&lhttp.send*0>
N
;/script=
;/head=
;body=
;for&=
"elect a /.:
;select na&eA1cds1 onchangeA1show/.*this.value01=
;option valueA11="elect a /.:;/option=
;option valueA1Bob .ylan1=Bob .ylan;/option=
;option valueA1Bonnie Tyler1=Bonnie Tyler;/option=
;option valueA1.olly Parton1=.olly Parton;/option=
;/select=
;/for&=
;div idA1t'tHint1=;b=/. info will be listed here...;/b=;/div=
;/body=
;/ht&l=
The show/.*0 function does the following:
/hec( if a /. is selected
/reate an MLHttp6e:uest ob$ect
/reate the function to be e'ecuted when the server response is ready
"end the re:uest off to a file on the server
Fotice that a para&eter *:0 is added to the 46L *with the content of the dropdown list0
1he PHP File
The page on the server called by the !ava"cript above is a PHP file called 1getcd.php1.
The PHP script loads an ML docu&ent% 1cdJcatalog.'&l1% runs a :uery against the ML file% and
returns the result as HTML:
;<php
G:AGJ-7TO1:1P>
G'&l.oc A new .,M.ocu&ent*0>
G'&l.oc-=load*1cdJcatalog.'&l10>
G'AG'&l.oc-=get7le&entsByTagFa&e*8)6T#"T80>
for *GiAH> Gi;AG'-=length-E> GiDD0
M
//Process only ele&ent nodes
if *G'-=ite&*Gi0-=nodeTypeAAE0
M
if *G'-=ite&*Gi0-=childFodes-=ite&*H0-=node@alue AA G:0
M
GyA*G'-=ite&*Gi0-=parentFode0>
N
N
N
GcdA*Gy-=childFodes0>
for *GiAH>Gi;Gcd-=length>GiDD0
M
//Process only ele&ent nodes
if *Gcd-=ite&*Gi0-=nodeTypeAAE0
M
echo*1;b=1 . Gcd-=ite&*Gi0-=nodeFa&e . 1:;/b= 10>
echo*Gcd-=ite&*Gi0-=childFodes-=ite&*H0-=node@alue0>
echo*1;br /=10>
N
N
<=
3hen the /. :uery is sent fro& the !ava"cript to the PHP page% the following happens:
E. PHP creates an ML .,M ob$ect
Q. 5ind all ;artist= ele&ents that &atches the na&e sent fro& the !ava"cript
2. ,utput the albu& infor&ation *send to the 1t'tHint1 placeholder0
PHP 6%am#le 9 AHAG Li$e Search
)!) can be used to create &ore user-friendly and interactive searches.
AHAG Li$e Search
The following e'a&ple will de&onstrate a live search% where you get search results while you type.
Live search has &any benefits co&pared to traditional searching:
6esults are shown as you type
6esults narrow as you continue typing
#f results beco&e too narrow% re&ove characters to see a broader result
"earch for a 32"chools page in the input field below:
The results in the e'a&ple above are found in an ML file *lin(s.'&l0. To &a(e this e'a&ple s&all
and si&ple% only si' results are available.
6%am#le 6%#lained 9 1he H1ML Pa.e
3hen a user types a character in the input field above% the function 1show6esult*01 is e'ecuted. The
function is triggered by the 1on(eyup1 event:
;ht&l=
;head=
;script typeA1te't/$avascript1=
function show6esult*str0
M
if *str.lengthAAH0
M
docu&ent.get7le&entBy#d*1livesearch10.innerHTMLA11>
docu&ent.get7le&entBy#d*1livesearch10.style.borderA1Hp'1>
return>
N
if *window.MLHttp6e:uest0
M// code for #7RD% 5irefo'% /hro&e% ,pera% "afari
'&lhttpAnew MLHttp6e:uest*0>
N
else
M// code for #7B% #79
'&lhttpAnew )ctive,b$ect*1Microsoft.MLHTTP10>
N
'&lhttp.onreadystatechangeAfunction*0
M
if *'&lhttp.ready"tateAAS VV '&lhttp.statusAAQHH0
M
docu&ent.get7le&entBy#d*1livesearch10.innerHTMLA'&lhttp.responseTe't>
docu&ent.get7le&entBy#d*1livesearch10.style.borderA1Ep' solid ])9)/BQ1>
N
N
'&lhttp.open*1-7T1%1livesearch.php<:A1Dstr%true0>
'&lhttp.send*0>
N
;/script=
;/head=
;body=
;for&=
;input typeA1te't1 siCeA12H1 on(eyupA1show6esult*this.value01 /=
;div idA1livesearch1=;/div=
;/for&=
;/body=
;/ht&l=
"ource code e'planation:
#f the input field is e&pty *str.lengthAAH0% the function clears the content of the livesearch
placeholder and e'its the function.
#f the input field is not e&pty% the show6esult*0 function e'ecutes the following:
/reate an MLHttp6e:uest ob$ect
/reate the function to be e'ecuted when the server response is ready
"end the re:uest off to a file on the server
Fotice that a para&eter *:0 is added to the 46L *with the content of the input field0
1he PHP File
The page on the server called by the !ava"cript above is a PHP file called 1livesearch.php1.
The source code in 1livesearch.php1 searches an ML file for titles &atching the search string and
returns the result:
;<php
G'&l.ocAnew .,M.ocu&ent*0>
G'&l.oc-=load*1lin(s.'&l10>
G'AG'&l.oc-=get7le&entsByTagFa&e*8lin(80>
//get the : para&eter fro& 46L
G:AGJ-7TO1:1P>
//loo(up all lin(s fro& the '&l file if length of :=H
if *strlen*G:0=H0
M
GhintA11>
for*GiAH> Gi;*G'-=length0> GiDD0
M
GyAG'-=ite&*Gi0-=get7le&entsByTagFa&e*8title80>
GCAG'-=ite&*Gi0-=get7le&entsByTagFa&e*8url80>
if *Gy-=ite&*H0-=nodeTypeAAE0
M
//find a lin( &atching the search te't
if *stristr*Gy-=ite&*H0-=childFodes-=ite&*H0-=node@alue%G:00
M
if *GhintAA110
M
GhintA1;a hrefA81 .
GC-=ite&*H0-=childFodes-=ite&*H0-=node@alue .
18 targetA8Jblan(8=1 .
Gy-=ite&*H0-=childFodes-=ite&*H0-=node@alue . 1;/a=1>
N
else
M
GhintAGhint . 1;br /=;a hrefA81 .
GC-=ite&*H0-=childFodes-=ite&*H0-=node@alue .
18 targetA8Jblan(8=1 .
Gy-=ite&*H0-=childFodes-=ite&*H0-=node@alue . 1;/a=1>
N
N
N
N
N
// "et output to 1no suggestion1 if no hint were found
// or to the correct values
if *GhintAA110
M
GresponseA1no suggestion1>
N
else
M
GresponseAGhint>
N
//output the response
echo Gresponse>
<=
#f there is any te't sent fro& the !ava"cript *strlen*G:0 = H0% the following happens:
Load an ML file into a new ML .,M ob$ect
Loop through all ;title= ele&ents to find &atches fro& the te't sent fro& the !ava"cript
"ets the correct url and title in the 1Gresponse1 variable. #f &ore than one &atch is found% all
&atches are added to the variable
#f no &atches are found% the Gresponse variable is set to 1no suggestion1
PHP 6%am#le 9 AHAG -SS -eader
)n 6"" 6eader is used to read 6"" 5eeds.
AHAG -SS -eader
The following e'a&ple will de&onstrate an 6"" reader% where the 6""-feed is loaded into a
webpage without reloading:
6""-feed will be listed here...
6%am#le 6%#lained 9 1he H1ML Pa.e
3hen a user selects an 6""-feed in the dropdown list above% a function called 1show6esult*01 is
e'ecuted. The function is triggered by the 1onchange1 event:
;ht&l=
;head=
;script typeA1te't/$avascript1=
function show6""*str0
M
if *str.lengthAAH0
M
docu&ent.get7le&entBy#d*1rss,utput10.innerHTMLA11>
return>
N
if *window.MLHttp6e:uest0
M// code for #7RD% 5irefo'% /hro&e% ,pera% "afari
'&lhttpAnew MLHttp6e:uest*0>
N
else
M// code for #7B% #79
'&lhttpAnew )ctive,b$ect*1Microsoft.MLHTTP10>
N
'&lhttp.onreadystatechangeAfunction*0
M
if *'&lhttp.ready"tateAAS VV '&lhttp.statusAAQHH0
M
docu&ent.get7le&entBy#d*1rss,utput10.innerHTMLA'&lhttp.responseTe't>
N
N
'&lhttp.open*1-7T1%1getrss.php<:A1Dstr%true0>
'&lhttp.send*0>
N
;/script=
;/head=
;body=
;for&=
;select onchangeA1show6""*this.value01=
;option valueA11="elect an 6""-feed:;/option=
;option valueA1-oogle1=-oogle Fews;/option=
;option valueA1M"FB/1=M"FB/ Fews;/option=
;/select=
;/for&=
;br /=
;div idA1rss,utput1=6""-feed will be listed here...;/div=
;/body=
;/ht&l=
The show6esult*0 function does the following:
/hec( if an 6""-feed is selected
/reate an MLHttp6e:uest ob$ect
/reate the function to be e'ecuted when the server response is ready
"end the re:uest off to a file on the server
Fotice that a para&eter *:0 is added to the 46L *with the content of the dropdown list0
1he PHP File
The page on the server called by the !ava"cript above is a PHP file called 1getrss.php1:
;<php
//get the : para&eter fro& 46L
G:AGJ-7TO1:1P>
//find out which feed was selected
if*G:AA1-oogle10
M
G'&lA*1http://news.google.co&/news<nedAusVtopicAhVoutputArss10>
N
elseif*G:AA1M"FB/10
M
G'&lA*1http://rss.&snbc.&sn.co&/id/2H2QHIE/device/rss/rss.'&l10>
N
G'&l.oc A new .,M.ocu&ent*0>
G'&l.oc-=load*G'&l0>
//get ele&ents fro& 1;channel=1
GchannelAG'&l.oc-=get7le&entsByTagFa&e*8channel80-=ite&*H0>
GchannelJtitle A Gchannel-=get7le&entsByTagFa&e*8title80
-=ite&*H0-=childFodes-=ite&*H0-=node@alue>
GchannelJlin( A Gchannel-=get7le&entsByTagFa&e*8lin(80
-=ite&*H0-=childFodes-=ite&*H0-=node@alue>
GchannelJdesc A Gchannel-=get7le&entsByTagFa&e*8description80
-=ite&*H0-=childFodes-=ite&*H0-=node@alue>
//output ele&ents fro& 1;channel=1
echo*1;p=;a hrefA81 . GchannelJlin(
. 18=1 . GchannelJtitle . 1;/a=10>
echo*1;br /=10>
echo*GchannelJdesc . 1;/p=10>
//get and output 1;ite&=1 ele&ents
G'AG'&l.oc-=get7le&entsByTagFa&e*8ite&80>
for *GiAH> Gi;AQ> GiDD0
M
Gite&JtitleAG'-=ite&*Gi0-=get7le&entsByTagFa&e*8title80
-=ite&*H0-=childFodes-=ite&*H0-=node@alue>
Gite&Jlin(AG'-=ite&*Gi0-=get7le&entsByTagFa&e*8lin(80
-=ite&*H0-=childFodes-=ite&*H0-=node@alue>
Gite&JdescAG'-=ite&*Gi0-=get7le&entsByTagFa&e*8description80
-=ite&*H0-=childFodes-=ite&*H0-=node@alue>
echo *1;p=;a hrefA81 . Gite&Jlin(
. 18=1 . Gite&Jtitle . 1;/a=10>
echo *1;br /=10>
echo *Gite&Jdesc . 1;/p=10>
N
<=
3hen a re:uest for an 6"" feed is sent fro& the !ava"cript% the following happens:
/hec( which feed was selected
/reate a new ML .,M ob$ect
Load the 6"" docu&ent in the '&l variable
7'tract and output ele&ents fro& the channel ele&ent
7'tract and output ele&ents fro& the ite& ele&ents
PHP 6%am#le 9 AHAG Poll
AHAG Poll
The following e'a&ple will de&onstrate a poll where the result is shown without reloading.
Do you like PHP and AA! so far"
Kes:
Fo:
6%am#le 6%#lained 9 1he H1ML Pa.e
3hen a user choose an option above% a function called 1get@ote*01 is e'ecuted. The function is
triggered by the 1onclic(1 event:
;ht&l=
;head=
;script typeA1te't/$avascript1=
function get@ote*int0
M
if *window.MLHttp6e:uest0
M// code for #7RD% 5irefo'% /hro&e% ,pera% "afari
'&lhttpAnew MLHttp6e:uest*0>
N
else
M// code for #7B% #79
'&lhttpAnew )ctive,b$ect*1Microsoft.MLHTTP10>
N
'&lhttp.onreadystatechangeAfunction*0
M
if *'&lhttp.ready"tateAAS VV '&lhttp.statusAAQHH0
M
docu&ent.get7le&entBy#d*1poll10.innerHTMLA'&lhttp.responseTe't>
N
N
'&lhttp.open*1-7T1%1pollJvote.php<voteA1Dint%true0>
'&lhttp.send*0>
N
;/script=
;/head=
;body=
;div idA1poll1=
;h2=.o you li(e PHP and )!) so far<;/h2=
;for&=
Kes:
;input typeA1radio1 na&eA1vote1 valueA1H1 onclic(A1get@ote*this.value01 /=
;br /=Fo:
;input typeA1radio1 na&eA1vote1 valueA1E1 onclic(A1get@ote*this.value01 /=
;/for&=
;/div=
;/body=
;/ht&l=
The get@ote*0 function does the following:
/reate an MLHttp6e:uest ob$ect
/reate the function to be e'ecuted when the server response is ready
"end the re:uest off to a file on the server
Fotice that a para&eter *vote0 is added to the 46L *with the value of the yes or no option0
1he PHP File
The page on the server called by the !ava"cript above is a PHP file called 1pollJvote.php1:
;<php
Gvote A GJ67+47"TO8vote8P>
//get content of te'tfile
Gfilena&e A 1pollJresult.t't1>
Gcontent A file*Gfilena&e0>
//put content in array
Garray A e'plode*1WW1% GcontentOHP0>
Gyes A GarrayOHP>
Gno A GarrayOEP>
if *Gvote AA H0
M
Gyes A Gyes D E>
N
if *Gvote AA E0
M
Gno A Gno D E>
N
//insert votes to t't file
Ginsertvote A Gyes.1WW1.Gno>
Gfp A fopen*Gfilena&e%1w10>
fputs*Gfp%Ginsertvote0>
fclose*Gfp0>
<=
;hQ=6esult:;/hQ=
;table=
;tr=
;td=Kes:;/td=
;td=
;i&g srcA1poll.gif1
widthA8;<php echo*EHH?round*Gyes/*GnoDGyes0%Q00> <=8
heightA8QH8=
;<php echo*EHH?round*Gyes/*GnoDGyes0%Q00> <=T
;/td=
;/tr=
;tr=
;td=Fo:;/td=
;td=
;i&g srcA1poll.gif1
widthA8;<php echo*EHH?round*Gno/*GnoDGyes0%Q00> <=8
heightA8QH8=
;<php echo*EHH?round*Gno/*GnoDGyes0%Q00> <=T
;/td=
;/tr=
;/table=
The value is sent fro& the !ava"cript% and the following happens:
E. -et the content of the 1pollJresult.t't1 file
Q. Put the content of the file in variables and add one to the selected variable
2. 3rite the result to the 1pollJresult.t't1 file
S. ,utput a graphical representation of the poll result
1he 1e%t File
The te't file *pollJresult.t't0 is where we store the data fro& the poll.
#t is stored li(e this:
HWWH
The first nu&ber represents the 1Kes1 votes% the second nu&ber represents the 1Fo1 votes.
!ote2 6e&e&ber to allow your web server to edit the te't file. .o !41 give everyone access% $ust
the web server *PHP0.
PHP -6F6-6!)6
PHP Array Functions
PHP Array Introduction
The array functions allow you to &anipulate arrays.
PHP supports both si&ple and &ulti-di&ensional arrays. There are also specific functions for
populating arrays fro& database :ueries.
Installation
The array functions are part of the PHP core. There is no installation needed to use these functions.
PHP Array Functions
PHP: indicates the earliest version of PHP that supports the function.
Function Descri#tion PHP
array*0 /reates an array 2
arrayJchangeJ(eyJcase*0 6eturns an array with all (eys in lowercase or uppercase S
arrayJchun(*0 "plits an array into chun(s of arrays S
arrayJco&bine*0 /reates an array by using one array for (eys and another for
its values
9
arrayJcountJvalues*0 6eturns an array with the nu&ber of occurrences for each
value
S
arrayJdiff*0 /o&pares array values% and returns the differences S
arrayJdiffJassoc*0 /o&pares array (eys and values% and returns the differences S
arrayJdiffJ(ey*0 /o&pares array (eys% and returns the differences 9
arrayJdiffJuassoc*0 /o&pares array (eys and values% with an additional user-
&ade function chec(% and returns the differences
9
arrayJdiffJu(ey*0 /o&pares array (eys% with an additional user-&ade function
chec(% and returns the differences
9
arrayJfill*0 5ills an array with values S
arrayJfilter*0 5ilters ele&ents of an array using a user-&ade function S
arrayJflip*0 7'changes all (eys with their associated values in an array S
arrayJintersect*0 /o&pares array values% and returns the &atches S
arrayJintersectJassoc*0 /o&pares array (eys and values% and returns the &atches S
arrayJintersectJ(ey*0 /o&pares array (eys% and returns the &atches 9
arrayJintersectJuassoc*0 /o&pares array (eys and values% with an additional user-
&ade function chec(% and returns the &atches
9
arrayJintersectJu(ey*0 /o&pares array (eys% with an additional user-&ade function
chec(% and returns the &atches
9
arrayJ(eyJe'ists*0 /hec(s if the specified (ey e'ists in the array S
arrayJ(eys*0 6eturns all the (eys of an array S
arrayJ&ap*0 "ends each value of an array to a user-&ade function% which
returns new values
S
arrayJ&erge*0 Merges one or &ore arrays into one array S
arrayJ&ergeJrecursive*0 Merges one or &ore arrays into one array S
arrayJ&ultisort*0 "orts &ultiple or &ulti-di&ensional arrays S
arrayJpad*0 #nserts a specified nu&ber of ite&s% with a specified value%
to an array
S
arrayJpop*0 .eletes the last ele&ent of an array S
arrayJproduct*0 /alculates the product of the values in an array 9
arrayJpush*0 #nserts one or &ore ele&ents to the end of an array S
arrayJrand*0 6eturns one or &ore rando& (eys fro& an array S
arrayJreduce*0 6eturns an array as a string% using a user-defined function S
arrayJreverse*0 6eturns an array in the reverse order S
arrayJsearch*0 "earches an array for a given value and returns the (ey S
arrayJshift*0 6e&oves the first ele&ent fro& an array% and returns the
value of the re&oved ele&ent
S
arrayJslice*0 6eturns selected parts of an array S
arrayJsplice*0 6e&oves and replaces specified ele&ents of an array S
arrayJsu&*0 6eturns the su& of the values in an array S
arrayJudiff*0 /o&pares array values in a user-&ade function and returns
an array
9
arrayJudiffJassoc*0 /o&pares array (eys% and co&pares array values in a user-
&ade function% and returns an array
9
arrayJudiffJuassoc*0 /o&pares array (eys and array values in user-&ade
functions% and returns an array
9
arrayJuintersect*0 /o&pares array values in a user-&ade function and returns
an array
9
arrayJuintersectJassoc*0 /o&pares array (eys% and co&pares array values in a user-
&ade function% and returns an array
9
arrayJuintersectJuassoc*0 /o&pares array (eys and array values in user-&ade
functions% and returns an array
9
arrayJuni:ue*0 6e&oves duplicate values fro& an array S
arrayJunshift*0 )dds one or &ore ele&ents to the beginning of an array S
arrayJvalues*0 6eturns all the values of an array S
arrayJwal(*0 )pplies a user function to every &e&ber of an array 2
arrayJwal(Jrecursive*0 )pplies a user function recursively to every &e&ber of an
array
9
arsort*0 "orts an array in reverse order and &aintain inde'
association
2
asort*0 "orts an array and &aintain inde' association 2
co&pact*0 /reate array containing variables and their values S
count*0 /ounts ele&ents in an array% or properties in an ob$ect 2
current*0 6eturns the current ele&ent in an array 2
each*0 6eturns the current (ey and value pair fro& an array 2
end*0 "ets the internal pointer of an array to its last ele&ent 2
e'tract*0 #&ports variables into the current sy&bol table fro& an
array
2
inJarray*0 /hec(s if a specified value e'ists in an array S
(ey*0 5etches a (ey fro& an array 2
(rsort*0 "orts an array by (ey in reverse order 2
(sort*0 "orts an array by (ey 2
list*0 )ssigns variables as if they were an array 2
natcasesort*0 "orts an array using a case insensitive 1natural order1
algorith&
S
natsort*0 "orts an array using a 1natural order1 algorith& S
ne't*0 )dvance the internal array pointer of an array 2
pos*0 )lias of current*0 2
prev*0 6ewinds the internal array pointer 2
range*0 /reates an array containing a range of ele&ents 2
reset*0 "ets the internal pointer of an array to its first ele&ent 2
rsort*0 "orts an array in reverse order 2
shuffle*0 "huffles an array 2
siCeof*0 )lias of count*0 2
sort*0 "orts an array 2
uasort*0 "orts an array with a user-defined function and &aintain
inde' association
2
u(sort*0 "orts an array by (eys using a user-defined function 2
usort*0 "orts an array by values using a user-defined function 2
PHP Array )onstants
PHP: indicates the earliest version of PHP that supports the constant.
)onstant Descri#tion PHP
/)"7JL,376 4sed with arrayJchangeJ(eyJcase*0 to convert array (eys
to lower case

/)"7J4PP76 4sed with arrayJchangeJ(eyJcase*0 to convert array (eys
to upper case

",6TJ)"/ 4sed with arrayJ&ultisort*0 to sort in ascending order
",6TJ.7"/ 4sed with arrayJ&ultisort*0 to sort in descending order
",6TJ67-4L)6 4sed to co&pare ite&s nor&ally
",6TJF4M76#/ 4sed to co&pare ite&s nu&erically
",6TJ"T6#F- 4sed to co&pare ite&s as strings
",6TJL,/)L7J"T6#F- 4sed to co&pare ite&s as strings% based on the current
locale
S
/,4FTJF,6M)L
/,4FTJ67/46"#@7
7T6J,@7636#T7
7T6J"X#P
7T6JP675#J")M7
7T6JP675#J)LL
7T6JP675#J#F@)L#.
7T6JP675#J#5J7#"T"
7T6J#5J7#"T"
7T6J675"
PHP )alendar Functions
PHP )alendar Introduction
The calendar functions are useful when wor(ing with different calendar for&ats. The standard it is
based on is the !ulian day count *!ulian day count is a count of days starting fro& !anuary E% SRE2
B./.0. Fote that the !ulian day count is not the sa&e as the !ulian calendarL
!ote2 To convert between calendar for&ats% you &ust first convert to !ulian day count% then to the
calendar for&at.
Installation
The windows version of PHP has built-in support for the calendar e'tension. "o% the calendar
functions will wor( auto&atically.
However% if you are running the Linu' version of PHP% you will have to co&pile PHP with ""enable"
calendar to get the calendar functions to wor(.
PHP )alendar Functions
PHP: indicates the earliest version of PHP that supports the function.
Function Descri#tion PHP
calJdaysJinJ&onth*0 6eturns the nu&ber of days in a &onth for a specified year and
calendar
S
calJfro&J$d*0 /onverts a !ulian day count into a date of a specified calendar S
calJinfo*0 6eturns infor&ation about a given calendar S
calJtoJ$d*0 /onverts a date to !ulian day count S
easterJdate*0 6eturns the 4ni' ti&esta&p for &idnight on 7aster of a
specified year
2
easterJdays*0 6eturns the nu&ber of days after March QE% on which 7aster
falls for a specified year
2
5renchTo!.*0 /onverts a 5rench 6epublican date to a !ulian day count 2
-regorianTo!.*0 /onverts a -regorian date to a !ulian day count 2
!..ay,f3ee(*0 6eturns the day of a wee( 2
!.MonthFa&e*0 6eturns a &onth na&e 2
!.To5rench*0 /onverts a !ulian day count to a 5rench 6epublican date 2
!.To-regorian*0 /onverts a !ulian day count to a -regorian date 2
$dto$ewish*0 /onverts a !ulian day count to a !ewish date 2
!.To!ulian*0 /onverts a !ulian day count to a !ulian date 2
$dtouni'*0 /onverts a !ulian day count to a 4ni' ti&esta&p S
!ewishTo!.*0 /onverts a !ewish date to a !ulian day count 2
!ulianTo!.*0 /onverts a !ulian date to a !ulian day count 2
uni'to$d*0 /onverts a 4ni' ti&esta&p to a !ulian day count S
PHP )alendar )onstants
PHP: indicates the earliest version of PHP that supports the constant.
)onstant Descri#tion PHP
/)LJ-67-,6#)F -regorian calendar 2
/)LJ!4L#)F !ulian calendar 2
/)LJ!73#"H !ewish calendar 2
/)LJ567F/H 5rench 6epublican calendar 2
/)LJF4MJ/)L" 2
/)LJ.,3J.)KF, 2
/)LJ.,3J"H,6T 2
/)LJ.,3JL,F- 2
/)LJM,FTHJ-67-,6#)FJ"H,6T 2
/)LJM,FTHJ-67-,6#)FJL,F- 2
/)LJM,FTHJ!4L#)FJ"H,6T 2
/)LJM,FTHJ!4L#)FJL,F- 2
/)LJM,FTHJ!73#"H 2
/)LJM,FTHJ567F/H 2
/)LJ7)"T76J.75)4LT S
/)LJ7)"T76J6,M)F S
/)LJ7)"T76J)L3)K"J-67-,6#)F S
/)LJ7)"T76J)L3)K"J!4L#)F S
/)LJ!73#"HJ)..J)L)5#MJ-767"H 9
/)LJ!73#"HJ)..J)L)5#M 9
/)LJ!73#"HJ)..J-767"H)K#M 9
PHP Date * 1ime Functions
PHP Date * 1ime Introduction
The date/ti&e functions allow you to e'tract and for&at the date and ti&e on the server.
!ote2 These functions depend on the locale settings of the serverL
Installation
The date/ti&e functions are part of the PHP core. There is no installation needed to use these
functions.
-untime )on5i.uration
The behavior of the date/ti&e functions is affected by settings in php.ini.
.ate/Ti&e configuration options:
!ame De5ault Descri#tion )han.ea"le
date.defaultJlatitude 12E.RBBR1 "pecifies the default latitude *available
since PHP 90. This option is used by
dateJsunrise*0 and dateJsunset*0
PHPJ#F#J)LL
date.defaultJlongitude 129.Q2221 "pecifies the default longitude *available
since PHP 90. This option is used by
dateJsunrise*0 and dateJsunset*0
PHPJ#F#J)LL
date.sunriseJCenith 1IH.U21 "pecifies the default sunrise Cenith
*available since PHP 90. This option is
used by dateJsunrise*0 and dateJsunset*0
PHPJ#F#J)LL
date.sunsetJCenith 1IH.U21 "pecifies the default sunset Cenith
*available since PHP 90. This option is
used by dateJsunrise*0 and dateJsunset*0
PHPJ#F#J)LL
date.ti&eCone 11 "pecifies the default ti&eCone *available
since PHP 9.E0
PHPJ#F#J)LL
PHP Date * 1ime Functions
PHP: indicates the earliest version of PHP that supports the function.
Function Descri#tion PHP
chec(date*0 @alidates a -regorian date 2
dateJdefaultJti&eConeJget*0 6eturns the default ti&e Cone 9
dateJdefaultJti&eConeJset*0 "ets the default ti&e Cone 9
dateJsunrise*0 6eturns the ti&e of sunrise for a given day / location 9
dateJsunset*0 6eturns the ti&e of sunset for a given day / location 9
date*0 5or&ats a local ti&e/date 2
getdate*0 6eturns an array that contains date and ti&e infor&ation
for a 4ni' ti&esta&p
2
getti&eofday*0 6eturns an array that contains current ti&e infor&ation 2
g&date*0 5or&ats a -MT/4T/ date/ti&e 2
g&&(ti&e*0 6eturns the 4ni' ti&esta&p for a -MT date 2
g&strfti&e*0 5or&ats a -MT/4T/ ti&e/date according to locale
settings
2
idate*0 5or&ats a local ti&e/date as integer 9
localti&e*0 6eturns an array that contains the ti&e co&ponents of a
4ni' ti&esta&p
S
&icroti&e*0 6eturns the &icroseconds for the current ti&e 2
&(ti&e*0 6eturns the 4ni' ti&esta&p for a date 2
strfti&e*0 5or&ats a local ti&e/date according to locale settings 2
strpti&e*0 Parses a ti&e/date generated with strfti&e*0 9
strtoti&e*0 Parses an 7nglish te'tual date or ti&e into a 4ni'
ti&esta&p
2
ti&e*0 6eturns the current ti&e as a 4ni' ti&esta&p 2
PHP Date * 1ime )onstants
PHP: indicates the earliest version of PHP that supports the constant.
)onstant Descri#tion PHP
.)T7J)T,M )to& *e'a&ple: QHH9-HU-E9TEB:E2:H2DHHHH0
.)T7J/,,X#7 HTTP /oo(ies *e'a&ple: "un% ES )ug QHH9 EB:E2:H2
4T/0

.)T7J#",UBHE #",-UBHE *e'a&ple: QHH9-HU-ESTEB:E2:H2DHHHH0
.)T7J65/UQQ 65/ UQQ *e'a&ple: "un% ES )ug QHH9 EB:E2:H2 4T/0
.)T7J65/U9H 65/ U9H *e'a&ple: "unday% ES-)ug-H9 EB:E2:H2 4T/0
.)T7J65/EH2B 65/ EH2B *e'a&ple: "unday% ES-)ug-H9 EB:E2:H2 4T/0
.)T7J65/EEQ2 65/ EEQ2 *e'a&ple: "un% ES )ug QHH9 EB:E2:H2 4T/0
.)T7J65/QUQQ 65/ QUQQ *"un% ES )ug QHH9 EB:E2:H2 DHHHH0
.)T7J6"" 6"" *"un% ES )ug QHH9 EB:E2:H2 4T/0
.)T7J32/ 3orld 3ide 3eb /onsortiu& *e'a&ple: QHH9-HU-
ESTEB:E2:H2DHHHH0

PHP Directory Functions
PHP Directory Introduction
The directory functions allow you to retrieve infor&ation about directories and their contents.
Installation
The directory functions are part of the PHP core. There is no installation needed to use these
functions.
PHP Directory Functions
PHP: indicates the earliest version of PHP that supports the function.
Function Descri#tion PHP
chdir*0 /hanges the current directory 2
chroot*0 /hanges the root directory of the current process S
dir*0 ,pens a directory handle and returns an ob$ect 2
closedir*0 /loses a directory handle 2
getcwd*0 6eturns the current directory S
opendir*0 ,pens a directory handle 2
readdir*0 6eturns an entry fro& a directory handle 2
rewinddir*0 6esets a directory handle 2
scandir*0 Lists files and directories inside a specified path 9
PHP Directory )onstants
PHP: indicates the earliest version of PHP that supports the constant.
)onstant Descri#tion PHP
.#67/T,6KJ"7P)6)T,6 2
P)THJ"7P)6)T,6 S
PHP 6rror and Lo..in. Functions
PHP 6rror and Lo..in. Introduction
The error and logging functions allows error handling and logging.
The error functions allow users to define error handling rules% and &odify the way the errors can be
logged.
The logging functions allow users to log applications and send log &essages to e&ail% syste& logs or
other &achines.
Installation
The error and logging functions are part of the PHP core. There is no installation needed to use these
functions.
PHP 6rror and Lo..in. Functions
PHP: indicates the earliest version of PHP that supports the function.
Function Descri#tion PHP
debugJbac(trace*0 -enerates a bac(trace S
debugJprintJbac(trace*0 Prints a bac(trace 9
errorJgetJlast*0 -ets the last error occurred 9
errorJlog*0 "ends an error to the server error-log% to a file or to a
re&ote destination
S
errorJreporting*0 "pecifies which errors are reported S
restoreJerrorJhandler*0 6estores the previous error handler S
restoreJe'ceptionJhandler*0 6estores the previous e'ception handler 9
setJerrorJhandler*0 "ets a user-defined function to handle errors S
setJe'ceptionJhandler*0 "ets a user-defined function to handle e'ceptions 9
triggerJerror*0 /reates a user-defined error &essage S
userJerror*0 )lias of triggerJerror*0 S
PHP 6rror and Lo..in. )onstants
PHP: indicates the earliest version of PHP that supports the constant.
,alue )onstant Descri#tion PHP
E 7J766,6 5atal run-ti&e errors. 7rrors that cannot be recovered
fro&. 7'ecution of the script is halted

Q 7J3)6F#F- Fon-fatal run-ti&e errors. 7'ecution of the script is
not halted

S 7JP)6"7 /o&pile-ti&e parse errors. Parse errors should only
be generated by the parser

U 7JF,T#/7 6un-ti&e notices. The script found so&ething that
&ight be an error% but could also happen when
running a script nor&ally

EB 7J/,67J766,6 5atal errors at PHP startup. This is li(e an 7J766,6
in the PHP core
S
2Q 7J/,67J3)6F#F- Fon-fatal errors at PHP startup. This is li(e an
7J3)6F#F- in the PHP core
S
BS 7J/,MP#L7J766,6 5atal co&pile-ti&e errors. This is li(e an 7J766,6
generated by the \end "cripting 7ngine
S
EQU 7J/,MP#L7J3)6F#F- Fon-fatal co&pile-ti&e errors. This is li(e an
7J3)6F#F- generated by the \end "cripting
7ngine
S
Q9B 7J4"76J766,6 5atal user-generated error. This is li(e an 7J766,6
set by the progra&&er using the PHP function
triggerJerror*0
S
9EQ 7J4"76J3)6F#F- Fon-fatal user-generated warning. This is li(e an
7J3)6F#F- set by the progra&&er using the PHP
function triggerJerror*0
S
EHQS 7J4"76JF,T#/7 4ser-generated notice. This is li(e an 7JF,T#/7 set
by the progra&&er using the PHP function
triggerJerror*0
S
QHSU 7J"T6#/T 6un-ti&e notices. PHP suggest changes to your code
to help interoperability and co&patibility of the code
9
SHIB 7J67/,@76)BL7J766,6 /atchable fatal error. This is li(e an 7J766,6 but 9
can be caught by a user defined handle *see also
setJerrorJhandler*00
BES2 7J)LL )ll errors and warnings% e'cept of level 7J"T6#/T 9
PHP Filesystem Functions
PHP Filesystem Introduction
The filesyste& functions allow you to access and &anipulate the filesyste&.
Installation
The filesyste& functions are part of the PHP core. There is no installation needed to use these
functions.
-untime )on5i.uration
The behavior of the filesyste& functions is affected by settings in php.ini.
5ilesyste& configuration options:
!ame De5ault Descri#tion )han.ea"le
allowJurlJfopen 1E1
)llows fopen*0-type functions to wor(
with 46Ls *available since PHP S.H.S0
PHPJ#F#J"K"T7M
userJagent F4LL .efines the user agent for PHP to send
*available since PHP S.20
PHPJ#F#J)LL
defaultJsoc(etJti&eout 1BH1 "ets the default ti&eout% in seconds% for
soc(et based strea&s *available since
PHP S.20
PHPJ#F#J)LL
fro& 11 .efines the anony&ous 5TP password
*your e&ail address0
PHPJ#F#J)LL
autoJdetectJlineJendings 1H1 3hen set to 1E1% PHP will e'a&ine the
data read by fgets*0 and file*0 to see if it
is using 4ni'% M"-.os or Mac line-
PHPJ#F#J)LL
ending characters *available since PHP
S.20
:ni% * Windows )om#ati"ility
3hen specifying a path on 4ni' platfor&s% the forward slash */0 is used as directory separator.
However% on 3indows platfor&s% both forward slash */0 and bac(slash *Z0 can be used.
PHP Filesystem Functions
PHP: indicates the earliest version of PHP that supports the function.
Function Descri#tion PHP
basena&e*0 6eturns the filena&e co&ponent of a path 2
chgrp*0 /hanges the file group 2
ch&od*0 /hanges the file &ode 2
chown*0 /hanges the file owner 2
clearstatcache*0 /lears the file status cache 2
copy*0 /opies a file 2
delete*0 "ee unlin(*0 or unset*0
dirna&e*0 6eturns the directory na&e co&ponent of a path 2
dis(JfreeJspace*0 6eturns the free space of a directory S
dis(JtotalJspace*0 6eturns the total siCe of a directory S
dis(freespace*0 )lias of dis(JfreeJspace*0 2
fclose*0 /loses an open file 2
feof*0 Tests for end-of-file on an open file 2
fflush*0 5lushes buffered output to an open file S
fgetc*0 6eturns a character fro& an open file 2
fgetcsv*0 Parses a line fro& an open file% chec(ing for /"@ fields 2
fgets*0 6eturns a line fro& an open file 2
fgetss*0 6eturns a line% with HTML and PHP tags re&oved% fro& an open
file
2
file*0 6eads a file into an array 2
fileJe'ists*0 /hec(s whether or not a file or directory e'ists 2
fileJgetJcontents*0 6eads a file into a string S
fileJputJcontents 3rites a string to a file 9
fileati&e*0 6eturns the last access ti&e of a file 2
filecti&e*0 6eturns the last change ti&e of a file 2
filegroup*0 6eturns the group #. of a file 2
fileinode*0 6eturns the inode nu&ber of a file 2
file&ti&e*0 6eturns the last &odification ti&e of a file 2
fileowner*0 6eturns the user #. *owner0 of a file 2
fileper&s*0 6eturns the per&issions of a file 2
filesiCe*0 6eturns the file siCe 2
filetype*0 6eturns the file type 2
floc(*0 Loc(s or releases a file 2
fn&atch*0 Matches a filena&e or string against a specified pattern S
fopen*0 ,pens a file or 46L 2
fpassthru*0 6eads fro& an open file% until 7,5% and writes the result to the
output buffer
2
fputcsv*0 5or&ats a line as /"@ and writes it to an open file 9
fputs*0 )lias of fwrite*0 2
fread*0 6eads fro& an open file 2
fscanf*0 Parses input fro& an open file according to a specified for&at S
fsee(*0 "ee(s in an open file 2
fstat*0 6eturns infor&ation about an open file S
ftell*0 6eturns the current position in an open file 2
ftruncate*0 Truncates an open file to a specified length S
fwrite*0 3rites to an open file 2
glob*0 6eturns an array of filena&es / directories &atching a specified
pattern
S
isJdir*0 /hec(s whether a file is a directory 2
isJe'ecutable*0 /hec(s whether a file is e'ecutable 2
isJfile*0 /hec(s whether a file is a regular file 2
isJlin(*0 /hec(s whether a file is a lin( 2
isJreadable*0 /hec(s whether a file is readable 2
isJuploadedJfile*0 /hec(s whether a file was uploaded via HTTP P,"T 2
isJwritable*0 /hec(s whether a file is writeable S
isJwriteable*0 )lias of isJwritable*0 2
lin(*0 /reates a hard lin( 2
lin(info*0 6eturns infor&ation about a hard lin( 2
lstat*0 6eturns infor&ation about a file or sy&bolic lin( 2
&(dir*0 /reates a directory 2
&oveJuploadedJfile*0 Moves an uploaded file to a new location S
parseJiniJfile*0 Parses a configuration file S
pathinfo*0 6eturns infor&ation about a file path S
pclose*0 /loses a pipe opened by popen*0 2
popen*0 ,pens a pipe 2
readfile*0 6eads a file and writes it to the output buffer 2
readlin(*0 6eturns the target of a sy&bolic lin( 2
realpath*0 6eturns the absolute pathna&e S
rena&e*0 6ena&es a file or directory 2
rewind*0 6ewinds a file pointer 2
r&dir*0 6e&oves an e&pty directory 2
setJfileJbuffer*0 "ets the buffer siCe of an open file 2
stat*0 6eturns infor&ation about a file 2
sy&lin(*0 /reates a sy&bolic lin( 2
te&pna&*0 /reates a uni:ue te&porary file 2
t&pfile*0 /reates a uni:ue te&porary file 2
touch*0 "ets access and &odification ti&e of a file 2
u&as(*0 /hanges file per&issions for files 2
unlin(*0 .eletes a file 2
PHP Filesystem )onstants
PHP: indicates the earliest version of PHP that supports the constant.
)onstant Descri#tion PHP
-L,BJB6)/7
-L,BJ,FLK.#6
-L,BJM)6X
-L,BJF,",6T
-L,BJF,/H7/X
-L,BJF,7"/)P7
P)TH#F5,J.#6F)M7
P)TH#F5,JB)"7F)M7
P)TH#F5,J7T7F"#,F
5#L7J4"7J#F/L4.7JP)TH
5#L7J)PP7F.
5#L7J#-F,67JF73JL#F7"
5#L7J"X#PJ7MPTKJL#F7"
PHP Filter Functions
PHP Filter Introduction
This PHP filters is used to validate and filter data co&ing fro& insecure sources% li(e user input.
Installation
The filter functions are part of the PHP core. There is no installation needed to use these functions.
PHP Filter Functions
PHP: indicates the earliest version of PHP that supports the function.
Function Descri#tion PHP
filterJhasJvar*0 /hec(s if a variable of a specified input type e'ist 9
filterJid*0 6eturns the #. nu&ber of a specified filter 9
filterJinput*0 -et input fro& outside the script and filter it 9
filterJinputJarray*0 -et &ultiple inputs fro& outside the script and filters the& 9
filterJlist*0 6eturns an array of all supported filters 9
filterJvarJarray*0 -et &ultiple variables and filter the& 9
filterJvar*0 -et a variable and filter it 9
PHP Filters
ID !ame Descri#tion
5#LT76J/)LLB)/X /all a user-defined function to filter data
5#LT76J")F#T#\7J"T6#F- "trip tags% optionally strip or encode special
characters
5#LT76J")F#T#\7J"T6#PP7. )lias of 1string1 filter
5#LT76J")F#T#\7J7F/,.7. 46L-encode string% optionally strip or encode
special characters
5#LT76J")F#T#\7J"P7/#)LJ/H)6" HTML-escape 81;=V and characters with )"/##
value less than 2Q
5#LT76J")F#T#\7J7M)#L 6e&ove all characters% e'cept letters% digits and L
]GTV8?D-/A<aJbMWNc[.OP
5#LT76J")F#T#\7J46L 6e&ove all characters% e'cept letters% digits and G-
J.DL?8*0%MNWZZacOPb;=]T1>/<:[VA
5#LT76J")F#T#\7JF4MB76J#FT 6e&ove all characters% e'cept digits and D-
5#LT76J")F#T#\7JF4MB76J5L,)T 6e&ove all characters% e'cept digits% D- and
optionally .%e7
5#LT76J")F#T#\7JM)-#/J+4,T7" )pply addslashes*0
5#LT76J4F")57J6)3 .o nothing% optionally strip or encode special
characters
5#LT76J@)L#.)T7J#FT @alidate value as integer% optionally fro& the
specified range
5#LT76J@)L#.)T7JB,,L7)F 6eturn T647 for 1E1% 1true1% 1on1 and 1yes1%
5)L"7 for 1H1% 1false1% 1off1% 1no1% and 11% F4LL
otherwise
5#LT76J@)L#.)T7J5L,)T @alidate value as float
5#LT76J@)L#.)T7J67-7P @alidate value against rege'p% a Perl-co&patible
regular e'pression
5#LT76J@)L#.)T7J46L @alidate value as 46L% optionally with re:uired
co&ponents
5#LT76J@)L#.)T7J7M)#L @alidate value as e-&ail
5#LT76J@)L#.)T7J#P @alidate value as #P address% optionally only #PvS
or #PvB or not fro& private or reserved ranges
PHP F1P Functions
PHP F1P Introduction
The 5TP functions give client access to file servers through the 5ile Transfer Protocol *5TP0.
The 5TP functions are used to open% login and close connections% as well as upload% download%
rena&e% delete% and get infor&ation on files fro& file servers. Fot all of the 5TP functions will wor(
with every server or return the sa&e results. The 5TP functions beca&e available with PHP 2.
These functions are &eant for detailed access to an 5TP server. #f you only wish to read fro& or
write to a file on an 5TP server% consider using the ftp:// wrapper with the 5ilesyste& functions.
Installation
The windows version of PHP has built-in support for the 5TP e'tension. "o% the 5TP functions will
wor( auto&atically.
However% if you are running the Linu' version of PHP% you will have to co&pile PHP with ""enable"
ftp *PHP SD0 or ""#ith"ftp *PHP 20 to get the 5TP functions to wor(.
PHP F1P Functions
PHP: indicates the earliest version of PHP that supports the function.
Function Descri#tion PHP
ftpJalloc*0 )llocates space for a file to be uploaded to the 5TP server 9
ftpJcdup*0 /hanges the current directory to the parent directory on the 5TP
server
2
ftpJchdir*0 /hanges the current directory on the 5TP server 2
ftpJch&od*0 "ets per&issions on a file via 5TP 9
ftpJclose*0 /loses an 5TP connection S
ftpJconnect*0 ,pens an 5TP connection 2
ftpJdelete*0 .eletes a file on the 5TP server 2
ftpJe'ec*0 7'ecutes a progra&/co&&and on the 5TP server S
ftpJfget*0 .ownloads a file fro& the 5TP server and saves it to an open file 2
ftpJfput*0 4ploads fro& an open file and saves it to a file on the 5TP server 2
ftpJgetJoption*0 6eturns runti&e behaviors of the 5TP connection S
ftpJget*0 .ownloads a file fro& the 5TP server 2
ftpJlogin*0 Logs on to an 5TP connection 2
ftpJ&dt&*0 6eturns the last &odified ti&e of a specified file 2
ftpJ&(dir*0 /reates a new directory on the 5TP server 2
ftpJnbJcontinue*0 /ontinues retrieving/sending a file *non-bloc(ing0 S
ftpJnbJfget*0 .ownloads a file fro& the 5TP server and saves it to an open file
*non-bloc(ing0
S
ftpJnbJfput*0 4ploads fro& an open file and saves it to a file on the 5TP server
*non-bloc(ing0
S
ftpJnbJget*0 .ownloads a file fro& the 5TP server *non-bloc(ing0 S
ftpJnbJput*0 4ploads a file to the 5TP server *non-bloc(ing0 S
ftpJnlist*0 Lists the files in a specified directory on the 5TP server 2
ftpJpasv*0 Turns passive &ode on or off 2
ftpJput*0 4ploads a file to the 5TP server 2
ftpJpwd*0 6eturns the current directory na&e 2
ftpJ:uit*0 )lias of ftpJclose*0 2
ftpJraw*0 "ends a raw co&&and to the 5TP server 9
ftpJrawlist*0 6eturns a detailed list of files in the specified directory 2
ftpJrena&e*0 6ena&es a file or directory on the 5TP server 2
ftpJr&dir*0 6e&oves a directory on the 5TP server 2
ftpJsetJoption*0 "ets runti&e options for the 5TP connection S
ftpJsite*0 "ends a "#T7 co&&and to the server 2
ftpJsiCe*0 6eturns the siCe of the specified file 2
ftpJsslJconnect*0 ,pens a secure ""L-5TP connection S
ftpJsystype*0 6eturns the syste& type identifier of the 5TP server 2
PHP F1P )onstants
PHP: indicates the earliest version of PHP that supports the constant.
)onstant Descri#tion PHP
5TPJ)"/## 2
5TPJT7T 2
5TPJB#F)6K 2
5TPJ#M)-7 2
5TPJT#M7,4TJ"7/ 2
5TPJ)4T,"77X S
5TPJ)4T,67"4M7 .eter&ine resu&e position and start position for get and put
re:uests auto&atically
S
5TPJ5)#L7. )synchronous transfer has failed S
5TPJ5#F#"H7. )synchronous transfer has finished S
5TPJM,67.)T) )synchronous transfer is still active S
PHP H11P Functions
PHP H11P Introduction
The HTTP functions let you &anipulate infor&ation sent to the browser by the 3eb server% before
any other output has been sent.
Installation
The directory functions are part of the PHP core. There is no installation needed to use these
functions.
PHP H11P Functions
PHP: indicates the earliest version of PHP that supports the function.
Function Descri#tion PHP
header*0 "ends a raw HTTP header to a client 2
headersJlist*0 6eturns a list of response headers sent *or ready to send0 9
headersJsent*0 /hec(s if / where the HTTP headers have been sent 2
setcoo(ie*0 "ends an HTTP coo(ie to a client 2
setrawcoo(ie*0 "ends an HTTP coo(ie without 46L encoding the
coo(ie value
9
PHP H11P )onstants
!one7
PHP li"%ml Functions
PHP li"%ml Introduction
The lib'&l functions and constants are used together with "i&pleML% "LT and .,M functions.
Installation
These functions re:uire the lib'&l pac(age. .ownload at '&lsoft.org
PHP li"%ml Functions
PHP: indicates the earliest version of PHP that supports the function.
Function Descri#tion PHP
lib'&lJclearJerrors*0 /lear lib'&l error buffer 9
lib'&lJgetJerrors*0 6etrieve array of errors 9
lib'&lJgetJlastJerror*0 6etrieve last error fro& lib'&l 9
lib'&lJsetJstrea&sJconte't*0 "et the strea&s conte't for the ne't lib'&l docu&ent
load or write
9
lib'&lJuseJinternalJerrors*0 .isable lib'&l errors and allow user to fetch error
infor&ation as needed
9
PHP li"%ml )onstants
Function Descri#tion PHP
L#BMLJ/,MP)/T "et s&all nodes allocation opti&iCation. This &ay
i&prove the application perfor&ance
9
L#BMLJ.T.)TT6 "et default .T. attributes 9
L#BMLJ.T.L,). Load e'ternal subset 9
L#BMLJ.T.@)L#. @alidate with the .T. 9
L#BMLJF,BL)FX" 6e&ove blan( nodes 9
L#BMLJF,/.)T) "et /.)T) as te't nodes 9
L#BMLJF,7MPTKT)- /hange e&pty tags *e.g. ;br/= to ;br=;/br=0% only
available in the .,M.ocu&ent-=save*0 and
.,M.ocu&ent-=saveML*0 functions
9
L#BMLJF,7FT "ubstitute entities 9
L#BMLJF,766,6 .o not show error reports 9
L#BMLJF,F7T "top networ( access while loading docu&ents 9
L#BMLJF,3)6F#F- .o not show warning reports 9
L#BMLJF,ML.7/L .rop the ML declaration when saving a docu&ent 9
L#BMLJF"/L7)F 6e&ove e'cess na&espace declarations 9
L#BMLJ#F/L4.7 4se #nclude substitution 9
L#BMLJ766J766,6 -et recoverable errors 9
L#BMLJ766J5)T)L -et fatal errors 9
L#BMLJ766JF,F7 -et no errors 9
L#BMLJ766J3)6F#F- -et si&ple warnings 9
L#BMLJ@76"#,F -et lib'&l version *e.g. QHBH9 or QHBER0 9
L#BMLJ.,TT7.J@76"#,F -et dotted lib'&l version *e.g. Q.B.9 or Q.B.ER0 9
PHP Mail Functions
PHP Mail Introduction
The &ail*0 function allows you to send e&ails directly fro& a script.
-e?uirements
5or the &ail functions to be available% PHP re:uires an installed and wor(ing e&ail syste&. The
progra& to be used is defined by the configuration settings in the php.ini file.
Installation
The &ail functions are part of the PHP core. There is no installation needed to use these functions.
-untime )on5i.uration
The behavior of the &ail functions is affected by settings in the php.ini file.
Mail configuration options:
!ame De5ault Descri#tion )han.ea"le
"MTP 1localhost1 3indows only: The .F" na&e or #P
address of the "MTP server
PHPJ#F#J)LL
s&tpJport 1Q91 3indows only: The "MTP port nu&ber.
)vailable since PHP S.2
PHPJ#F#J)LL
send&ailJfro& F4LL 3indows only: "pecifies the 1fro&1
address to be used in e&ail sent fro&
PHP
PHPJ#F#J)LL
send&ailJpath F4LL 4ni' syste&s only: "pecifies where the
send&ail progra& can be found
*usually /usr/sbin/send&ail or
/usr/lib/send&ail0
PHPJ#F#J"K"T7M
PHP Mail Functions
PHP: indicates the earliest version of PHP that supports the function.
Function Descri#tion PHP
eC&l&Jhash*0 /alculates the hash value needed by the 7\MLM &ailing list syste& 2
&ail*0 )llows you to send e&ails directly fro& a script 2
PHP Mail )onstants
!one7
PHP Math Functions
PHP Math Introduction
The &ath functions can handle values within the range of integer and float types.
Installation
The &ath functions are part of the PHP core. There is no installation needed to use these functions.
PHP Math Functions
PHP: indicates the earliest version of PHP that supports the function.
Function Descri#tion PHP
abs*0 6eturns the absolute value of a nu&ber 2
acos*0 6eturns the arccosine of a nu&ber 2
acosh*0 6eturns the inverse hyperbolic cosine of a nu&ber S
asin*0 6eturns the arcsine of a nu&ber 2
asinh*0 6eturns the inverse hyperbolic sine of a nu&ber S
atan*0 6eturns the arctangent of a nu&ber as a nu&eric value between
-P#/Q and P#/Q radians
2
atanQ*0 6eturns the angle theta of an *'%y0 point as a nu&eric value
between -P# and P# radians
2
atanh*0 6eturns the inverse hyperbolic tangent of a nu&ber S
baseJconvert*0 /onverts a nu&ber fro& one base to another 2
bindec*0 /onverts a binary nu&ber to a deci&al nu&ber 2
ceil*0 6eturns the value of a nu&ber rounded upwards to the nearest
integer
2
cos*0 6eturns the cosine of a nu&ber 2
cosh*0 6eturns the hyperbolic cosine of a nu&ber S
decbin*0 /onverts a deci&al nu&ber to a binary nu&ber 2
deche'*0 /onverts a deci&al nu&ber to a he'adeci&al nu&ber 2
decoct*0 /onverts a deci&al nu&ber to an octal nu&ber 2
degQrad*0 /onverts a degree to a radian nu&ber 2
e'p*0 6eturns the value of 7
'
2
e'p&E*0 6eturns the value of 7
'
- E S
floor*0 6eturns the value of a nu&ber rounded downwards to the nearest
integer
2
f&od*0 6eturns the re&ainder *&odulo0 of the division of the argu&ents S
getrand&a'*0
6eturns the &a'i&u& rando& nu&ber that can be returned by a
call to the rand*0 function
2
he'dec*0 /onverts a he'adeci&al nu&ber to a deci&al nu&ber 2
hypot*0 6eturns the length of the hypotenuse of a right-angle triangle S
isJfinite*0 6eturns true if a value is a finite nu&ber S
isJinfinite*0 6eturns true if a value is an infinite nu&ber S
isJnan*0 6eturns true if a value is not a nu&ber S
lcgJvalue*0 6eturns a pseudo rando& nu&ber in the range of *H%E0 S
log*0 6eturns the natural logarith& *base 70 of a nu&ber 2
logEH*0 6eturns the base-EH logarith& of a nu&ber 2
logEp*0 6eturns log*EDnu&ber0 S
&a'*0 6eturns the nu&ber with the highest value of two specified
nu&bers
2
&in*0 6eturns the nu&ber with the lowest value of two specified
nu&bers
2
&tJgetrand&a'*0 6eturns the largest possible value that can be returned by
&tJrand*0
2
&tJrand*0 6eturns a rando& integer using Mersenne Twister algorith& 2
&tJsrand*0 "eeds the Mersenne Twister rando& nu&ber generator 2
octdec*0 /onverts an octal nu&ber to a deci&al nu&ber 2
pi*0 6eturns the value of P# 2
pow*0 6eturns the value of ' to the power of y 2
radQdeg*0 /onverts a radian nu&ber to a degree 2
rand*0 6eturns a rando& integer 2
round*0 6ounds a nu&ber to the nearest integer 2
sin*0 6eturns the sine of a nu&ber 2
sinh*0 6eturns the hyperbolic sine of a nu&ber S
s:rt*0 6eturns the s:uare root of a nu&ber 2
srand*0 "eeds the rando& nu&ber generator 2
tan*0 6eturns the tangent of an angle 2
tanh*0 6eturns the hyperbolic tangent of an angle S
PHP Math )onstants
PHP: indicates the earliest version of PHP that supports the constant.
)onstant Descri#tion PHP
MJ7 6eturns e *appro'. Q.REU0 S
MJ74L76 6eturns 7uler8s constant *appro'. H.9RR0 S
MJLFP# 6eturns the natural logarith& of P# *appro'. E.ESS0 S
MJLFQ 6eturns the natural logarith& of Q *appro'. H.BI20 S
MJLFEH 6eturns the natural logarith& of EH *appro'. Q.2HQ0 S
MJL,-Q7 6eturns the base-Q logarith& of 7 *appro'. E.SSQ0 S
MJL,-EH7 6eturns the base-EH logarith& of 7 *appro'. H.S2S0 S
MJP# 6eturns P# *appro'. 2.ESE9I0 2
MJP#JQ 6eturns P#/Q *appro'. E.9RH0 S
MJP#JS 6eturns P#/S *appro'. H.RU90 S
MJEJP# 6eturns E/P# *appro'. H.2EU0 S
MJQJP# 6eturns Q/P# *appro'. H.B2B0 S
MJ"+6TP# 6eturns the s:uare root of P# *appro'. E.RRQ0 S
MJQJ"+6TP# 6eturns Q/s:uare root of P# *appro'. E.EQU0 S
MJ"+6TEJQ 6eturns the s:uare root of E/Q *appro'. H.RHR0 S
MJ"+6TQ 6eturns the s:uare root of Q *appro'. E.SES0 S
MJ"+6T2 6eturns the s:uare root of 2 *appro'. E.R2Q0 S
PHP Misc7 Functions
PHP Miscellaneous Introduction
The &isc. functions were only placed here because none of the other categories see&ed to fit.
Installation
The &isc functions are part of the PHP core. There is no installation needed to use these functions.
-untime )on5i.uration
The behavior of the &isc functions is affected by settings in the php.ini file.
Misc. configuration options:
!ame De5ault Descri#tion )han.ea"le
ignoreJuserJabort 1H1 5)L"7 indicates that scripts will be
ter&inated as soon as they try to output
so&ething after a client has aborted their
connection
PHPJ#F#J)LL
highlight.string 1]..HHHH1 /olor for highlighting a string in PHP
synta'
PHPJ#F#J)LL
highlight.co&&ent 1]55UHHH1 /olor for highlighting PHP co&&ents PHPJ#F#J)LL
highlight.(eyword 1]HHRRHH1 /olor for synta' highlighting PHP PHPJ#F#J)LL
(eywords *e.g. parenthesis and
se&icolon0
highlight.bg 1]5555551 /olor for bac(ground PHPJ#F#J)LL
highlight.default 1]HHHHBB1 .efault color for PHP synta' PHPJ#F#J)LL
highlight.ht&l 1]HHHHHH1 /olor for HTML code PHPJ#F#J)LL
browscap F4LL Fa&e and location of browser-
capabilities file *e.g. browscap.ini0
PHPJ#F#J"K"T7M
PHP Misc7 Functions
PHP: indicates the earliest version of PHP that supports the function.
Function Descri#tion PHP
connectionJaborted*0 /hec(s whether the client has disconnected 2
connectionJstatus*0 6eturns the current connection status 2
connectionJti&eout*0 .eprecated in PHP S.H.9 2
constant*0 6eturns the value of a constant S
define*0 .efines a constant 2
defined*0 /hec(s whether a constant e'ists 2
die*0 Prints a &essage and e'its the current script 2
eval*0 7valuates a string as PHP code 2
e'it*0 Prints a &essage and e'its the current script 2
getJbrowser*0 6eturns the capabilities of the user8s browser 2
highlightJfile*0 ,utputs a file with the PHP synta' highlighted S
highlightJstring*0 ,utputs a string with the PHP synta' highlighted S
ignoreJuserJabort*0 "ets whether a re&ote client can abort the running of a script 2
pac(*0 Pac(s data into a binary string 2
phpJchec(Jsynta'*0 .eprecated in PHP 9.H.9 9
phpJstripJwhitespace*0 6eturns the source code of a file with PHP co&&ents and
whitespace re&oved
9
showJsource*0 )lias of highlightJfile*0 S
sleep*0 .elays code e'ecution for a nu&ber of seconds 2
ti&eJnanosleep*0 .elays code e'ecution for a nu&ber of seconds and nanoseconds 9
ti&eJsleepJuntil*0 .elays code e'ecution until a specified ti&e 9
uni:id*0 -enerates a uni:ue #. 2
unpac(*0 4npac(s data fro& a binary string 2
usleep*0 .elays code e'ecution for a nu&ber of &icroseconds 2
PHP Misc7 )onstants
PHP: indicates the earliest version of PHP that supports the constant.
)onstant Descri#tion PHP
/,FF7/T#,FJ)B,6T7.
/,FF7/T#,FJF,6M)L
/,FF7/T#,FJT#M7,4T
JJ/,MP#L76JH)LTJ,55"7TJJ 9
PHP MySQL Functions
PHP MySQL Introduction
The My"+L functions allows you to access My"+L database servers.
Installation
5or the My"+L functions to be available% you &ust co&pile PHP with My"+L support.
5or co&piling% use ""#ith"mys$l=%&' *the optional .#6 points to the My"+L directory0.
!ote2 5or full functionality of My"+L versions greater than S.E.% use the My"+Li e'tension instead.
#f you would li(e to install both the &ys:l e'tension and the &ys:li e'tension you should use the
sa&e client library to avoid any conflicts.
Installation on Linu% Systems
PHP I2 My"+L and the My"+L library is not enabled by default. 4se the ""#ith"mys$l=%&'
configure option to include My"+L support and download headers and libraries fro&
www.&ys:l.co&.
Installation on Windows Systems
PHP I2 My"+L is not enabled by default% so the phpJ&ys:l.dll &ust be enabled inside of php.ini.
)lso% PHP needs access to the My"+L client library. ) file na&ed lib&ys:l.dll is included in the
3indows PHP distribution% and in order for PHP to tal( to My"+L this file needs to be available to
the 3indows syste&s P)TH.
To enable any PHP e'tension% the PHP e'tensionJdir setting *in the php.ini file0 should be set to the
directory where the PHP e'tensions are located. )n e'a&ple e'tensionJdir value is c:ZphpZe't.
!ote2 #f you get the following error when starting the web server: 14nable to load dyna&ic library
8./phpJ&ys:l.dll81% this is because phpJ&ys:l.dll or lib&ys:l.dll cannot be found by the syste&.
-untime )on5i.uration
The behavior of the My"+L functions is affected by settings in the php.ini file.
My"+L configuration options:
!ame De5ault Descri#tion )han.ea"le
&ys:l.allowJpersistent 1E1 3hether or not to allow persistent
connections
PHPJ#F#J"K"T7M
&ys:l.&a'Jpersistent 1-E1 The &a'i&u& nu&ber of persistent
connections per process
PHPJ#F#J"K"T7M
&ys:l.&a'Jlin(s 1-E1 The &a'i&u& nu&ber of connections
per process *persistent connections
included0
PHPJ#F#J"K"T7M
&ys:l.traceJ&ode 1H1 Trace &ode. 3hen set to 1E1% warnings
and "+L-errors will be displayed.
)vailable since PHP S.2
PHPJ#F#J)LL
&ys:l.defaultJport F4LL The default T/P port nu&ber to use PHPJ#F#J)LL
&ys:l.defaultJsoc(et F4LL The default soc(et na&e to use.
)vailable since PHP S.H.E
PHPJ#F#J)LL
&ys:l.defaultJhost F4LL The default server host to use *doesn8t
apply in "+L safe &ode0
PHPJ#F#J)LL
&ys:l.defaultJuser F4LL The default user na&e to use *doesn8t
apply in "+L safe &ode0
PHPJ#F#J)LL
&ys:l.defaultJpassword F4LL The default password to use *doesn8t
apply in "+L safe &ode0
PHPJ#F#J)LL
&ys:l.connectJti&eout 1BH1 /onnection ti&eout in seconds PHPJ#F#J)LL
-esource 1y#es
There are two resource types used in the My"+L e'tension. The first one is the lin(Jidentifier for a
database connection% the second is a resource which holds the result of a :uery.
!ote2 Most My"+L functions accept lin(Jidentifier as the last optional para&eter. #f it is not
provided% the last opened connection is used.
PHP MySQL Functions
PHP: indicates the earliest version of PHP that supports the function.
Function Descri#tion PHP
&ys:lJaffectedJrows*0 6eturns the nu&ber of affected rows in the previous
My"+L operation
2
&ys:lJchangeJuser*0 .eprecated. /hanges the user of the current My"+L
connection
2
&ys:lJclientJencoding*0 6eturns the na&e of the character set for the current
connection
S
&ys:lJclose*0 /loses a non-persistent My"+L connection 2
&ys:lJconnect*0 ,pens a non-persistent My"+L connection 2
&ys:lJcreateJdb*0 .eprecated. /reates a new My"+L database. 4se 2
&ys:lJ:uery*0 instead
&ys:lJdataJsee(*0 Moves the record pointer 2
&ys:lJdbJna&e*0 6eturns a database na&e fro& a call to &ys:lJlistJdbs*0 2
&ys:lJdbJ:uery*0 .eprecated. "ends a My"+L :uery. 4se &ys:lJselectJdb*0
and &ys:lJ:uery*0 instead
2
&ys:lJdropJdb*0 .eprecated. .eletes a My"+L database. 4se &ys:lJ:uery*0
instead
2
&ys:lJerrno*0 6eturns the error nu&ber of the last My"+L operation 2
&ys:lJerror*0 6eturns the error description of the last My"+L operation 2
&ys:lJescapeJstring*0 .eprecated. 7scapes a string for use in a &ys:lJ:uery. 4se
&ys:lJrealJescapeJstring*0 instead
S
&ys:lJfetchJarray*0 6eturns a row fro& a recordset as an associative array
and/or a nu&eric array
2
&ys:lJfetchJassoc*0 6eturns a row fro& a recordset as an associative array S
&ys:lJfetchJfield*0 6eturns colu&n info fro& a recordset as an ob$ect 2
&ys:lJfetchJlengths*0 6eturns the length of the contents of each field in a result
row
2
&ys:lJfetchJob$ect*0 6eturns a row fro& a recordset as an ob$ect 2
&ys:lJfetchJrow*0 6eturns a row fro& a recordset as a nu&eric array 2
&ys:lJfieldJflags*0 6eturns the flags associated with a field in a recordset 2
&ys:lJfieldJlen*0 6eturns the &a'i&u& length of a field in a recordset 2
&ys:lJfieldJna&e*0 6eturns the na&e of a field in a recordset 2
&ys:lJfieldJsee(*0 Moves the result pointer to a specified field 2
&ys:lJfieldJtable*0 6eturns the na&e of the table the specified field is in 2
&ys:lJfieldJtype*0 6eturns the type of a field in a recordset 2
&ys:lJfreeJresult*0 5ree result &e&ory 2
&ys:lJgetJclientJinfo*0 6eturns My"+L client info S
&ys:lJgetJhostJinfo*0 6eturns My"+L host info S
&ys:lJgetJprotoJinfo*0 6eturns My"+L protocol info S
&ys:lJgetJserverJinfo*0 6eturns My"+L server info S
&ys:lJinfo*0 6eturns infor&ation about the last :uery S
&ys:lJinsertJid*0 6eturns the )4T,J#F/67M7FT #. generated fro& the
previous #F"76T operation
2
&ys:lJlistJdbs*0 Lists available databases on a My"+L server 2
&ys:lJlistJfields*0 .eprecated. Lists My"+L table fields. 4se &ys:lJ:uery*0
instead
2
&ys:lJlistJprocesses*0 Lists My"+L processes S
&ys:lJlistJtables*0 .eprecated. Lists tables in a My"+L database. 4se
&ys:lJ:uery*0 instead
2
&ys:lJnu&Jfields*0 6eturns the nu&ber of fields in a recordset 2
&ys:lJnu&Jrows*0 6eturns the nu&ber of rows in a recordset 2
&ys:lJpconnect*0 ,pens a persistent My"+L connection 2
&ys:lJping*0 Pings a server connection or reconnects if there is no
connection
S
&ys:lJ:uery*0 7'ecutes a :uery on a My"+L database 2
&ys:lJrealJescapeJstring*0 7scapes a string for use in "+L state&ents S
&ys:lJresult*0 6eturns the value of a field in a recordset 2
&ys:lJselectJdb*0 "ets the active My"+L database 2
&ys:lJstat*0 6eturns the current syste& status of the My"+L server S
&ys:lJtablena&e*0 .eprecated. 6eturns the table na&e of field. 4se
&ys:lJ:uery*0 instead
2
&ys:lJthreadJid*0 6eturns the current thread #. S
&ys:lJunbufferedJ:uery*0 7'ecutes a :uery on a My"+L database *without fetching /
buffering the result0
S
PHP MySQL )onstants
"ince PHP S.2 it has been possible to specify additional flags for the &ys:lJconnect*0 and
&ys:lJpconnect*0 functions:
PHP: indicates the earliest version of PHP that supports the constant.
)onstant Descri#tion PHP
MK"+LJ/L#7FTJ/,MP67"" 4se co&pression protocol S.2
MK"+LJ/L#7FTJ#-F,67J"P)/7 )llow space after function na&es S.2
MK"+LJ/L#7FTJ#FT76)/T#@7 )llow interactive ti&eout seconds of inactivity
before closing the connection
S.2
MK"+LJ/L#7FTJ""L 4se ""L encryption *only available with version
SD of the My"+L client library0
S.2
The &ys:lJfetchJarray*0 function uses a constant for the different types of result arrays. The
following constants are defined:
)onstant Descri#tion PHP
MK"+LJ)"",/ /olu&ns are returned into the array with the fieldna&e as the array
inde'

MK"+LJB,TH /olu&ns are returned into the array having both a nu&erical inde'
and the fieldna&e as the array inde'

MK"+LJF4M /olu&ns are returned into the array having a nu&erical inde' *inde'
starts at H0

PHP Sim#leGML Functions
PHP Sim#leGML Introduction
The "i&pleML functions lets you convert ML to an ob$ect.
This ob$ect can be processed% li(e any other ob$ect% with nor&al property selectors and array
iterators.
"o&e of these functions re:uires the newest PHP build.
Installation
The "i&pleML functions are part of the PHP core. There is no installation needed to use these
functions.
PHP Sim#leGML Functions
PHP: indicates the earliest version of PHP that supports the function.
Function Descri#tion PHP
JJconstruct*0 /reates a new "i&pleML7le&ent ob$ect 9
add)ttribute*0 )dds an attribute to the "i&pleML ele&ent 9
add/hild*0 )dds a child ele&ent the "i&pleML ele&ent 9
asML*0 -ets an ML string fro& a "i&pleML ele&ent 9
attributes*0 -ets a "i&pleML ele&ent8s attributes 9
children*0 -ets the children of a specified node 9
get.ocFa&espaces*0 -ets the na&espaces of an ML docu&ent 9
getFa&e*0 -ets the na&e of a "i&pleML ele&ent 9
getFa&espace*0 -ets the na&espaces fro& ML data 9
registerPathFa&espace*0 /reates a na&espace conte't for the ne't Path :uery 9
si&ple'&lJi&portJdo&*0 -ets a "i&pleML7le&ent ob$ect fro& a .,M node 9
si&ple'&lJloadJfile*0 -ets a "i&pleML7le&ent ob$ect fro& an ML docu&ent 9
si&ple'&lJloadJstring*0 -ets a "i&pleML7le&ent ob$ect fro& an ML string 9
'path*0 6uns an Path :uery on ML data 9
PHP Sim#leGML )onstants
Fone
PHP Strin. Functions
PHP Strin. Introduction
The string functions allow you to &anipulate strings.
Installation
The string functions are part of the PHP core. There is no installation needed to use these functions.
PHP Strin. Functions
PHP: indicates the earliest version of PHP that supports the function.
Function Descri#tion PHP
addcslashes*0 6eturns a string with bac(slashes in front of the
specified characters
S
addslashes*0 6eturns a string with bac(slashes in front of predefined
characters
2
binQhe'*0 /onverts a string of )"/## characters to he'adeci&al
values
2
chop*0 )lias of rtri&*0 2
chr*0 6eturns a character fro& a specified )"/## value 2
chun(Jsplit*0 "plits a string into a series of s&aller parts 2
convertJcyrJstring*0 /onverts a string fro& one /yrillic character-set to
another
2
convertJuudecode*0 .ecodes a uuencoded string 9
convertJuuencode*0 7ncodes a string using the uuencode algorith& 9
countJchars*0 6eturns how &any ti&es an )"/## character occurs
within a string and returns the infor&ation
S
crc2Q*0 /alculates a 2Q-bit /6/ for a string S
crypt*0 ,ne-way string encryption *hashing0 2
echo*0 ,utputs strings 2
e'plode*0 Brea(s a string into an array 2
fprintf*0 3rites a for&atted string to a specified output strea& 9
getJht&lJtranslationJtable*0 6eturns the translation table used by ht&lspecialchars*0
and ht&lentities*0
S
hebrev*0 /onverts Hebrew te't to visual te't 2
hebrevc*0 /onverts Hebrew te't to visual te't and new lines *Zn0
into ;br /=
2
ht&lJentityJdecode*0 /onverts HTML entities to characters S
ht&lentities*0 /onverts characters to HTML entities 2
ht&lspecialcharsJdecode*0 /onverts so&e predefined HTML entities to characters 9
ht&lspecialchars*0 /onverts so&e predefined characters to HTML entities 2
i&plode*0 6eturns a string fro& the ele&ents of an array 2
$oin*0 )lias of i&plode*0 2
levenshtein*0 6eturns the Levenshtein distance between two strings 2
localeconv*0 6eturns locale nu&eric and &onetary for&atting
infor&ation
S
ltri&*0 "trips whitespace fro& the left side of a string 2
&d9*0 /alculates the M.9 hash of a string 2
&d9Jfile*0 /alculates the M.9 hash of a file S
&etaphone*0 /alculates the &etaphone (ey of a string S
&oneyJfor&at*0 6eturns a string for&atted as a currency string S
nlJlanginfo*0 6eturns specific local infor&ation S
nlQbr*0 #nserts HTML line brea(s in front of each newline in a
string
2
nu&berJfor&at*0 5or&ats a nu&ber with grouped thousands 2
ord*0 6eturns the )"/## value of the first character of a string 2
parseJstr*0 Parses a :uery string into variables 2
print*0 ,utputs a string 2
printf*0 ,utputs a for&atted string 2
:uotedJprintableJdecode*0 .ecodes a :uoted-printable string 2
:uote&eta*0 +uotes &eta characters 2
rtri&*0 "trips whitespace fro& the right side of a string 2
setlocale*0 "ets locale infor&ation 2
shaE*0 /alculates the "H)-E hash of a string S
shaEJfile*0 /alculates the "H)-E hash of a file S
si&ilarJte't*0 /alculates the si&ilarity between two strings 2
sounde'*0 /alculates the sounde' (ey of a string 2
sprintf*0 3rites a for&atted string to a variable 2
sscanf*0 Parses input fro& a string according to a for&at S
strJireplace*0 6eplaces so&e characters in a string *case-insensitive0 9
strJpad*0 Pads a string to a new length S
strJrepeat*0 6epeats a string a specified nu&ber of ti&es S
strJreplace*0 6eplaces so&e characters in a string *case-sensitive0 2
strJrotE2*0 Perfor&s the 6,TE2 encoding on a string S
strJshuffle*0 6ando&ly shuffles all characters in a string S
strJsplit*0 "plits a string into an array 9
strJwordJcount*0 /ount the nu&ber of words in a string S
strcasec&p*0 /o&pares two strings *case-insensitive0 2
strchr*0 5inds the first occurrence of a string inside another string
*alias of strstr*00
2
strc&p*0 /o&pares two strings *case-sensitive0 2
strcoll*0 Locale based string co&parison S
strcspn*0 6eturns the nu&ber of characters found in a string before
any part of so&e specified characters are found
2
stripJtags*0 "trips HTML and PHP tags fro& a string 2
stripcslashes*0 4n:uotes a string :uoted with addcslashes*0 S
stripslashes*0 4n:uotes a string :uoted with addslashes*0 2
stripos*0 6eturns the position of the first occurrence of a string
inside another string *case-insensitive0
9
stristr*0 5inds the first occurrence of a string inside another string
*case-insensitive0
2
strlen*0 6eturns the length of a string 2
strnatcasec&p*0 /o&pares two strings using a 1natural order1 algorith&
*case-insensitive0
S
strnatc&p*0 /o&pares two strings using a 1natural order1 algorith&
*case-sensitive0
S
strncasec&p*0 "tring co&parison of the first n characters *case-
insensitive0
S
strnc&p*0 "tring co&parison of the first n characters *case-
sensitive0
S
strpbr(*0 "earches a string for any of a set of characters 9
strpos*0 6eturns the position of the first occurrence of a string
inside another string *case-sensitive0
2
strrchr*0 5inds the last occurrence of a string inside another string 2
strrev*0 6everses a string 2
strripos*0 5inds the position of the last occurrence of a string inside
another string *case-insensitive0
9
strrpos*0 5inds the position of the last occurrence of a string inside
another string *case-sensitive0
2
strspn*0 6eturns the nu&ber of characters found in a string that
contains only characters fro& a specified charlist
2
strstr*0 5inds the first occurrence of a string inside another string
*case-sensitive0
2
strto(*0 "plits a string into s&aller strings 2
strtolower*0 /onverts a string to lowercase letters 2
strtoupper*0 /onverts a string to uppercase letters 2
strtr*0 Translates certain characters in a string 2
substr*0 6eturns a part of a string 2
substrJco&pare*0 /o&pares two strings fro& a specified start position
*binary safe and optionally case-sensitive0
9
substrJcount*0 /ounts the nu&ber of ti&es a substring occurs in a string S
substrJreplace*0 6eplaces a part of a string with another string S
tri&*0 "trips whitespace fro& both sides of a string 2
ucfirst*0 /onverts the first character of a string to uppercase 2
ucwords*0 /onverts the first character of each word in a string to
uppercase
2
vfprintf*0 3rites a for&atted string to a specified output strea& 9
vprintf*0 ,utputs a for&atted string S
vsprintf*0 3rites a for&atted string to a variable S
wordwrap*0 3raps a string to a given nu&ber of characters S
PHP Strin. )onstants
PHP: indicates the earliest version of PHP that supports the constant.
)onstant Descri#tion PHP
/6KPTJ")LTJL7F-TH /ontains the length of the default encryption &ethod for
the
syste&. 5or standard .7" encryption% the length is Q

/6KPTJ"T.J.7" "et to E if the standard .7"-based encryption with a Q
character salt is supported% H otherwise

/6KPTJ7TJ.7" "et to E if the e'tended .7"-based encryption with a I
character salt is supported% H otherwise

/6KPTJM.9 "et to E if the M.9 encryption with a EQ character salt
starting with GEG is supported% H otherwise

/6KPTJBL,35#"H "et to E if the Blowfish encryption with a EB character
salt starting with GQG or GQaG is supported% H otherwiseH

HTMLJ"P7/#)L/H)6"
HTMLJ7FT#T#7"
7FTJ/,MP)T
7FTJ+4,T7"
7FTJF,+4,T7"
/H)6JM)
L/J/TKP7
L/JF4M76#/
L/JT#M7
L/J/,LL)T7
L/JM,F7T)6K
L/J)LL
L/JM7"")-7"
"T6JP).JL75T
"T6JP).J6#-HT
"T6JP).JB,TH
PHP GML Parser Functions
PHP GML Parser Introduction
The ML functions lets you parse% but not validate% ML docu&ents.
ML is a data for&at for standardiCed structured docu&ent e'change. More infor&ation on ML
can be found in our ML Tutorial.
This e'tension uses the 7'pat ML parser.
7'pat is an event-based parser% it views an ML docu&ent as a series of events. 3hen an event
occurs% it calls a specified function to handle it.
7'pat is a non-validating parser% and ignores any .T.s lin(ed to a docu&ent. However% if the
docu&ent is not well for&ed it will end with an error &essage.
Because it is an event-based% non validating parser% 7'pat is fast and well suited for web
applications.
The ML parser functions lets you create ML parsers and define handlers for ML events.
Installation
The ML functions are part of the PHP core. There is no installation needed to use these functions.
PHP GML Parser Functions
PHP: indicates the earliest version of PHP that supports the function.
Function Descri#tion PHP
utfUJdecode*0 .ecodes an 4T5-U string to #",-UU9I-E 2
utfUJencode*0 7ncodes an #",-UU9I-E string to 4T5-U 2
'&lJerrorJstring*0 -ets an error string fro& the ML parser 2
'&lJgetJcurrentJbyteJinde'*0 -ets the current byte inde' fro& the ML
parser
2
'&lJgetJcurrentJcolu&nJnu&ber*0 -ets the current colu&n nu&ber fro& the
ML parser
2
'&lJgetJcurrentJlineJnu&ber*0 -ets the current line nu&ber fro& the
ML parser
2
'&lJgetJerrorJcode*0 -ets an error code fro& the ML parser 2
'&lJparse*0 Parses an ML docu&ent 2
'&lJparseJintoJstruct*0 Parse ML data into an array 2
'&lJparserJcreateJns*0 /reate an ML parser with na&espace
support
S
'&lJparserJcreate*0 /reate an ML parser 2
'&lJparserJfree*0 5ree an ML parser 2
'&lJparserJgetJoption*0 -et options fro& an ML parser 2
'&lJparserJsetJoption*0 "et options in an ML parser 2
'&lJsetJcharacterJdataJhandler*0 "et handler function for character data 2
'&lJsetJdefaultJhandler*0 "et default handler function 2
'&lJsetJele&entJhandler*0 "et handler function for start and end
ele&ent of ele&ents
2
'&lJsetJendJna&espaceJdeclJhandler*0 "et handler function for the end of
na&espace declarations
S
'&lJsetJe'ternalJentityJrefJhandler*0 "et handler function for e'ternal entities 2
'&lJsetJnotationJdeclJhandler*0 "et handler function for notation
declarations
2
'&lJsetJob$ect*0 4se ML Parser within an ob$ect S
'&lJsetJprocessingJinstructionJhandler*0 "et handler function for processing
instruction
2
'&lJsetJstartJna&espaceJdeclJhandler*0 "et handler function for the start of
na&espace declarations
S
'&lJsetJunparsedJentityJdeclJhandler*0 "et handler function for unparsed entity
declarations
2
PHP GML Parser )onstants
)onstant
MLJ766,6JF,F7 *integer0
MLJ766,6JF,JM7M,6K *integer0
MLJ766,6J"KFT) *integer0
MLJ766,6JF,J7L7M7FT" *integer0
MLJ766,6J#F@)L#.JT,X7F *integer0
MLJ766,6J4F/L,"7.JT,X7F *integer0
MLJ766,6JP)6T#)LJ/H)6 *integer0
MLJ766,6JT)-JM#"M)T/H *integer0
MLJ766,6J.4PL#/)T7J)TT6#B4T7 *integer0
MLJ766,6J!4FXJ)5T76J.,/J7L7M7FT *integer0
MLJ766,6JP)6)MJ7FT#TKJ675 *integer0
MLJ766,6J4F.75#F7.J7FT#TK *integer0
MLJ766,6J67/46"#@7J7FT#TKJ675 *integer0
MLJ766,6J)"KF/J7FT#TK *integer0
MLJ766,6JB).J/H)6J675 *integer0
MLJ766,6JB#F)6KJ7FT#TKJ675 *integer0
MLJ766,6J)TT6#B4T7J7T76F)LJ7FT#TKJ675 *integer0
MLJ766,6JM#"PL)/7.JMLJP# *integer0
MLJ766,6J4FXF,3FJ7F/,.#F- *integer0
MLJ766,6J#F/,667/TJ7F/,.#F- *integer0
MLJ766,6J4F/L,"7.J/.)T)J"7/T#,F *integer0
MLJ766,6J7T76F)LJ7FT#TKJH)F.L#F- *integer0
MLJ,PT#,FJ/)"7J5,L.#F- *integer0
MLJ,PT#,FJT)6-7TJ7F/,.#F- *integer0
MLJ,PT#,FJ"X#PJT)-"T)6T *integer0
MLJ,PT#,FJ"X#PJ3H#T7 *integer0
PHP Ji# File Functions
PHP Ji# File Introduction
The \ip files functions allows you to read \#P files.
Installation
5or the \ip file functions to wor( on your server% these libraries &ust be installed:
The \\#Plib library by -uido .rahei&: .ownload the \\#Plib library
The \ip P7L/ e'tension: .ownload the \ip P7L/ e'tension
Installation on Linu% Systems
PHP I2 \ip functions and the \ip library is not enabled by default and &ust be downloaded fro&
the lin(s above. 4se the ""#ith"(ip=%&' configure option to include \ip support.
Installation on Windows Systems
PHP I2 \ip functions is not enabled by default% so the phpJCip.dll and the \\#Plib library &ust be
downloaded fro& the lin( above. phpJCip.dll &ust be enabled inside of php.ini.
To enable any PHP e'tension% the PHP e'tensionJdir setting *in the php.ini file0 should be set to the
directory where the PHP e'tensions are located. )n e'a&ple e'tensionJdir value is c:ZphpZe't.
PHP Ji# File Functions
PHP: indicates the earliest version of PHP that supports the function.
Function Descri#tion PHP
CipJclose*0 /loses a \#P file S
CipJentryJclose*0 /loses an entry in the \#P file S
CipJentryJco&pressedsiCe*0 6eturns the co&pressed siCe of an entry in the \#P file S
CipJentryJco&pression&ethod*0 6eturns the co&pression &ethod of an entry in the \#P
file
S
CipJentryJfilesiCe*0 6eturns the actual file siCe of an entry in the \#P file S
CipJentryJna&e*0 6eturns the na&e of an entry in the \#P file S
CipJentryJopen*0 ,pens an entry in the \#P file for reading S
CipJentryJread*0 6eads fro& an open entry in the \#P file S
CipJopen*0 ,pens a \#P file S
CipJread*0 6eads the ne't entry in a \#P file S
PHP Ji# File )onstants
F,F7

Vous aimerez peut-être aussi