Vous êtes sur la page 1sur 37

M.E.

CSE (WP)2010-2012 Web Technology Page


1 of 37
PHP is a powerful tool for making dynamic and interactive Web pages.
PHP is the widely-used, free, and efficient alternative to competitors such as Microsoft's !P.
"n our PHP tutorial you will learn about PHP, and how to e#ecute scripts on your server.
PHP is a server-side scripting language.
What is PHP?
PHP stands for PHP$ Hyperte#t Preprocessor
PHP is a server-side scripting language, like !P
PHP scripts are e#ecuted on the server
PHP supports many databases %My!&', "nformi#, (racle, !ybase, !olid, Postgre!&', )eneric (*+,,
etc.-
PHP is an open source software
PHP is free to download and use
What is a PHP File?
PHP files can contain te#t, H.M' tags and scripts
PHP files are returned to the browser as plain H.M'
PHP files have a file e#tension of /.php/, /.php0/, or /.phtml/
What is MySQL?
My!&' is a database server
My!&' is ideal for both small and large applications
My!&' supports standard !&'
My!&' compiles on a number of platforms
My!&' is free to download and use
PHP + MySQL
PHP combined with My!&' are cross-platform %you can develop in Windows and serve on a 1ni#
platform-
Why PHP?
PHP runs on different platforms %Windows, 'inu#, 1ni#, etc.-
PHP is compatible with almost all servers used today %pache, ""!, etc.-
PHP is 2344 to download from the official PHP resource$ www.php.net
PHP is easy to learn and runs efficiently on the server side
Download PHP
*ownload PHP for free here$ http$55www.php.net5downloads.php
Download MySQL Database
*ownload My!&' for free here$ http$55www.mys6l.com5downloads5
Download Apache Server
*ownload pache for free here$ http$55httpd.apache.org5download.cgi
PHP Syntax
PHP code is e#ecuted on the server, and the plain H.M' result is sent to the browser.
asic PHP Syntax
PHP scripting block always starts with !?php and ends with ?". PHP scripting block can be
placed anywhere in the document.
(n servers with shorthand support enabled you can start a scripting block with 78 and end with 89.
2or ma#imum compatibility, we recommend that you use the standard form %78php- rather than the
shorthand form.
78php
89
PHP file normally contains H.M' tags, :ust like an H.M' file, and some PHP scripting code.
+elow, we have an e#ample of a simple PHP script which sends the te#t /Hello World/ to the browser$
7html9
7body9
M.E. CSE (WP)2010-2012 Web Technology Page
2 of 37
78php
echo /Hello World/;
89
75body9
75html9
4ach code line in PHP must end with a semicolon. .he semicolon is a separator and is used to
distinguish one set of instructions from another.
.here are two basic statements to output te#t with PHP$ echo and print. "n the e#ample above we
have used the echo statement to output the te#t /Hello World/.
#ote$ .he file must have a .php e#tension. "f the file has a .html e#tension, the PHP code will not be
e#ecuted.
%o&&ents in PHP
"n PHP, we use 55 to make a single-line comment or 5< and <5 to make a large comment block.
7html9
7body9
78php
55.his is a comment
5< .his is a comment block <5
89
75body9
75html9
PHP 'ariables
variable is used to store information.
'ariables in PHP
=ariables are used for storing values, like te#t strings, numbers or arrays.
When a variable is declared, it can be used over and over again in your script.
ll variables in PHP start with a > sign symbol.
.he correct way of declaring a variable in PHP$
>var?name @ value;
Aew PHP programmers often forget the > sign at the beginning of the variable. "n that case it will not
work.
'et's try creating a variable containing a string, and a variable containing a number$
78php
>t#t@/Hello WorldB/;
>#@CD;
89
PHP is a Loosely (yped Lan)*a)e
"n PHP, a variable does not need to be declared before adding a value to it.
"n the e#ample above, you see that you do not have to tell PHP which data type the variable is.
PHP automatically converts the variable to the correct data type, depending on its value.
"n a strongly typed programming language, you have to declare %define- the type and name of the
variable before using it.
"n PHP, the variable is declared automatically when you use it.
#a&in) +*les ,or 'ariables
variable name must start with a letter or an underscore /?/
variable name can only contain alpha-numeric characters and underscores %a-E, -F, G-H, and ? -
variable name should not contain spaces. "f a variable name is more than one word, it should be
separated with an underscore %>my?string-, or with capitaliEation %>my!tring-
M.E. CSE (WP)2010-2012 Web Technology Page
3 of 37
PHP Strin) 'ariables
string variable is used to store and manipulate te#t.
Strin) 'ariables in PHP
!tring variables are used for values that contain characters.
"n this chapter we are going to look at the most common functions and operators used to manipulate
strings in PHP.
fter we create a string we can manipulate it. string can be used directly in a function or it can be
stored in a variable.
+elow, the PHP script assigns the te#t /Hello World/ to a string variable called >t#t$
78php
>t#t@/Hello World/;
echo >t#t;
89
.he output of the code above will be$
Hello World
Aow, lets try to use some different functions and operators to manipulate the string.
(he %oncatenation -perator
.here is only one string operator in PHP.
.he concatenation operator %.- is used to put two string values together.
.o concatenate two string variables together, use the concatenation operator$
78php
>t#tC@/Hello WorldB/;
>t#tI@/What a nice dayB/;
echo >t#tC . / / . >t#tI;
89
.he output of the code above will be$
Hello WorldB What a nice dayB
"f we look at the code above you see that we used the concatenation operator two times. .his is
because we had to insert a third string %a space character-, to separate the two strings.
(he strlen./ ,*nction
.he strlen%- function is used to return the length of a string.
'et's find the length of a string$
78php
echo strlen%/Hello worldB/-;
89
.he output of the code above will be$
CI
.he length of a string is often used in loops or other functions, when it is important to know when the
string ends. %i.e. in a loop, we would want to stop the loop after the last character in the string-.
(he strpos./ ,*nction
.he strpos%- function is used to search for a character5te#t within a string.
"f a match is found, this function will return the character position of the first match. "f no match is
found, it will return 2'!4.
'et's see if we can find the string /world/ in our string$
78php
echo strpos%/Hello worldB/,/world/-;
89
.he output of the code above will be$
M.E. CSE (WP)2010-2012 Web Technology Page
4 of 37
D
.he position of the string /world/ in the e#ample above is D. .he reason that it is D %and not J-, is that
the first character position in the string is G, and not C.
PHP -perators
(perators are used to operate on values.
PHP -perators
.his section lists the different operators used in PHP.
Arith&etic -perators
-perator Description 0xa&ple +es*lt
K ddition #@I
#KI
L
- !ubtraction #@I
M-#
0
< Multiplication #@L
#<M
IG
5 *ivision CM5M
M5I
0
I.M
N Modulus %division remainder- MNI
CGNO
CGNI
C
I
G
KK "ncrement #@M
#KK
#@D
-- *ecrement #@M
#--
#@L
Assi)n&ent -perators
-perator 0xa&ple 1s (he Sa&e As
@ #@y #@y
K@ #K@y #@#Ky
-@ #-@y #@#-y
<@ #<@y #@#<y
5@ #5@y #@#5y
.@ #.@y #@#.y
N@ #N@y #@#Ny
%o&parison -perators
-perator Description 0xa&ple
@@ is e6ual to M@@O returns false
B@ is not e6ual MB@O returns true
79 is not e6ual M79O returns true
9 is greater than M9O returns false
7 is less than M7O returns true
9@ is greater than or e6ual to M9@O returns false
7@ is less than or e6ual to M7@O returns true
Lo)ical -perators
-perator Description 0xa&ple
PP and #@D
M.E. CSE (WP)2010-2012 Web Technology Page
5 of 37
y@0
%# 7 CG PP y 9 C- returns true
QQ or #@D
y@0
%#@@M QQ y@@M- returns false
B not #@D
y@0
B%#@@y- returns true
PHP 1,2220lse State&ents
,onditional statements are used to perform different actions based on different conditions.
%onditional State&ents
=ery often when you write code, you want to perform different actions for different decisions.
Rou can use conditional statements in your code to do this.
"n PHP we have the following conditional statements$
i, state&ent - use this statement to e#ecute some code only if a specified condition is true
i,222else state&ent - use this statement to e#ecute some code if a condition is true and another code if
the condition is false
i,222elsei,2222else state&ent - use this statement to select one of several blocks of code to be e#ecuted
switch state&ent - use this statement to select one of many blocks of code to be e#ecuted
(he i, State&ent
1se the if statement to e#ecute some code only if a specified condition is true.
Syntax
if %condition- code to be executed if condition is true;
.he following e#ample will output /Have a nice weekendB/ if the current day is 2riday$
7html9
7body9
78php
>d@date%/*/-;
if %>d@@/2ri/- echo /Have a nice weekendB/;
89
75body9
75html9
Aotice that there is no ..else.. in this synta#. .he code is e#ecuted only i, the speci,ied condition is
tr*e.
(he i,222else State&ent
1se the if....else statement to e#ecute some code if a condition is true and another code if a condition
is false.
Syntax
if %condition-
code to be executed if condition is true;
else
code to be executed if condition is false;
0xa&ple
.he following e#ample will output /Have a nice weekendB/ if the current day is 2riday, otherwise it will
output /Have a nice dayB/$
7html9
7body9
M.E. CSE (WP)2010-2012 Web Technology Page
6 of 37
78php
>d@date%/*/-;
if %>d@@/2ri/-
echo /Have a nice weekendB/;
else
echo /Have a nice dayB/;
89
75body9
75html9
"f more than one line should be e#ecuted if a condition is true5false, the lines should be enclosed
within curly braces$
7html9
7body9
78php
>d@date%/*/-;
if %>d@@/2ri/-
S
echo /HelloB7br 59/;
echo /Have a nice weekendB/;
echo /!ee you on MondayB/;
T
89
75body9
75html9
(he i,222elsei,2222else State&ent
1se the if....elseif...else statement to select one of several blocks of code to be e#ecuted.
Syntax
if %condition-
code to be executed if condition is true;
elseif %condition-
code to be executed if condition is true;
else
code to be executed if condition is false;
0xa&ple
.he following e#ample will output /Have a nice weekendB/ if the current day is 2riday, and /Have a
nice !undayB/ if the current day is !unday. (therwise it will output /Have a nice dayB/$
7html9
7body9
78php
>d@date%/*/-;
if %>d@@/2ri/-
echo /Have a nice weekendB/;
elseif %>d@@/!un/-
echo /Have a nice !undayB/;
else
echo /Have a nice dayB/;
89
75body9
75html9
PHP Switch State&ent
,onditional statements are used to perform different actions based on different conditions.
M.E. CSE (WP)2010-2012 Web Technology Page
7 of 37
(he PHP Switch State&ent
1se the switch statement to select one of many blocks of code to be e#ecuted.
Syntax
switch %n-
S
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
default$
code to be executed if n is different from both label1 and label2;
T
.his is how it works$ 2irst we have a single e#pression n %most often a variable-, that is evaluated
once. .he value of the e#pression is then compared with the values for each case in the structure. "f
there is a match, the block of code associated with that case is e#ecuted. 1se brea3 to prevent the
code from running into the ne#t case automatically. .he default statement is used if no match is
found.
0xa&ple
7html9
7body9
78php
switch %>#-
S
case C$
echo /Aumber C/;
break;
case I$
echo /Aumber I/;
break;
case 0$
echo /Aumber 0/;
break;
default$
echo /Ao number between C and 0/;
T
89
75body9
75html9
PHP Arrays
n array stores multiple values in one single variable.
What is an Array?
variable is a storage area holding a number or te#t. .he problem is, a variable will hold only one
value.
n array is a special variable, which can store multiple values in one single variable.
"f you have a list of items %a list of car names, for e#ample-, storing the cars in single variables could
look like this$
>carsC@/!aab/;
>carsI@/=olvo/;
M.E. CSE (WP)2010-2012 Web Technology Page
8 of 37
>cars0@/+MW/;
However, what if you want to loop through the cars and find a specific one8 nd what if you had not 0
cars, but 0GG8
.he best solution here is to use an arrayB
n array can hold all your variable values under a single name. nd you can access the values by
referring to the array name.
4ach element in the array has its own inde# so that it can be easily accessed.
"n PHP, there are three kind of arrays$
#*&eric array - n array with a numeric inde#
Associative array - n array where each "* key is associated with a value
M*ltidi&ensional array - n array containing one or more arrays
#*&eric Arrays
numeric array stores each array element with a numeric inde#.
.here are two methods to create a numeric array.
C. "n the following e#ample the inde# are automatically assigned %the inde# starts at G-$
>cars@array%/!aab/,/=olvo/,/+MW/,/.oyota/-;
I. "n the following e#ample we assign the inde# manually$
>carsUGV@/!aab/;
>carsUCV@/=olvo/;
>carsUIV@/+MW/;
>carsU0V@/.oyota/;
0xa&ple
"n the following e#ample you access the variable values by referring to the array name and inde#$
78php
>carsUGV@/!aab/;
>carsUCV@/=olvo/;
>carsUIV@/+MW/;
>carsU0V@/.oyota/;
echo >carsUGV . / and / . >carsUCV . / are !wedish cars./;
89
.he code above will output$
!aab and =olvo are !wedish cars.
Associative Arrays
n associative array, each "* key is associated with a value.
When storing data about specific named values, a numerical array is not always the best way to do it.
With associative arrays we can use the values as keys and assign values to them.
0xa&ple 4
"n this e#ample we use an array to assign ages to the different persons$
>ages @ array%/Peter/@90I, /&uagmire/@90G, /Woe/@90L-;
0xa&ple 5
.his e#ample is the same as e#ample C, but shows a different way of creating the array$
>agesU'Peter'V @ /0I/;
>agesU'&uagmire'V @ /0G/;
>agesU'Woe'V @ /0L/;
.he "* keys can be used in a script$
78php
>agesU'Peter'V @ /0I/;
>agesU'&uagmire'V @ /0G/;
>agesU'Woe'V @ /0L/;
echo /Peter is / . >agesU'Peter'V . / years old./;
M.E. CSE (WP)2010-2012 Web Technology Page
9 of 37
89
.he code above will output$
Peter is 0I years old.
M*ltidi&ensional Arrays
"n a multidimensional array, each element in the main array can also be an array. nd each element
in the sub-array can be an array, and so on.
0xa&ple
"n this e#ample we create a multidimensional array, with automatically assigned "* keys$
>families @ array
%
/)riffin/@9array
%
/Peter/,
/'ois/,
/Megan/
-,
/&uagmire/@9array
%
/)lenn/
-,
/+rown/@9array
%
/,leveland/,
/'oretta/,
/Wunior/
-
-;
.he array above would look like this if written to the output$
rray
%
U)riffinV @9 rray
%
UGV @9 Peter
UCV @9 'ois
UIV @9 Megan
-
U&uagmireV @9 rray
%
UGV @9 )lenn
-
U+rownV @9 rray
%
UGV @9 ,leveland
UCV @9 'oretta
UIV @9 Wunior
-
-
0xa&ple 5
'ets try displaying a single value from the array above$
echo /"s / . >familiesU')riffin'VUIV .
/ a part of the )riffin family8/;
.he code above will output$
"s Megan a part of the )riffin family8
M.E. CSE (WP)2010-2012 Web Technology Page
10 of 37
PHP Loopin) 6 While Loops
'oops e#ecute a block of code a specified number of times, or while a specified condition is true.
PHP Loops
(ften when you write code, you want the same block of code to run over and over again in a row.
"nstead of adding several almost e6ual lines in a script we can use loops to perform a task like this.
"n PHP, we have the following looping statements$
while - loops through a block of code while a specified condition is true
do222while - loops through a block of code once, and then repeats the loop as long as a specified
condition is true
,or - loops through a block of code a specified number of times
,oreach - loops through a block of code for each element in an array
(he while Loop
.he while loop e#ecutes a block of code while a condition is true.
Syntax
while %condition-
S
code to be executed;
T
0xa&ple
.he e#ample below defines a loop that starts with i@C. .he loop will continue to run as long as i is less
than, or e6ual to M. i will increase by C each time the loop runs$
7html9
7body9
78php
>i@C;
while%>i7@M-
S
echo /.he number is / . >i . /7br 59/;
>iKK;
T
89
75body9
75html9
(utput$
.he number is C
.he number is I
.he number is 0
.he number is L
.he number is M
(he do222while State&ent
.he do...while statement will always e#ecute the block of code once, it will then check the condition,
and repeat the loop while the condition is true.
Syntax
do
S
code to be executed;
T
while %condition-;
M.E. CSE (WP)2010-2012 Web Technology Page
11 of 37
0xa&ple
.he e#ample below defines a loop that starts with i@C. "t will then increment i with C, and write some
output. .hen the condition is checked, and the loop will continue to run as long as i is less than, or
e6ual to M$
7html9
7body9
78php
>i@C;
do
S
>iKK;
echo /.he number is / . >i . /7br 59/;
T
while %>i7@M-;
89
75body9
75html9
(utput$
.he number is I
.he number is 0
.he number is L
.he number is M
.he number is D
.he for loop and the foreach loop will be e#plained in the ne#t chapter.
PHP Loopin) 6 For Loops
'oops e#ecute a block of code a specified number of times, or while a specified condition is true.
(he ,or Loop
.he for loop is used when you know in advance how many times the script should run.
Syntax
for %init; condition; increment-
S
code to be executed;
T
Parameters$
init$ Mostly used to set a counter %but can be any code to be e#ecuted once at the beginning of the
loop-
condition$ 4valuated for each loop iteration. "f it evaluates to .314, the loop continues. "f it evaluates to
2'!4, the loop ends.
increment$ Mostly used to increment a counter %but can be any code to be e#ecuted at the end of the
loop-
#ote$ 4ach of the parameters above can be empty, or have multiple e#pressions %separated by
commas-.
0xa&ple
.he e#ample below defines a loop that starts with i@C. .he loop will continue to run as long as i is less
than, or e6ual to M. i will increase by C each time the loop runs$
7html9
7body9
78php
for %>i@C; >i7@M; >iKK-
S
echo /.he number is / . >i . /7br 59/;
T
M.E. CSE (WP)2010-2012 Web Technology Page
12 of 37
89
75body9
75html9
(utput$
.he number is C
.he number is I
.he number is 0
.he number is L
.he number is M
(he ,oreach Loop
.he foreach loop is used to loop through arrays.
Syntax
foreach %>array as >value-
S
code to be executed;
T
2or every loop iteration, the value of the current array element is assigned to >value %and the array
pointer is moved by one- - so on the ne#t loop iteration, you'll be looking at the ne#t array value.
0xa&ple
.he following e#ample demonstrates a loop that will print the values of the given array$
7html9
7body9
78php
>#@array%/one/,/two/,/three/-;
foreach %># as >value-
S
echo >value . /7br 59/;
T
89
75body9
75html9
(utput$
one
two
three
PHP F*nctions
.he real power of PHP comes from its functions.
"n PHP, there are more than JGG built-in functions.
PHP *ilt6in F*nctions
PHP F*nctions
"n this chapter we will show you how to create your own functions.
.o keep the script from 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.
Rou may call a function from anywhere within a page.
%reate a PHP F*nction
function will be e#ecuted by a call to the function.
Syntax
function functionName%-
S
M.E. CSE (WP)2010-2012 Web Technology Page
13 of 37
code to be executed;
T
PHP function guidelines$
)ive the function a name that reflects what the function does
.he function name can start with a letter or underscore %not a number-
0xa&ple
simple function that writes my name when it is called$
7html9
7body9
78php
function writeAame%-
S
echo /Xai Wim 3efsnes/;
T
echo /My name is /;
writeAame%-;
89
75body9
75html9
(utput$
My name is Xai Wim 3efsnes
PHP F*nctions 6 Addin) para&eters
.o add more functionality to a function, we can add parameters. parameter is :ust like a variable.
Parameters are specified after the function name, inside the parentheses.
0xa&ple 4
.he following e#ample will write different first names, but e6ual last name$
7html9
7body9
78php
function writeAame%>fname-
S
echo >fname . / 3efsnes.7br 59/;
T
echo /My name is /;
writeAame%/Xai Wim/-;
echo /My sister's name is /;
writeAame%/Hege/-;
echo /My brother's name is /;
writeAame%/!tale/-;
89
75body9
75html9
(utput$
My name is Xai Wim 3efsnes.
My sister's name is Hege 3efsnes.
My brother's name is !tale 3efsnes.
0xa&ple 5
.he following function has two parameters$
7html9
7body9
78php
function writeAame%>fname,>punctuation-
M.E. CSE (WP)2010-2012 Web Technology Page
14 of 37
S
echo >fname . / 3efsnes/ . >punctuation . /7br 59/;
T
echo /My name is /;
writeAame%/Xai Wim/,/./-;
echo /My sister's name is /;
writeAame%/Hege/,/B/-;
echo /My brother's name is /;
writeAame%/!tYle/,/8/-;
89
75body9
75html9
(utput$
My name is Xai Wim 3efsnes.
My sister's name is Hege 3efsnesB
My brother's name is !tYle 3efsnes8

PHP F*nctions 6 +et*rn val*es
.o let a function return a value, use the return statement.
0xa&ple
7html9
7body9
78php
function add%>#,>y-
S
>total@>#K>y;
return >total;
T
echo /C K CD @ / . add%C,CD-;
89
75body9
75html9
(utput$
C K CD @ CJ
PHP For&s and 7ser 1np*t
.he PHP >?)4. and >?P(!. variables are used to retrieve information from forms, like user input.
PHP For& Handlin)
.he most important thing to notice when dealing with H.M' forms and PHP is that any form element
in an H.M' page will a*to&atically be available to your PHP scripts.
0xa&ple
.he e#ample below contains an H.M' form with two input fields and a submit button$
7html9
7body9
7form action@/welcome.php/ method@/post/9
Aame$ 7input type@/te#t/ name@/fname/ 59
ge$ 7input type@/te#t/ name@/age/ 59
7input type@/submit/ 59
75form9
75body9
75html9
When a user fills out the form above and click on the submit button, the form data is sent to a PHP
file, called /welcome.php/$
M.E. CSE (WP)2010-2012 Web Technology Page
15 of 37
/welcome.php/ looks like this$
7html9
7body9
Welcome 78php echo >?P(!.U/fname/V; 89B7br 59
Rou are 78php echo >?P(!.U/age/V; 89 years old.
75body9
75html9
(utput could be something like this$
Welcome WohnB
Rou are IO years old.
.he PHP >?)4. and >?P(!. functions will be e#plained in the ne#t chapters.
For& 'alidation
1ser input should be validated on the browser whenever possible %by client scripts-. +rowser
validation is faster and reduces the server load.
Rou should consider server validation if the user input will be inserted into a database. good way to
validate a form on the server is to post the form to itself, instead of :umping to a different page. .he
user will then get the error messages on the same page as the form. .his makes it easier to discover
the error.
PHP 89:0( F*nction
.he built-in >?)4. function is used to collect values in a form with method@/get/.
(he 89:0( F*nction
.he built-in >?)4. function is used to collect values from a form sent with method@/get/.
"nformation sent from a form with the )4. method is visible to everyone %it will be displayed in the
browser's address bar- and has limits on the amount of information to send.
0xa&ple
7form action@/welcome.php/ method@/get/9
Aame$ 7input type@/te#t/ name@/fname/ 59
ge$ 7input type@/te#t/ name@/age/ 59
7input type@/submit/ 59
75form9
When the user clicks the /!ubmit/ button, the 13' sent to the server could look something like this$
http$55www.sathyabama.com5welcome.php8fname@PeterPage@0J
.he /welcome.php/ file can now use the >?)4. function to collect form data %the names of the form
fields will automatically be the keys in the >?)4. array-$
Welcome 78php echo >?)4.U/fname/V; 89.7br 59
Rou are 78php echo >?)4.U/age/V; 89 years oldB
When to *se &ethod;<)et<?
When using method@/get/ in H.M' forms, all variable names and values are displayed in the 13'.
#ote$ .his method should not be used when sending passwords or other sensitive informationB
However, because the variables are displayed in the 13', it is possible to bookmark the page. .his
can be useful in some cases.
#ote$ .he get method is not suitable for very large variable values. "t should not be used with values
e#ceeding IGGG characters.
PHP 89P-S( F*nction
.he built-in >?P(!. function is used to collect values in a form with method@/post/.
(he 89P-S( F*nction
.he built-in >?P(!. function is used to collect values from a form sent with method@/post/.
M.E. CSE (WP)2010-2012 Web Technology Page
16 of 37
"nformation sent from a form with the P(!. method is invisible to others and has no limits on the
amount of information to send.
#ote$ However, there is an O Mb ma# siEe for the P(!. method, by default %can be changed by
setting the post?ma#?siEe in the php.ini file-.
0xa&ple
7form action@/welcome.php/ method@/post/9
Aame$ 7input type@/te#t/ name@/fname/ 59
ge$ 7input type@/te#t/ name@/age/ 59
7input type@/submit/ 59
75form9
When the user clicks the /!ubmit/ button, the 13' will look like this$
http$55www.sathyabama.com5welcome.php
.he /welcome.php/ file can now use the >?P(!. function to collect form data %the names of the form
fields will automatically be the keys in the >?P(!. array-$
Welcome 78php echo >?P(!.U/fname/V; 89B7br 59
Rou are 78php echo >?P(!.U/age/V; 89 years old.
When to *se &ethod;<post<?
"nformation sent from a form with the P(!. method is invisible to others and has no limits on the
amount of information to send.
However, because the variables are not displayed in the 13', it is not possible to bookmark the page.
(he PHP 89+0Q70S( F*nction
.he PHP built-in >?34&14!. function contains the contents of both >?)4., >?P(!., and
>?,((X"4.
.he >?34&14!. function can be used to collect form data sent with both the )4. and P(!.
methods.
0xa&ple
Welcome 78php echo >?34&14!.U/fname/V; 89B7br 59
Rou are 78php echo >?34&14!.U/age/V; 89 years old.
PHP Date./ F*nction
.he PHP date%- function is used to format a time and5or date.
(he PHP Date./ F*nction
.he PHP date%- function formats a timestamp to a more readable date and time.
timestamp is a se6uence of characters, denoting the date and5or time at which a certain event
occurred.
Syntax
date%format,timestamp-
Para&eter Description
format 3e6uired. !pecifies the format of the timestamp
timestamp (ptional. !pecifies a timestamp. *efault is the current date and time
PHP Date./ 6 For&at the Date
.he re6uired format parameter in the date%- function specifies how to format the date5time.
Here are some characters that can be used$
d - 3epresents the day of the month %GC to 0C-
m - 3epresents a month %GC to CI-
R - 3epresents a year %in four digits-
M.E. CSE (WP)2010-2012 Web Technology Page
17 of 37
(ther characters, like/5/, /./, or /-/ can also be inserted between the letters to add additional
formatting$
78php
echo date%/R5m5d/- . /7br 59/;
echo date%/R.m.d/- . /7br 59/;
echo date%/R-m-d/-;
89
.he output of the code above could be something like this$
IGGH5GM5CC
IGGH.GM.CC
IGGH-GM-CC
PHP Date./ 6 Addin) a (i&esta&p
.he optional timestamp parameter in the date%- function specifies a timestamp. "f you do not specify a
timestamp, the current date and time will be used.
.he mktime%- function returns the 1ni# timestamp for a date.
.he 1ni# timestamp contains the number of seconds between the 1ni# 4poch %Wanuary C CHJG
GG$GG$GG )M.- and the time specified.
Syntax ,or &3ti&e./
mktime%hour,minute,second,month,day,year,is?dst-
.o go one day in the future we simply add one to the day argument of mktime%-$
78php
>tomorrow @ mktime%G,G,G,date%/m/-,date%/d/-KC,date%/R/--;
echo /.omorrow is /.date%/R5m5d/, >tomorrow-;
89
.he output of the code above could be something like this$
.omorrow is IGGH5GM5CI
PHP 1ncl*de File
Server Side 1ncl*des .SS1/
Rou can insert the content of one PHP file into another PHP file before the server e#ecutes it, with the
include%- or re6uire%- function.
.he two functions are identical in every way, e#cept how they handle errors$
include%- generates a warning, but the script will continue e#ecution
re6uire%- generates a fatal error, and the script will stop
.hese two functions are used to create functions, headers, footers, or elements that will be reused on
multiple pages.
!erver side includes saves a lot of work. .his means that you can create a standard header, footer, or
menu file for all your web pages. When the header needs to be updated, you can only update the
include file, or when you add a new page to your site, you can simply change the menu file %instead
of updating the links on all your web pages-.
PHP incl*de./ F*nction
.he include%- function takes all the content in a specified file and includes it in the current file.
"f an error occurs, the include%- function generates a warning, but the script will continue e#ecution.
0xa&ple 4
ssume that you have a standard header file, called /header.php/. .o include the header file in a
page, use the include%- function$
7html9
7body9
78php include%/header.php/-; 89
7hC9Welcome to my home pageB75hC9
M.E. CSE (WP)2010-2012 Web Technology Page
18 of 37
7p9!ome te#t.75p9
75body9
75html9
0xa&ple 5
ssume we have a standard menu file, called /menu.php/, that should be used on all pages$
7a href@/5default.php/9Home75a9
7a href@/5tutorials.php/9.utorials75a9
7a href@/5references.php/93eferences75a9
7a href@/5e#amples.php/94#amples75a9
7a href@/5about.php/9bout 1s75a9
7a href@/5contact.php/9,ontact 1s75a9
ll pages in the Web site should include this menu file. Here is how it can be done$
7html9
7body9
7div class@/leftmenu/9
78php include%/menu.php/-; 89
75div9
7hC9Welcome to my home page.75hC9
7p9!ome te#t.75p9
75body9
75html9
"f you look at the source code of the page above %in a browser-, it will look like this$
7html9
7body9
7div class@/leftmenu/9
7a href@/5default.php/9Home75a9
7a href@/5tutorials.php/9.utorials75a9
7a href@/5references.php/93eferences75a9
7a href@/5e#amples.php/94#amples75a9
7a href@/5about.php/9bout 1s75a9
7a href@/5contact.php/9,ontact 1s75a9
75div9
7hC9Welcome to my home pageB75hC9
7p9!ome te#t.75p9
75body9
75html9
PHP re=*ire./ F*nction
.he re6uire%- function is identical to include%-, e#cept that it handles errors differently.
"f an error occurs, the include%- function generates a warning, but the script will continue e#ecution.
.he re6uire%- generates a fatal error, and the script will stop.
0rror 0xa&ple incl*de./ F*nction
7html9
7body9
78php
include%/wrong2ile.php/-;
echo /Hello WorldB/;
89
75body9
75html9
4rror message$
Warnin)$ include%wrong2ile.php- Ufunction.includeV$
failed to open stream$
Ao such file or directory in ,$ZhomeZwebsiteZtest.php on line M
M.E. CSE (WP)2010-2012 Web Technology Page
19 of 37
Warnin)$ include%- Ufunction.includeV$
2ailed opening 'wrong2ile.php' for inclusion
%include?path@'.;,$ZphpMZpear'-
in ,$ZhomeZwebsiteZtest.php on line M
Hello WorldB
Aotice that the echo statement is e#ecutedB .his is because a Warning does not stop the script
e#ecution.
0rror 0xa&ple re=*ire./ F*nction
Aow, let's run the same e#ample with the re6uire%- function.
7html9
7body9
78php
re6uire%/wrong2ile.php/-;
echo /Hello WorldB/;
89
75body9
75html9
4rror message$
Warnin)$ re6uire%wrong2ile.php- Ufunction.re6uireV$
failed to open stream$
Ao such file or directory in ,$ZhomeZwebsiteZtest.php on line M
Fatal error$ re6uire%- Ufunction.re6uireV$
2ailed opening re6uired 'wrong2ile.php'
%include?path@'.;,$ZphpMZpear'-
in ,$ZhomeZwebsiteZtest.php on line M
.he echo statement is not e#ecuted, because the script e#ecution stopped after the fatal error.
"t is recommended to use the re6uire%- function instead of include%-, because scripts should not
continue after an error.
PHP File Handlin)
.he fopen%- function is used to open files in PHP.
-penin) a File
.he fopen%- function is used to open files in PHP.
.he first parameter of this function contains the name of the file to be opened and the second
parameter specifies in which mode the file should be opened$
7html9
7body9
78php
>file@fopen%/welcome.t#t/,/r/-;
89
75body9
75html9
.he file may be opened in one of the following modes$
Modes Description
r 3ead only. !tarts at the beginning of the file
rK 3ead5Write. !tarts at the beginning of the file
w Write only. (pens and clears the contents of file; or creates a new file if it doesn't e#ist
wK 3ead5Write. (pens and clears the contents of file; or creates a new file if it doesn't e#ist
a ppend. (pens and writes to the end of the file or creates a new file if it doesn't e#ist
M.E. CSE (WP)2010-2012 Web Technology Page
20 of 37
aK 3ead5ppend. Preserves file content by writing to the end of the file
# Write only. ,reates a new file. 3eturns 2'!4 and an error if file already e#ists
#K 3ead5Write. ,reates a new file. 3eturns 2'!4 and an error if file already e#ists
#ote$ "f the fopen%- function is unable to open the specified file, it returns G %false-.
0xa&ple
.he following e#ample generates a message if the fopen%- function is unable to open the specified
file$
7html9
7body9
78php
>file@fopen%/welcome.t#t/,/r/- or e#it%/1nable to open fileB/-;
89
75body9
75html9
%losin) a File
.he fclose%- function is used to close an open file$
78php
>file @ fopen%/test.t#t/,/r/-;
55some code to be e#ecuted
fclose%>file-;
89
%hec3 0nd6o,6,ile
.he feof%- function checks if the /end-of-file/ %4(2- has been reached.
.he feof%- function is useful for looping through data of unknown length.
#ote$ Rou cannot read from files opened in w, a, and # modeB
if %feof%>file-- echo /4nd of file/;
+eadin) a File Line by Line
.he fgets%- function is used to read a single line from a file.
#ote$ fter a call to this function the file pointer has moved to the ne#t line.
0xa&ple
.he e#ample below reads a file line by line, until the end of file is reached$
78php
>file @ fopen%/welcome.t#t/, /r/- or e#it%/1nable to open fileB/-;
55(utput a line of the file until the end is reached
while%Bfeof%>file--
S
echo fgets%>file-. /7br 59/;
T
fclose%>file-;
89
M.E. CSE (WP)2010-2012 Web Technology Page
21 of 37
+eadin) a File %haracter by %haracter
.he fgetc%- function is used to read a single character from a file.
#ote$ fter a call to this function the file pointer moves to the ne#t character.
0xa&ple
.he e#ample below reads a file character by character, until the end of file is reached$
78php
>file@fopen%/welcome.t#t/,/r/- or e#it%/1nable to open fileB/-;
while %Bfeof%>file--
S
echo fgetc%>file-;
T
fclose%>file-;
89
PHP %oo3ies
cookie is often used to identify a user.
What is a %oo3ie?
cookie is often used to identify a user. cookie is a small file that the server embeds on the user's
computer. 4ach time the same computer re6uests a page with a browser, it will send the cookie too.
With PHP, you can both create and retrieve cookie values.
How to %reate a %oo3ie?
.he setcookie%- function is used to set a cookie.
#ote$ .he setcookie%- function must appear +42(34 the 7html9 tag.
Syntax
setcookie%name, value, e#pire, path, domain-;
0xa&ple 4
"n the e#ample below, we will create a cookie named /user/ and assign the value /le# Porter/ to it.
We also specify that the cookie should e#pire after one hour$
78php
setcookie%/user/, /le# Porter/, time%-K0DGG-;
89
7html9
.....
#ote$ .he value of the cookie is automatically 13'encoded when sending the cookie, and
automatically decoded when received %to prevent 13'encoding, use setrawcookie%- instead-.
0xa&ple 5
Rou can also set the e#piration time of the cookie in another way. "t may be easier than using
seconds.
78php
>e#pire@time%-KDG<DG<IL<0G;
setcookie%/user/, /le# Porter/, >e#pire-;
89
7html9
.....
"n the e#ample above the e#piration time is set to a month %60 sec * 60 min * 24 hours * 0 days-.
How to +etrieve a %oo3ie 'al*e?
M.E. CSE (WP)2010-2012 Web Technology Page
22 of 37
.he PHP >?,((X"4 variable is used to retrieve a cookie value.
"n the e#ample below, we retrieve the value of the cookie named /user/ and display it on a page$
78php
55 Print a cookie
echo >?,((X"4U/user/V;
55 way to view all cookies
print?r%>?,((X"4-;
89
"n the following e#ample we use the isset%- function to find out if a cookie has been set$
7html9
7body9
78php
if %isset%>?,((X"4U/user/V--
echo /Welcome / . >?,((X"4U/user/V . /B7br 59/;
else
echo /Welcome guestB7br 59/;
89
75body9
75html9
How to Delete a %oo3ie?
When deleting a cookie you should assure that the e#piration date is in the past.
*elete e#ample$
78php
55 set the e#piration date to one hour ago
setcookie%/user/, //, time%--0DGG-;
89
What i, a rowser Does #-( S*pport %oo3ies?
"f your application deals with browsers that do not support cookies, you will have to use other
methods to pass information from one page to another in your application. (ne method is to pass the
data through forms %forms and user input are described earlier in this tutorial-.
.he form below passes the user input to /welcome.php/ when the user clicks on the /!ubmit/ button$
7html9
7body9
7form action@/welcome.php/ method@/post/9
Aame$ 7input type@/te#t/ name@/name/ 59
ge$ 7input type@/te#t/ name@/age/ 59
7input type@/submit/ 59
75form9
75body9
75html9
3etrieve the values in the /welcome.php/ file like this$
M.E. CSE (WP)2010-2012 Web Technology Page
23 of 37
7html9
7body9
Welcome 78php echo >?P(!.U/name/V; 89.7br 59
Rou are 78php echo >?P(!.U/age/V; 89 years old.
75body9
75html9
PHP Sessions
PHP session variable is used to store information about, or change settings for a user session.
!ession variables hold information about one single user, and are available to all pages in one
application.
PHP Session 'ariables
When you are working with an application, you open it, do some changes and then you close it. .his
is much like a !ession. .he computer knows who you are. "t knows when you start the application
and when you end. +ut on the internet there is one problem$ the web server does not know who you
are and what you do because the H..P address doesn't maintain state.
PHP session solves this problem by allowing you to store user information on the server for later
use %i.e. username, shopping items, etc-. However, session information is temporary and will be
deleted after the user has left the website. "f you need a permanent storage you may want to store
the data in a database.
!essions work by creating a uni6ue id %1"*- for each visitor and store variables based on this 1"*.
.he 1"* is either stored in a cookie or is propagated in the 13'.
Startin) a PHP Session
+efore you can store user information in your PHP session, you must first start up the session.
#ote$ .he session?start%- function must appear +42(34 the 7html9 tag$
78php session?start%-; 89
7html9
7body9
75body9
75html9
.he code above will register the user's session with the server, allow you to start saving user
information, and assign a 1"* for that user's session.
Storin) a Session 'ariable
.he correct way to store and retrieve session variables is to use the PHP >?!4!!"(A variable$
M.E. CSE (WP)2010-2012 Web Technology Page
24 of 37
78php
session?start%-;
55 store session data
>?!4!!"(AU'views'V@C;
89
7html9
7body9
78php
55retrieve session data
echo /Pageviews@/. >?!4!!"(AU'views'V;
89
75body9
75html9
(utput$
Pageviews@C
"n the e#ample below, we create a simple page-views counter. .he isset%- function checks if the
/views/ variable has already been set. "f /views/ has been set, we can increment our counter. "f
/views/ doesn't e#ist, we create a /views/ variable, and set it to C$
78php
session?start%-;
if%isset%>?!4!!"(AU'views'V--
>?!4!!"(AU'views'V@>?!4!!"(AU'views'VKC;
else
>?!4!!"(AU'views'V@C;
echo /=iews@/. >?!4!!"(AU'views'V;
89
Destroyin) a Session
"f you wish to delete some session data, you can use the unset%- or the session?destroy%- function.
.he unset%- function is used to free the specified session variable$
78php
unset%>?!4!!"(AU'views'V-;
89
Rou can also completely destroy the session by calling the session?destroy%- function$
78php
session?destroy%-;
89
#ote$ session?destroy%- will reset your session and you will lose all your stored session data.
PHP 0rror Handlin)
.he default error handling in PHP is very simple. n error message with filename, line number and a
message describing the error is sent to the browser.
PHP 0rror Handlin)
When creating scripts and web applications, error handling is an important part. "f your code lacks
error checking code, your program may look very unprofessional and you may be open to security
risks.
.his tutorial contains some of the most common error checking methods in PHP.
We will show different error handling methods$
M.E. CSE (WP)2010-2012 Web Technology Page
25 of 37
!imple /die%-/ statements
,ustom errors and error triggers
4rror reporting
asic 0rror Handlin)$ 7sin) the die./ ,*nction
.he first e#ample shows a simple script that opens a te#t file$
78php
>file@fopen%/welcome.t#t/,/r/-;
89
"f the file does not e#ist you might get an error like this$
Warnin)$ fopen%welcome.t#t- Ufunction.fopenV$ failed to open stream$
Ao such file or directory in %$>web,older>test2php on line 5
.o avoid that the user gets an error message like the one above, we test if the file e#ist before we try
to access it$
78php
if%Bfile?e#ists%/welcome.t#t/--
S
die%/2ile not found/-;
T
else
S
>file@fopen%/welcome.t#t/,/r/-;
T
89
Aow if the file does not e#ist you get an error like this$
2ile not found
.he code above is more efficient than the earlier code, because it uses a simple error handling
mechanism to stop the script after the error.
However, simply stopping the script is not always the right way to go. 'et's take a look at alternative
PHP functions for handling errors.
%reatin) a %*sto& 0rror Handler
,reating a custom error handler is 6uite simple. We simply create a special function that can be
called when an error occurs in PHP.
.his function must be able to handle a minimum of two parameters %error level and error message-
but can accept up to five parameters %optionally$ file, line-number, and the error conte#t-$
Syntax
error?function%error?level,error?message,
error?file,error?line,error?conte#t-
Para&eter Description
error?level 3e6uired. !pecifies the error report level for the user-defined error. Must be a value
number. !ee table below for possible error report levels
error?message 3e6uired. !pecifies the error message for the user-defined error
error?file (ptional. !pecifies the filename in which the error occurred
error?line (ptional. !pecifies the line number in which the error occurred
error?conte#t (ptional. !pecifies an array containing every variable, and their values, in use when the
error occurred
0rror +eport levels
.hese error report levels are the different types of error the user-defined error handler can be used
for$
M.E. CSE (WP)2010-2012 Web Technology Page
26 of 37
'al*e %onstant Description
I 4?W3A"A) Aon-fatal run-time errors. 4#ecution of the script is not halted
O 4?A(.",4 3un-time notices. .he script found something that might be an error,
but could also happen when running a script normally
IMD 4?1!43?433(3 2atal user-generated error. .his is like an 4?433(3 set by the
programmer using the PHP function trigger?error%-
MCI 4?1!43?W3A"A) Aon-fatal user-generated warning. .his is like an 4?W3A"A) set by
the programmer using the PHP function trigger?error%-
CGIL 4?1!43?A(.",4 1ser-generated notice. .his is like an 4?A(.",4 set by the
programmer using the PHP function trigger?error%-
LGHD 4?34,(=43+'4?433(3 ,atchable fatal error. .his is like an 4?433(3 but can be caught by a
user defined handle %see also set?error?handler%--
OCHC 4?'' ll errors and warnings, e#cept level 4?!.3",. %4?!.3",. will be part
of 4?'' as of PHP D.G-
Aow lets create a function to handle errors$
function custom4rror%>errno, >errstr-
S
echo /7b94rror$75b9 U>errnoV >errstr7br 59/;
echo /4nding !cript/;
die%-;
T
.he code above is a simple error handling function. When it is triggered, it gets the error level and an
error message. "t then outputs the error level and message and terminates the script.
Aow that we have created an error handling function we need to decide when it should be triggered.
Set 0rror Handler
.he default error handler for PHP is the built in error handler. We are going to make 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 some errors, that way the script can handle
different errors in different ways. However, in this e#ample we are going to use our custom error
handler for all errors$
set?error?handler%/custom4rror/-;
!ince we want our custom function to handle all errors, the set?error?handler%- only needed one
parameter, a second parameter could be added to specify an error level.
0xa&ple
.esting the error handler by trying to output variable that does not e#ist$
78php
55error handler function
function custom4rror%>errno, >errstr-
S
echo /7b94rror$75b9 U>errnoV >errstr/;
T
55set error handler
set?error?handler%/custom4rror/-;
55trigger error
echo%>test-;
89
.he output of the code above should be something like this$
0rror$ UOV 1ndefined variable$ test
M.E. CSE (WP)2010-2012 Web Technology Page
27 of 37
(ri))er an 0rror
"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 trigger?error%- function.
0xa&ple
"n this e#ample an error occurs if the /test/ variable is bigger than /C/$
78php
>test@I;
if %>test9C-
S
trigger?error%/=alue must be C or below/-;
T
89
.he output of the code above should be something like this$
#otice$ =alue must be C or below
in %$>web,older>test2php on line ?
n error can be triggered anywhere you wish in a script, and by adding a second parameter, you can
specify what error level is triggered.
Possible error types$
4?1!43?433(3 - 2atal user-generated run-time error. 4rrors that can not be recovered from.
4#ecution of the script is halted
4?1!43?W3A"A) - Aon-fatal user-generated run-time warning. 4#ecution of the script is not halted
4?1!43?A(.",4 - *efault. 1ser-generated run-time notice. .he script found something that might be
an error, but could also happen when running a script normally
0xa&ple
"n this e#ample an 4?1!43?W3A"A) occurs if the /test/ variable is bigger than /C/. "f an
4?1!43?W3A"A) occurs we will use our custom error handler and end the script$
78php
55error handler function
function custom4rror%>errno, >errstr-
S
echo /7b94rror$75b9 U>errnoV >errstr7br 59/;
echo /4nding !cript/;
die%-;
T
55set error handler
set?error?handler%/custom4rror/,4?1!43?W3A"A)-;
55trigger error
>test@I;
if %>test9C-
S
trigger?error%/=alue must be C or below/,4?1!43?W3A"A)-;
T
89
.he output of the code above should be something like this$
0rror$ UMCIV =alue must be C or below
4nding !cript
Aow that we have learned to create our own errors and how to trigger them, lets take a look at error
logging.
M.E. CSE (WP)2010-2012 Web Technology Page
28 of 37
0rror Lo))in)
+y default, PHP sends an error log to the servers logging system or a file, depending on how the
error?log configuration is set in the php.ini file. +y using the error?log%- function you can send error
logs to a specified file or a remote destination.
!ending errors messages to yourself by e-mail can be a good way of getting notified of specific
errors.
Send an 0rror Messa)e by 06Mail
"n the e#ample below we will send an e-mail with an error message and end the script, if a specific
error occurs$
78php
55error handler function
function custom4rror%>errno, >errstr-
S
echo /7b94rror$75b9 U>errnoV >errstr7br 59/;
echo /Webmaster has been notified/;
error?log%/4rror$ U>errnoV >errstr/,C,
/someone[e#ample.com/,/2rom$ webmaster[e#ample.com/-;
T
55set error handler
set?error?handler%/custom4rror/,4?1!43?W3A"A)-;
55trigger error
>test@I;
if %>test9C-
S
trigger?error%/=alue must be C or below/,4?1!43?W3A"A)-;
T
89
.he output of the code above should be something like this$
0rror$ UMCIV =alue must be C or below
Webmaster has been notified
nd the mail received from the code above looks like this$
4rror$ UMCIV =alue must be C or below
.his should not be used with all errors. 3egular errors should be logged on the server using the
default PHP logging system.
PHP 0xception Handlin)
4#ceptions are used to change the normal flow of a script if a specified error occurs
What is an 0xception
With PHP M came a new ob:ect oriented way of dealing with errors.
4#ception handling is used to change the normal flow of the code e#ecution if a specified error
%e#ceptional- condition occurs. .his condition is called an e#ception.
.his is what normally happens when an e#ception is triggered$
.he current code state is saved
.he code e#ecution will switch to a predefined %custom- e#ception handler function
*epending on the situation, the handler may then resume the e#ecution from the saved code state,
terminate the script e#ecution or continue the script from a different location in the code
We will show different error handling methods$
+asic use of 4#ceptions
,reating a custom e#ception handler
M.E. CSE (WP)2010-2012 Web Technology Page
29 of 37
Multiple e#ceptions
3e-throwing an e#ception
!etting a top level e#ception handler
#ote$ 4#ceptions should only be used with error conditions, and should not be used to :ump to
another place in the code at a specified point.
asic 7se o, 0xceptions
When an e#ception is thrown, the code following it will not be e#ecuted, and PHP will try to find the
matching /catch/ block.
"f an e#ception is not caught, a fatal error will be issued with an /1ncaught 4#ception/ message.
'ets try to throw an e#ception without catching it$
78php
55create function with an e#ception
function checkAum%>number-
S
if%>number9C-
S
throw new 4#ception%/=alue must be C or below/-;
T
return true;
T
55trigger e#ception
checkAum%I-;
89
.he code above will get an error like this$
Fatal error$ 1ncaught e#ception '4#ception'
with message '=alue must be C or below' in ,$ZwebfolderZtest.php$D
!tack trace$ \G ,$ZwebfolderZtest.php%CI-$
checkAum%IO- \C SmainT thrown in %$>web,older>test2php on line ?
(ry@ throw and catch
.o avoid the error from the e#ample above, we need to create the proper code to handle an
e#ception.
Proper e#ception code should include$
C. .ry - function using an e#ception should be in a /try/ block. "f the e#ception does not trigger, the code
will continue as normal. However if the e#ception triggers, an e#ception is /thrown/
I. .hrow - .his is how you trigger an e#ception. 4ach /throw/ must have at least one /catch/
0. ,atch - /catch/ block retrieves an e#ception and creates an ob:ect containing the e#ception
information
'ets try to trigger an e#ception with valid code$
78php
55create function with an e#ception
function checkAum%>number-
S
if%>number9C-
S
throw new 4#ception%/=alue must be C or below/-;
T
return true;
T
55trigger e#ception in a /try/ block
try
S
M.E. CSE (WP)2010-2012 Web Technology Page
30 of 37
checkAum%I-;
55"f the e#ception is thrown, this te#t will not be shown
echo '"f you see this, the number is C or below';
T
55catch e#ception
catch%4#ception >e-
S
echo 'Message$ ' .>e-9getMessage%-;
T
89
.he code above will get an error like this$
Message$ =alue must be C or below
0xa&ple explained$
.he code above throws an e#ception and catches it$
C. .he checkAum%- function is created. "t checks if a number is greater than C. "f it is, an e#ception is
thrown
I. .he checkAum%- function is called in a /try/ block
0. .he e#ception within the checkAum%- function is thrown
L. .he /catch/ block retrives the e#ception and creates an ob:ect %>e- containing the e#ception information
M. .he error message from the e#ception is echoed by calling >e-9getMessage%- from the e#ception
ob:ect
However, one way to get around the /every throw must have a catch/ rule is to set a top level
e#ception handler to handle errors that slip through.
%reatin) a %*sto& 0xception %lass
,reating a custom e#ception handler is 6uite simple. We simply create a special class with functions
that can be called when an e#ception occurs in PHP. .he class must be an e#tension of the e#ception
class.
.he custom e#ception class inherits the properties from PHP's e#ception class and you can add
custom functions to it.
'ets create an e#ception class$
78php
class custom4#ception e#tends 4#ception
S
public function errorMessage%-
S
55error message
>errorMsg @ '4rror on line '.>this-9get'ine%-.' in '.>this-9get2ile%-
.'$ 7b9'.>this-9getMessage%-.'75b9 is not a valid 4-Mail address';
return >errorMsg;
T
T
>email @ /someone[e#ample...com/;
try
S
55check if
if%filter?var%>email, 2"'.43?='"*.4?4M"'- @@@ 2'!4-
S
55throw e#ception if email is not valid
throw new custom4#ception%>email-;
T
M.E. CSE (WP)2010-2012 Web Technology Page
31 of 37
T
catch %custom4#ception >e-
S
55display custom message
echo >e-9errorMessage%-;
T
89
.he new class is a copy of the old e#ception class with an addition of the errorMessage%- function.
!ince it is a copy of the old class, and it inherits the properties and methods from the old class, we
can use the e#ception class methods like get'ine%- and get2ile%- and getMessage%-.
0xa&ple explained$
.he code above throws an e#ception and catches it with a custom e#ception class$
C. .he custom4#ception%- class is created as an e#tension of the old e#ception class. .his way it inherits
all methods and properties from the old e#ception class
I. .he errorMessage%- function is created. .his function returns an error message if an e-mail address is
invalid
0. .he >email variable is set to a string that is not a valid e-mail address
L. .he /try/ block is e#ecuted and an e#ception is thrown since the e-mail address is invalid
M. .he /catch/ block catches the e#ception and displays the error message
M*ltiple 0xceptions
"t is possible for a script to use multiple e#ceptions to check for multiple conditions.
"t is possible to use several if..else blocks, a switch, or nest multiple e#ceptions. .hese e#ceptions
can use different e#ception classes and return different error messages$
78php
class custom4#ception e#tends 4#ception
S
public function errorMessage%-
S
55error message
>errorMsg @ '4rror on line '.>this-9get'ine%-.' in '.>this-9get2ile%-
.'$ 7b9'.>this-9getMessage%-.'75b9 is not a valid 4-Mail address';
return >errorMsg;
T
T
>email @ /someone[e#ample.com/;
try
S
55check if
if%filter?var%>email, 2"'.43?='"*.4?4M"'- @@@ 2'!4-
S
55throw e#ception if email is not valid
throw new custom4#ception%>email-;
T
55check for /e#ample/ in mail address
if%strpos%>email, /e#ample/- B@@ 2'!4-
S
throw new 4#ception%/>email is an e#ample e-mail/-;
T
T
M.E. CSE (WP)2010-2012 Web Technology Page
32 of 37
catch %custom4#ception >e-
S
echo >e-9errorMessage%-;
T
catch%4#ception >e-
S
echo >e-9getMessage%-;
T
89
0xa&ple explained$
.he code above tests two conditions and throws an e#ception if any of the conditions are not met$
C. .he custom4#ception%- class is created as an e#tension of the old e#ception class. .his way it inherits
all methods and properties from the old e#ception class
I. .he errorMessage%- function is created. .his function returns an error message if an e-mail address is
invalid
0. .he >email variable is set to a string that is a valid e-mail address, but contains the string /e#ample/
L. .he /try/ block is e#ecuted and an e#ception is not thrown on the first condition
M. .he second condition triggers an e#ception since the e-mail contains the string /e#ample/
D. .he /catch/ block catches the e#ception and displays the correct error message
"f there was no custom4#ception catch, only the base e#ception catch, the e#ception would be
handled there
+e6throwin) 0xceptions
!ometimes, when an e#ception is thrown, you may wish to handle it differently than the standard way.
"t is possible to throw an e#ception a second time within a /catch/ block.
script should hide system errors from users. !ystem errors may be important for the coder, but is of
no interest to the user. .o make things easier for the user you can re-throw the e#ception with a user
friendly message$
78php
class custom4#ception e#tends 4#ception
S
public function errorMessage%-
S
55error message
>errorMsg @ >this-9getMessage%-.' is not a valid 4-Mail address.';
return >errorMsg;
T
T
>email @ /someone[e#ample.com/;
try
S
try
S
55check for /e#ample/ in mail address
if%strpos%>email, /e#ample/- B@@ 2'!4-
S
55throw e#ception if email is not valid
throw new 4#ception%>email-;
T
T
catch%4#ception >e-
M.E. CSE (WP)2010-2012 Web Technology Page
33 of 37
S
55re-throw e#ception
throw new custom4#ception%>email-;
T
T
catch %custom4#ception >e-
S
55display custom message
echo >e-9errorMessage%-;
T
89
0xa&ple explained$
.he code above tests if the email-address contains the string /e#ample/ in it, if it does, the e#ception
is re-thrown$
C. .he custom4#ception%- class is created as an e#tension of the old e#ception class. .his way it inherits
all methods and properties from the old e#ception class
I. .he errorMessage%- function is created. .his function returns an error message if an e-mail address is
invalid
0. .he >email variable is set to a string that is a valid e-mail address, but contains the string /e#ample/
L. .he /try/ block contains another /try/ block to make it possible to re-throw the e#ception
M. .he e#ception is triggered since the e-mail contains the string /e#ample/
D. .he /catch/ block catches the e#ception and re-throws a /custom4#ception/
J. .he /custom4#ception/ is caught and displays an error message
"f the e#ception is not caught in its current /try/ block, it will search for a catch block on /higher
levels/.
Set a (op Level 0xception Handler
.he set?e#ception?handler%- function sets a user-defined function to handle all uncaught e#ceptions.
78php
function my4#ception%>e#ception-
S
echo /7b94#ception$75b9 / , >e#ception-9getMessage%-;
T
set?e#ception?handler%'my4#ception'-;
throw new 4#ception%'1ncaught 4#ception occurred'-;
89
.he output of the code above should be something like this$
0xception$ 1ncaught 4#ception occurred
"n the code above there was no /catch/ block. "nstead, the top level e#ception handler triggered. .his
function should be used to catch uncaught e#ceptions.
+*les ,or exceptions
,ode may be surrounded in a try block, to help catch potential e#ceptions
4ach try block or /throw/ must have at least one corresponding catch block
Multiple catch blocks can be used to catch different classes of e#ceptions
4#ceptions can be thrown %or re-thrown- in a catch block within a try block
simple rule$ "f you throw something, you have to catch it.
PHP Filter
PHP filters are used to validate and filter data coming from insecure sources, like user input.
M.E. CSE (WP)2010-2012 Web Technology Page
34 of 37
What is a PHP Filter?
PHP filter is used to validate and filter data coming from insecure sources.
.o test, validate and filter user input or custom data is an important part of any web application.
.he PHP filter e#tension is designed to make data filtering easier and 6uicker.
Why *se a Filter?
lmost all web applications depend on e#ternal input. 1sually this comes from a user or another
application %like a web service-. +y using filters you can be sure your application gets the correct input
type.
Ao* sho*ld always ,ilter all external dataB
"nput filtering is one of the most important application security issues.
What is e#ternal data8
"nput data from a form
,ookies
Web services data
!erver variables
*atabase 6uery results
F*nctions and Filters
.o filter a variable, use one of the following filter functions$
filter?var%- - 2ilters a single variable with a specified filter
filter?var?array%- - 2ilter several variables with the same or different filters
filter?input - )et one input variable and filter it
filter?input?array - )et several input variables and filter them with the same or different filters
"n the e#ample below, we validate an integer using the filter?var%- function$
78php
>int @ CI0;
if%Bfilter?var%>int, 2"'.43?='"*.4?"A.--
S
echo%/"nteger is not valid/-;
T
else
S
echo%/"nteger is valid/-;
T
89
.he code above uses the /2"'.43?='"*.4?"A./ filter to filter the variable. !ince the integer is
valid, the output of the code above will be$ /"nteger is valid/.
"f we try with a variable that is not an integer %like /CI0abc/-, the output will be$ /"nteger is not valid/.
'alidatin) and SanitiCin)
.here are two kinds of filters$
=alidating filters$
re used to validate user input
!trict format rules %like 13' or 4-Mail validating-
3eturns the e#pected type on success or 2'!4 on failure
!anitiEing filters$
re used to allow or disallow specified characters in a string
Ao data format rules
lways return the string
M.E. CSE (WP)2010-2012 Web Technology Page
35 of 37
-ptions 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#ample below, we validate an integer using the filter?var%- and the /min?range/ and
/ma#?range/ options$
78php
>var@0GG;
>int?options @ array%
/options/@9array
%
/min?range/@9G,
/ma#?range/@9IMD
-
-;
if%Bfilter?var%>var, 2"'.43?='"*.4?"A., >int?options--
S
echo%/"nteger is not valid/-;
T
else
S
echo%/"nteger is valid/-;
T
89
'ike the code above, options must be put in an associative array with the name /options/. "f a flag is
used it does not need to be in an array.
!ince the integer is /0GG/ it is not in the specified range, and the output of the code above will be$
/"nteger is not valid/.
'alidate 1np*t
'et's try validating input from a form.
.he first thing we need to do is to confirm that the input data we are looking for e#ists.
.hen we filter the input data using the filter?input%- function.
"n the e#ample below, the input variable /email/ is sent to the PHP page$
78php
if%Bfilter?has?var%"AP1.?)4., /email/--
S
echo%/"nput type does not e#ist/-;
T
else
S
if %Bfilter?input%"AP1.?)4., /email/, 2"'.43?='"*.4?4M"'--
S
echo /4-Mail is not valid/;
T
else
S
echo /4-Mail is valid/;
T
T
89
M.E. CSE (WP)2010-2012 Web Technology Page
36 of 37
0xa&ple 0xplained
.he e#ample above has an input %email- sent to it using the /)4./ method$
C. ,heck if an /email/ input variable of the /)4./ type e#ist
I. "f the input variable e#ists, check if it is a valid e-mail address
SanitiCe 1np*t
'et's try cleaning up an 13' sent from a form.
2irst we confirm that the input data we are looking for e#ists.
.hen we sanitiEe the input data using the filter?input%- function.
"n the e#ample below, the input variable /url/ is sent to the PHP page$
78php
if%Bfilter?has?var%"AP1.?P(!., /url/--
S
echo%/"nput type does not e#ist/-;
T
else
S
>url @ filter?input%"AP1.?P(!.,
/url/, 2"'.43?!A"."F4?13'-;
T
89
0xa&ple 0xplained
.he e#ample above has an input %url- sent to it using the /P(!./ method$
C. ,heck if the /url/ input of the /P(!./ type e#ists
I. "f the input variable e#ists, sanitiEe %take away invalid characters- and store it in the >url variable
"f the input variable is a string like this /http$55www.!athyabama.com5/, the >url variable after the
sanitiEing will look like this$
http$55www.!athyabama.com5
Filter M*ltiple 1np*ts
form almost always consist of more than one input field. .o avoid calling the filter?var or filter?input
functions over and over, we can use the filter?var?array or the filter?input?array functions.
"n this e#ample we use the filter?input?array%- function to filter three )4. variables. .he received
)4. variables is a name, an age and an e-mail address$
78php
>filters @ array
%
/name/ @9 array
%
/filter/@92"'.43?!A"."F4?!.3"A)
-,
/age/ @9 array
%
/filter/@92"'.43?='"*.4?"A.,
/options/@9array
%
/min?range/@9C,
/ma#?range/@9CIG
-
-,
/email/@9 2"'.43?='"*.4?4M"',
-;
M.E. CSE (WP)2010-2012 Web Technology Page
37 of 37
>result @ filter?input?array%"AP1.?)4., >filters-;
if %B>resultU/age/V-
S
echo%/ge must be a number between C and CIG.7br 59/-;
T
elseif%B>resultU/email/V-
S
echo%/4-Mail is not valid.7br 59/-;
T
else
S
echo%/1ser input is valid/-;
T
89
0xa&ple 0xplained
.he e#ample above has three inputs %name, age and email- sent to it using the /)4./ method$
C. !et an array containing the name of input variables and the filters used on the specified input variables
I. ,all the filter?input?array%- function with the )4. input variables and the array we :ust set
0. ,heck the /age/ and /email/ variables in the >result variable for invalid inputs. %"f any of the input
variables are invalid, that input variable will be 2'!4 after the filter?input?array%- function-
.he second parameter of the filter?input?array%- function can be an array or a single filter "*.
"f the parameter is a single filter "* all values in the input array are filtered by the specified filter.
"f the parameter is an array it must follow these rules$
Must be an associative array containing an input variable as an array key %like the /age/ input variable-
.he array value must be a filter "* or an array specifying the filter, flags and options
7sin) Filter %allbac3
"t is possible to call a user defined function and use it as a filter using the 2"'.43?,''+,X filter.
.his way, we have full control of the data filtering.
Rou can create your own user defined function or use an e#isting PHP function
.he function you wish to use to filter is specified the same way as an option is specified. "n an
associative array with the name /options/
"n the e#ample below, we use a user created function to convert all /?/ to whitespaces$
78php
function convert!pace%>string-
S
return str?replace%/?/, / /, >string-;
T
>string @ /Peter?is?a?great?guyB/;
echo filter?var%>string, 2"'.43?,''+,X,
array%/options/@9/convert!pace/--;
89
.he result from the code above should look like this$
Peter is a great guyB
0xa&ple 0xplained
.he e#ample above converts all /?/ to whitespaces$
C. ,reate a function to replace /?/ to whitespaces
I. ,all the filter?var%- function with the 2"'.43?,''+,X filter and an array containing our function

Vous aimerez peut-être aussi