You are on page 1of 187

Tutorial PHP by www.w3schools.

com
Organized by Nur Dwi Muryanto, 2!
PHP Tutorial
PHP Tutorial
PHP is a powerful server-side scripting language for creating
dynamic and interactive websites.
PHP is the widely-used, free, and efficient alternative to
competitors such as Microsoft's AP. PHP is perfectly suited for
!eb development and can be embedded directly into the HTM"
code.
The PHP synta# is very similar to Perl and $. PHP is often used
together with Apache %web server& on various operating systems.
't also supports 'AP' and can be used with Microsoft's '' on
!indows.
tart learning PHP now(
PHP )eferences
At W3Schools you will find complete references of all PHP functions:
Array functions
Calendar functions
Date functions
Directory functions
Error functions
Filesystem functions
Filter functions
FTP functions
HTTP functions
i!"# functions
#ail functions
#ath functions
#isc functions
#yS$ functions
Simple"# functions
Strin% functions
"# Parser functions
Page 1 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
&ip functions
'ntroduction to PHP
PHP is a ser'er(side scriptin% lan%ua%e)
!hat *ou hould Already +now
*efore you continue you should ha'e a !asic understandin% of the followin%:
HT#
Some scriptin% +nowled%e
,f you want to study these su!-ects first. find the tutorials on our Home pa%e)
!hat is PHP,
PHP stands for PHP: Hyperte/t Preprocessor
PHP is a ser'er(side scriptin% lan%ua%e. li+e ASP
PHP scripts are e/ecuted on the ser'er
PHP supports many data!ases 0#yS$. ,nformi/. 1racle. Sy!ase. Solid.
Post%reS$. 2eneric 1D*C. etc)3
PHP is an open source software
PHP is free to download and use
!hat is a PHP -ile,
PHP files can contain te/t. HT# ta%s and scripts
PHP files are returned to the !rowser as plain HT#
PHP files ha'e a file e/tension of 4)php4. 4)php34. or 4)phtml4
!hat is My.",
#yS$ is a data!ase ser'er
#yS$ is ideal for !oth small and lar%e applications
#yS$ supports standard S$
#yS$ compiles on a num!er of platforms
#yS$ is free to download and use
PHP / My."
PHP com!ined with #yS$ are cross(platform 0you can de'elop in
Windows and ser'e on a 5ni/ platform3
!hy PHP,
PHP runs on different platforms 0Windows. inu/. 5ni/. etc)3
PHP is compati!le with almost all ser'ers used today 0Apache. ,,S. etc)3
PHP is F6EE to download from the official PHP resource: www)php)net
Page 2 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
PHP is easy to learn and runs efficiently on the ser'er side
!here to tart,
To %et access to a we! ser'er with PHP support. you can:
,nstall Apache 0or ,,S3 on your own ser'er. install PHP. and #yS$
1r find a we! hostin% plan with PHP and #yS$ support
PHP 'nstallation
!hat do *ou 0eed,
,f your ser'er supports PHP you don7t need to do anythin%) 8ust create some )php
files in your we! directory. and the ser'er will parse them for you) *ecause it is
free. most we! hosts offer PHP support)
Howe'er. if your ser'er does not support PHP. you must install PHP)
Here is a lin+ to a %ood tutorial from PHP)net on how to install PHP9:
http:::www)php)net:manual:en:install)php
1ownload PHP
Download PHP for free here: http:::www)php)net:downloads)php
1ownload My." 1atabase
Download #yS$ for free here: http:::www)mys;l)com:downloads:inde/)html
1ownload Apache erver
Download Apache for free here: http:::httpd)apache)or%:download)c%i
Page 3 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
PHP ynta#
PHP code is e/ecuted on the ser'er. and the plain HT# result is sent to the
!rowser)
2asic PHP ynta#
A PHP scriptin% !loc+ always starts with 3,php and ends with ,4) A PHP scriptin%
!loc+ can !e placed anywhere in the document)
1n ser'ers with shorthand support ena!led you can start a scriptin% !loc+ with <=
and end with =>)
For ma/imum compati!ility. we recommend that you use the standard form 0<=php3
rather than the shorthand form)
<?php
?>
A PHP file normally contains HT# ta%s. -ust li+e an HT# file. and some PHP
scriptin% code)
*elow. we ha'e an e/ample of a simple PHP script which sends the te/t 4Hello
World4 to the !rowser:
<html>
<body>
<?php
echo "Hello World";
?>
</body>
</html>
Each code line in PHP must end with a semicolon) The semicolon is a separator and
is used to distin%uish one set of instructions from another)
There are two !asic statements to output te/t with PHP: echo and print) ,n the
e/ample a!o'e we ha'e used the echo statement to output the te/t 4Hello World4)
0ote5 The file must ha'e the )php e/tension) ,f the file has a )html e/tension. the
PHP code will not !e e/ecuted)
Page 4 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
$omments in PHP
,n PHP. we use :: to ma+e a sin%le(line comment or :? and ?: to ma+e a lar%e
comment !loc+)
<html>
<body>
<?php
//This is a comment
/*
This is
a comment
block
*/
?>
</body>
</html>
PHP 6ariables
@aria!les are used for storin% 'alues. such as num!ers. strin%s or function results. so
that they can !e used many times in a script)
6ariables in PHP
@aria!les are used for storin% a 'alues. li+e te/t strin%s. num!ers or arrays)
When a 'aria!le is set it can !e used o'er and o'er a%ain in your script
All 'aria!les in PHP start with a A si%n sym!ol)
The correct way of settin% a 'aria!le in PHP:
$var_name val!e;
Bew PHP pro%rammers often for%et the A si%n at the !e%innin% of the 'aria!le) ,n
that case it will not wor+)
et7s try creatin% a 'aria!le with a strin%. and a 'aria!le with a num!er:
Page 5 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
<?php
$t"t "Hello World#";
$n!mber $%;
?>
PHP is a "oosely Typed "anguage
,n PHP a 'aria!le does not need to !e declared !efore !ein% set)
,n the e/ample a!o'e. you see that you do not ha'e to tell PHP which data type the
'aria!le is)
PHP automatically con'erts the 'aria!le to the correct data type. dependin% on how
they are set)
,n a stron%ly typed pro%rammin% lan%ua%e. you ha'e to declare 0define3 the type
and name of the 'aria!le !efore usin% it)
,n PHP the 'aria!le is declared automatically when you use it)
6ariable 0aming )ules
A 'aria!le name must start with a letter or an underscore 4C4
A 'aria!le name can only contain alpha(numeric characters and underscores
0a(D. A(&. E(F. and C 3
A 'aria!le name should not contain spaces) ,f a 'aria!le name is more than
one word. it should !e separated with underscore 0AmyCstrin%3. or with
capitaliDation 0AmyStrin%3
PHP tring
A strin% 'aria!le is used to store and manipulate a piece of te/t)
trings in PHP
Strin% 'aria!les are used for 'alues that contains character strin%s)
,n this tutorial we are %oin% to loo+ at some of the most common functions and
operators used to manipulate strin%s in PHP)
After we create a strin% we can manipulate it) A strin% can !e used directly in a
function or it can !e stored in a 'aria!le)
Page 6 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
*elow. the PHP script assi%ns the strin% 4Hello World4 to a strin% 'aria!le called
At/t:
<?php
$t"t"Hello World";
echo $t"t;
?>
The output of the code a!o'e will !e:
Hello World
Bow. lets try to use some different functions and operators to manipulate our strin%)
The $oncatenation 7perator
There is only one strin% operator in PHP)
The concatenation operator 0)3 is used to put two strin% 'alues to%ether)
To concatenate two 'aria!les to%ether. use the dot 0)3 operator:
<?php
$t"t$"Hello World";
$t"t&"$&'(";
echo $t"t$ ) " " ) $t"t&;
?>
The output of the code a!o'e will !e:
Hello World $&'(
,f we loo+ at the code a!o'e you see that we used the concatenation operator two
times) This is !ecause we had to insert a third strin%)
*etween the two strin% 'aria!les we added a strin% with a sin%le character. an
empty space. to separate the two 'aria!les)
8sing the strlen%& function
The strlen03 function is used to find the len%th of a strin%)
et7s find the len%th of our strin% 4Hello worldG4:
<?php
echo strlen*"Hello +orld#",;
Page 7 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
?>
The output of the code a!o'e will !e:
$&
The len%th of a strin% is often used in loops or other functions. when it is important
to +now when the strin% ends) 0i)e) in a loop. we would want to stop the loop after
the last character in the strin%3
8sing the strpos%& function
The strpos03 function is used to search for a strin% or character within a strin%)
,f a match is found in the strin%. this function will return the position of the first
match) ,f no match is found. it will return FASE)
et7s see if we can find the strin% 4world4 in our strin%:
<?php
echo strpos*"Hello +orld#"-"+orld",;
?>
The output of the code a!o'e will !e:
%
As you see the position of the strin% 4world4 in our strin% is position H) The reason
that it is H. and not I. is that the first position in the strin% is E. and not J)
$omplete PHP tring )eference
For a complete reference of all strin% functions. %o to our complete PHP Strin%
6eference)
The reference contains a !rief description and e/amples of use for each functionG
PHP 7perators
Page 8 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
1perators are used to operate on 'alues)
PHP 7perators
This section lists the different operators used in PHP)
Arithmetic 7perators
7perator 1escription 9#ample )esult
K Addition /LM
/KM
N
( Su!traction /LM
9(/
3
? #ultiplication /LN
/?9
ME
: Di'ision J9:9
9:M
3
M)9
O #odulus 0di'ision remainder3 9OM
JEOP
JEOM
J
M
E
KK ,ncrement /L9
/KK
/LH
(( Decrement /L9
/((
/LN
Assignment 7perators
7perator 9#ample 's The ame As
L /Ly /Ly
KL /KLy /L/Ky
(L /(Ly /L/(y
?L /?Ly /L/?y
:L /:Ly /L/:y
)L /)Ly /L/)y 0%a!un%in -adi /yQ !isa !uat %enerate +ey3
OL /OLy /L/Oy
$omparison 7perators
Page 9 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
7perator 1escription 9#ample
LL is e;ual to 9LLP returns false
GL is not e;ual 9GLP returns true
> is %reater than 9>P returns false
< is less than 9<P returns true
>L is %reater than or e;ual to 9>LP returns false
<L is less than or e;ual to 9<LP returns true
"ogical 7perators
7perator 1escription 9#ample
RR and /LH
yL3
0/ < JE RR y > J3 returns true
SS or /LH
yL3
0/LL9 SS yLL93 returns false
G not /LH
yL3
G0/LLy3 returns true
PHP 'f...9lse tatements
The if. elseif and else statements in PHP are used to perform different actions !ased
on different conditions)
$onditional tatements
@ery often when you write code. you want to perform different actions for different
decisions)
Tou can use conditional statements in your code to do this)
if...else statement " use this statement i# you want to e$ecute a
set o# code when a condition is true and another i# the condition is
not true
Page 10 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
elseif statement " is used with the i#...else statement to e$ecute
a set o# code i# one o# se%eral condition are true
The 'f...9lse tatement
,f you want to e/ecute some code if a condition is true and another code if a
condition is false. use the if))))else statement)
Syntax
i. *condition,
code to be executed if condition is true;
else
code to be executed if condition is false;
Example
The followin% e/ample will output 4Ha'e a nice wee+endG4 if the current day is
Friday. otherwise it will output 4Ha'e a nice dayG4:
<html>
<body>
<?php
$ddate*"/",;
i. *$d"0ri",
echo "Have a nice +eekend#";
else
echo "Have a nice day#";
?>
</body>
</html>
,f more than one line should !e e/ecuted if a condition is true:false. the lines should
!e enclosed within curly !races:
<html>
<body>
<?php
$ddate*"/",;
i. *$d"0ri",
1
echo "Hello#<br />";
echo "Have a nice +eekend#";
echo "2ee yo! on 3onday#";
4
?>
</body>
Page 11 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
</html>
The 9lse'f tatement
,f you want to e/ecute some code if one of se'eral conditions are true use the elseif
statement
Syntax
i. *condition,
code to be executed if condition is true;
elsei. *condition,
code to be executed if condition is true;
else
code to be executed if condition is false;
Example
The followin% e/ample will output 4Ha'e a nice wee+endG4 if the current day is
Friday. and 4Ha'e a nice SundayG4 if the current day is Sunday) 1therwise it will
output 4Ha'e a nice dayG4:
<html>
<body>
<?php
$ddate*"/",;
i. *$d"0ri",
echo "Have a nice +eekend#";
elsei. *$d"2!n",
echo "Have a nice 2!nday#";
else
echo "Have a nice day#";
?>
</body>
</html>
Page 12 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
PHP witch tatement
The Switch statement in PHP is used to perform one of se'eral different actions
!ased on one of se'eral different conditions)
The witch tatement
,f you want to select one of many !loc+s of code to !e e/ecuted. use the Switch
statement)
The switch statement is used to a'oid lon% !loc+s of if))elseif))else code)
Syntax
s+itch *expression,
1
case label1:
code to be executed if expression = label1;
break;
case label2:
code to be executed if expression = label2;
break;
de.a!lt5
code to be executed
if expression is different
from both label1 and label2;
4
Example
This is how it wor+s:
& single e$'ression (most o#ten a %ariable) is e%aluated once
The %alue o# the e$'ression is com'ared with the %alues #or each
case in the structure
*# there is a match, the code associated with that case is e$ecuted
&#ter a code is e$ecuted, break is used to sto' the code #rom
running into the ne$t case
The de#ault statement is used i# none o# the cases are true
<html>
<body>
<?php
s+itch *$",
1
case $5
echo "6!mber $";
break;
case &5
Page 13 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
echo "6!mber &";
break;
case '5
echo "6!mber '";
break;
de.a!lt5
echo "6o n!mber bet+een $ and '";
4
?>
</body>
</html>
PHP Arrays
An array can store one or more 'alues in a sin%le 'aria!le name)
!hat is an array,
When wor+in% with PHP. sooner or later. you mi%ht want to create many similar
'aria!les)
,nstead of ha'in% many similar 'aria!les. you can store the data as elements in an
array)
Each element in the array has its own ,D so that it can !e easily accessed)
There are three different +ind of arrays:
Numeric array " &n array with a numeric *D +ey
Associative array " &n array where each *D +ey is associated
with a %alue
Multidimensional array " &n array containing one or more
arrays
0umeric Arrays
A numeric array stores each element with a numeric ,D +ey)
There are different ways to create a numeric array)
Example 1
,n this e/ample the ,D +ey is automatically assi%ned:
Page 14 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
$names array*"7eter"-"8!a9mire"-":oe",;
Example
,n this e/ample we assi%n the ,D +ey manually:
$names;<= "7eter";
$names;$= "8!a9mire";
$names;&= ":oe";
The ,D +eys can !e used in a script:
<?php
$names;<= "7eter";
$names;$= "8!a9mire";
$names;&= ":oe";
echo $names;$= ) " and " ) $names;&= )
" are ") $names;<= ) ">s nei9hbors";
?>
The code a!o'e will output:
8!a9mire and :oe are 7eter>s nei9hbors
Associative Arrays
An associati'e array. each ,D +ey is associated with a 'alue)
When storin% data a!out specific named 'alues. a numerical array is not always the
!est way to do it)
With associati'e arrays we can use the 'alues as +eys and assi%n 'alues to them)
Example 1
,n this e/ample we use an array to assi%n a%es to the different persons:
$a9es array*"7eter">'&- "8!a9mire">'<- ":oe">'(,;
Example
This e/ample is the same as e/ample J. !ut shows a different way of creatin% the
array:
$a9es;>7eter>= "'&";
Page 15 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
$a9es;>8!a9mire>= "'<";
$a9es;>:oe>= "'(";
The ,D +eys can !e used in a script:
<?php
$a9es;>7eter>= "'&";
$a9es;>8!a9mire>= "'<";
$a9es;>:oe>= "'(";
echo "7eter is " ) $a9es;>7eter>= ) " years old)";
?>
The code a!o'e will output:
7eter is '& years old)
Multidimensional Arrays
,n a multidimensional array. each element in the main array can also !e an array)
And each element in the su!(array can !e an array. and so on)
Example
,n this e/ample we create a multidimensional array. with automatically assi%ned ,D
+eys:
$.amilies array
*
"?ri..in">array
*
"7eter"-
"@ois"-
"3e9an"
,-
"8!a9mire">array
*
"?lenn"
,-
"Aro+n">array
*
"Bleveland"-
"@oretta"-
":!nior"
,
,;
Page 16 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
The array a!o'e would loo+ li+e this if written to the output:
Crray
*
;?ri..in= > Crray
*
;<= > 7eter
;$= > @ois
;&= > 3e9an
,
;8!a9mire= > Crray
*
;<= > ?lenn
,
;Aro+n= > Crray
*
;<= > Bleveland
;$= > @oretta
;&= > :!nior
,
,
Example
ets try displayin% a sin%le 'alue from the array a!o'e:
echo "Ds " ) $.amilies;>?ri..in>=;&= )
" a part o. the ?ri..in .amily?";
The code a!o'e will output:
Ds 3e9an a part o. the ?ri..in .amily?
PHP "ooping
oopin% statements in PHP are used to e/ecute the same !loc+ of code a specified
num!er of times)
"ooping
@ery often when you write code. you want the same !loc+ of code to run a num!er
of times) Tou can use loopin% statements in your code to perform this)
Page 17 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
,n PHP we ha'e the followin% loopin% statements:
!"ile " loo's through a bloc+ o# code i# and as long as a s'eci#ied
condition is true
do...!"ile " loo's through a bloc+ o# code once, and then re'eats
the loo' as long as a s'ecial condition is true
for " loo's through a bloc+ o# code a s'eci#ied number o# times
foreac" " loo's through a bloc+ o# code #or each element in an
array
The while tatement
The while statement will e/ecute a !loc+ of code if and as long as a condition is
true)
Syntax
+hile *condition,
code to be executed;
Example
The followin% e/ample demonstrates a loop that will continue to run as lon% as the
'aria!le i is less than. or e;ual to 9) i will increase !y J each time the loop runs:
<html>
<body>
<?php
$i$;
+hile*$i<E,
1
echo "The n!mber is " ) $i ) "<br />";
$iFF;
4
?>
</body>
</html>
The do...while tatement
The do)))while statement will e/ecute a !loc+ of code at least once ( it then will
repeat the loop as long as a condition is true)
Syntax
do
1
code to be executed;
Page 18 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
4
+hile *condition,;
Example
The followin% e/ample will increment the 'alue of i at least once. and it will
continue incrementin% the 'aria!le i as lon% as it has a 'alue of less than 9:
<html>
<body>
<?php
$i<;
do
1
$iFF;
echo "The n!mber is " ) $i ) "<br />";
4
+hile *$i<E,;
?>
</body>
</html>
The for tatement
The for statement is the most ad'anced of the loops in PHP)
,n it7s simplest form. the for statement is used when you +now how many times you
want to e/ecute a statement or a list of statements)
Syntax
.or *init; cond; incr,
1
code to be executed;
4
Parameters:
init, *s mostly used to set a counter, but can be any code to
be e$ecuted once at the beginning o# the loo' statement.
cond, *s e%aluated at beginning o# each loo' iteration. *# the
condition e%aluates to T-./, the loo' continues and the
code e$ecutes. *# it e%aluates to 0&12/, the e$ecution o# the
loo' ends.
incr, *s mostly used to increment a counter, but can be any
code to be e$ecuted at the end o# each loo'.
Page 19 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
0ote5 Each of the parameters can !e empty or ha'e multiple e/pressions
separated !y commas)
cond# &ll e$'ressions se'arated by a comma are e%aluated
but the result is ta+en #rom the last 'art. This 'arameter
being em'ty means the loo' should be run inde#initely. This
is use#ul when using a conditional brea+ statement inside
the loo' #or ending the loo'.
Example
The followin% e/ample prints the te/t 4Hello WorldG4 fi'e times:
<html>
<body>
<?php
.or *$i$; $i<E; $iFF,
1
echo "Hello World#<br />";
4
?>
</body>
</html>
The foreach tatement
The foreach statement is used to loop throu%h arrays)
For e'ery loop. the 'alue of the current array element is assi%ned to A'alue 0and the
array pointer is mo'ed !y one3 ( so on the ne/t loop. you7ll !e loo+in% at the ne/t
element)
Syntax
.oreach *array as value,
1
code to be executed;
4
Example
The followin% e/ample demonstrates a loop that will print the 'alues of the %i'en
array:
<html>
<body>
<?php
Page 20 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
$arrarray*"one"- "t+o"- "three",;
.oreach *$arr as $val!e,
1
echo "Gal!e5 " ) $val!e ) "<br />";
4
?>
</body>
</html>
PHP -unctions
The real power of PHP comes from its functions)
,n PHP ( there are more than IEE !uilt(in functions a'aila!le)
PHP -unctions
,n this tutorial we will show you how to create your own functions)
For a reference and e/amples of the !uilt(in functions. please 'isit our PHP
6eference)
$reate a PHP -unction
A function is a !loc+ of code that can !e e/ecuted whene'er we need it)
Creatin% PHP functions:
&ll #unctions start with the word 3#unction()3
Name the #unction " *t should be 'ossible to understand
what the #unction does by its name. The name can start
with a letter or underscore (not a number)
&dd a 343 " The #unction code starts a#ter the o'ening curly
brace
*nsert the #unction code
&dd a 353 " The #unction is #inished by a closing curly brace
Example
A simple function that writes my name when it is called:
<html>
<body>
<?php
.!nction +rite3y6ame*,
Page 21 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
1
echo "Hai :im Ie.snes";
4
+rite3y6ame*,;
?>
</body>
</html>
8se a PHP -unction
Bow we will use the function in a PHP script:
<html>
<body>
<?php
.!nction +rite3y6ame*,
1
echo "Hai :im Ie.snes";
4
echo "Hello +orld#<br />";
echo "3y name is ";
+rite3y6ame*,;
echo ")<br />That>s ri9ht- ";
+rite3y6ame*,;
echo " is my name)";
?>
</body>
</html>
The output of the code a!o'e will !e:
Hello +orld#
3y name is Hai :im Ie.snes)
That>s ri9ht- Hai :im Ie.snes is my name)
PHP -unctions - Adding parameters
1ur first function 0write#yBame033 is a 'ery simple function) ,t only writes a static
strin%)
To add more functionality to a function. we can add parameters) A parameter is -ust
li+e a 'aria!le)
Tou may ha'e noticed the parentheses after the function name. li+e:
write#yBame03) The parameters are specified inside the parentheses)
Page 22 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
Example 1
The followin% e/ample will write different first names. !ut the same last name:
<html>
<body>
<?php
.!nction +rite3y6ame*$.name,
1
echo $.name ) " Ie.snes)<br />";
4
echo "3y name is ";
+rite3y6ame*"Hai :im",;
echo "3y name is ";
+rite3y6ame*"He9e",;
echo "3y name is ";
+rite3y6ame*"2tale",;
?>
</body>
</html>
The output of the code a!o'e will !e:
3y name is Hai :im Ie.snes)
3y name is He9e Ie.snes)
3y name is 2tale Ie.snes)
Example
The followin% function has two parameters:
<html>
<body>
<?php
.!nction +rite3y6ame*$.name-$p!nct!ation,
1
echo $.name ) " Ie.snes" ) $p!nct!ation ) "<br />";
4
echo "3y name is ";
+rite3y6ame*"Hai :im"-")",;
echo "3y name is ";
+rite3y6ame*"He9e"-"#",;
echo "3y name is ";
+rite3y6ame*"2tJle"-")))",;
?>
</body>
</html>
Page 23 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
The output of the code a!o'e will !e:
3y name is Hai :im Ie.snes)
3y name is He9e Ie.snes#
3y name is 2tJle Ie.snes)))
PHP -unctions - )eturn values
Functions can also !e used to return 'alues)
Example
<html>
<body>
<?php
.!nction add*$"-$y,
1
$total $" F $y;
ret!rn $total;
4
echo "$ F $% " ) add*$-$%,;
?>
</body>
</html>
The output of the code a!o'e will !e:
$ F $% $K
PHP -orms and 8ser 'nput
The PHP AC2ET and ACP1ST 'aria!les are used to retrie'e information from
forms. li+e user input)
PHP -orm Handling
The most important thin% to notice when dealin% with HT# forms and PHP is that
any form element in an HT# pa%e will automatically !e a'aila!le to your PHP
scripts)
-orm e#ample5
Page 24 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
<html>
<body>
<.orm action"+elcome)php" method"post">
6ame5 <inp!t type"te"t" name"name" />
C9e5 <inp!t type"te"t" name"a9e" />
<inp!t type"s!bmit" />
</.orm>
</body>
</html>
The e/ample HT# pa%e a!o'e contains two input fields and a su!mit !utton)
When the user fills in this form and clic+ on the su!mit !utton. the form data is sent
to the 4welcome)php4 file)
The 4welcome)php4 file loo+s li+e this:
<html>
<body>
Welcome <?php echo $_7L2T;"name"=; ?>)<br />
Mo! are <?php echo $_7L2T;"a9e"=; ?> years old)
</body>
</html>
A sample output of the a!o'e script may !e:
Welcome :ohn)
Mo! are &N years old)
The PHP AC2ET and ACP1ST 'aria!les will !e e/plained in the ne/t chapters)
-orm 6alidation
5ser input should !e 'alidated whene'er possi!le) Client side 'alidation is faster.
and will reduce ser'er load)
Howe'er. any site that %ets enou%h traffic to worry a!out ser'er resources. may also
need to worry a!out site security) Tou should always use ser'er side 'alidation if the
form accesses a data!ase)
A %ood way to 'alidate a form on the ser'er is to post the form to itself. instead of
-umpin% to a different pa%e) The user will then %et the error messa%es on the same
pa%e as the form) This ma+es it easier to disco'er the error)
Page 25 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
PHP :;<9T
The AC2ET 'aria!le is used to collect 'alues from a form with methodL4%et4)
The :;<9T 6ariable
The AC2ET 'aria!le is an array of 'aria!le names and 'alues sent !y the HTTP
2ET method)
The AC2ET 'aria!le is used to collect 'alues from a form with methodL4%et4)
,nformation sent from a form with the 2ET method is 'isi!le to e'eryone 0it will !e
displayed in the !rowser7s address !ar3 and it has limits on the amount of
information to send 0ma/) JEE characters3)
Example
<.orm action"+elcome)php" method"9et">
6ame5 <inp!t type"te"t" name"name" />
C9e5 <inp!t type"te"t" name"a9e" />
<inp!t type"s!bmit" />
</.orm>
When the user clic+s the 4Su!mit4 !utton. the 56 sent could loo+ somethin% li+e
this:
http5//+++)+'schools)com/+elcome)php?name7eterOa9e'K
The 4welcome)php4 file can now use the AC2ET 'aria!le to catch the form data
0notice that the names of the form fields will automatically !e the ,D +eys in the
AC2ET array3:
Welcome <?php echo $_?PT;"name"=; ?>)<br />
Mo! are <?php echo $_?PT;"a9e"=; ?> years old#
!hy use :;<9T,
0ote5 When usin% the AC2ET 'aria!le all 'aria!le names and 'alues are displayed
in the 56) So this method should not !e used when sendin% passwords or other
sensiti'e informationG Howe'er. !ecause the 'aria!les are displayed in the 56. it
is possi!le to !oo+mar+ the pa%e) This can !e useful in some cases)
Page 26 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
0ote5 The HTTP 2ET method is not suita!le on lar%e 'aria!le 'aluesQ the 'alue
cannot e/ceed JEE characters)
The :;)9.89T 6ariable
The PHP AC6E$5EST 'aria!le contains the contents of !oth AC2ET. ACP1ST. and
ACC11U,E)
The PHP AC6E$5EST 'aria!le can !e used to %et the result from form data sent
with !oth the 2ET and P1ST methods)
Example
Welcome <?php echo $_IP8QP2T;"name"=; ?>)<br />
Mo! are <?php echo $_IP8QP2T;"a9e"=; ?> years old#
PHP :;P7T
The ACP1ST 'aria!le is used to collect 'alues from a form with methodL4post4)
The :;P7T 6ariable
The ACP1ST 'aria!le is an array of 'aria!le names and 'alues sent !y the HTTP
P1ST method)
The ACP1ST 'aria!le is used to collect 'alues from a form with methodL4post4)
,nformation sent from a form with the P1ST method is in'isi!le to others and has
no limits on the amount of information to send)
Example
<.orm action"+elcome)php" method"post">
Pnter yo!r name5 <inp!t type"te"t" name"name" />
Pnter yo!r a9e5 <inp!t type"te"t" name"a9e" />
<inp!t type"s!bmit" />
</.orm>
When the user clic+s the 4Su!mit4 !utton. the 56 will not contain any form data.
and will loo+ somethin% li+e this:
http5//+++)+'schools)com/+elcome)php
Page 27 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
The 4welcome)php4 file can now use the ACP1ST 'aria!le to catch the form data
0notice that the names of the form fields will automatically !e the ,D +eys in the
ACP1ST array3:
Welcome <?php echo $_7L2T;"name"=; ?>)<br />
Mo! are <?php echo $_7L2T;"a9e"=; ?> years old#
!hy use :;P7T,
6ariables sent with HTTP PO2T are not shown in the .-1
6ariables ha%e no length limit
Howe'er. !ecause the 'aria!les are not displayed in the 56. it is not possi!le to
!oo+mar+ the pa%e)
The :;)9.89T 6ariable
The PHP AC6E$5EST 'aria!le contains the contents of !oth AC2ET. ACP1ST. and
ACC11U,E)
The PHP AC6E$5EST 'aria!le can !e used to %et the result from form data sent
with !oth the 2ET and P1ST methods)
Example
Welcome <?php echo $_IP8QP2T;"name"=; ?>)<br />
Mo! are <?php echo $_IP8QP2T;"a9e"=; ?> years old#
PHP 1ate%&
The PHP date03 function is used to format a time or a date)
The PHP 1ate%& -unction
The PHP date03 function formats a timestamp to a more reada!le date and time)
Syntax
date*.ormat-timestamp,
Page 28 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
Parameter $escription
#ormat -e7uired. 2'eci#ies the #ormat o# the timestam'
timestam' O'tional. 2'eci#ies a timestam'. De#ault is the current
date and time (as a timestam')
PHP 1ate - !hat is a Timestamp,
A timestamp is the num!er of seconds since 8anuary J. JFIE at EE:EE:EE 2#T) This
is also +nown as the 5ni/ Timestamp)
PHP 1ate - -ormat the 1ate
The first parameter in the date03 function specifies how to format the date:time) ,t
uses letters to represent date and time formats) Here are some of the letters that can
!e used:
d " The day o# the month (8"38)
m " The current month, as a number (8"82)
9 " The current year in #our digits
An o'er'iew of all the letters that can !e used in the format parameter. can !e found
in our PHP Date reference)
1ther characters. li+e4:4. 4)4. or 4(4 can also !e inserted !etween the letters to add
additional formattin%:
<?php
echo date*"M/m/d",;
echo "<br />";
echo date*"M)m)d",;
echo "<br />";
echo date*"MRmRd",;
?>
The output of the code a!o'e could !e somethin% li+e this:
&<<%/<K/$$
&<<%)<K)$$
&<<%R<KR$$
PHP 1ate - Adding a Timestamp
Page 29 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
The second parameter in the date03 function specifies a timestamp) This parameter is
optional) ,f you do not supply a timestamp. the current time will !e used)
,n our ne/t e/ample we will use the m+time03 function to create a timestamp for
tomorrow)
The m+time03 function returns the 5ni/ timestamp for a specified date)
Syntax
mktime*ho!r-min!te-second-month-day-year-is_dst,
To %o one day in the future we simply add one to the day ar%ument of m+time03:
<?php
$tomorro+ mktime*<-<-<-date*"m",-date*"d",F$-date*"M",,;
echo "Tomorro+ is ")date*"M/m/d"- $tomorro+,;
?>
The output of the code a!o'e could !e somethin% li+e this:
Tomorro+ is &<<%/<K/$&
PHP 1ate - )eference
For more information a!out all the PHP date functions. please 'isit our PHP Date
6eference)
PHP 'nclude -ile
Ser'er Side ,ncludes 0SS,3 are used to create functions. headers. footers. or elements
that will !e reused on multiple pa%es)
erver ide 'ncludes
Tou can insert the content of a file into a PHP file !efore the ser'er e/ecutes it. with
the include03 or re;uire03 function) The two functions are identical in e'ery way.
e/cept how they handle errors) The include03 function %enerates a warnin% 0!ut the
script will continue e/ecution3 while the re;uire03 function %enerates a fatal error
0and the script e/ecution will stop after the error3)
These two functions are used to create functions. headers. footers. or elements that
can !e reused on multiple pa%es)
Page 30 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
This can sa'e the de'eloper a considera!le amount of time) This means that you can
create a standard header or menu file that you want all your we! pa%es to include)
When the header needs to !e updated. you can only update this one include file. or
when you add a new pa%e to your site. you can simply chan%e the menu file 0instead
of updatin% the lin+s on all we! pa%es3)
The include%& -unction
The include03 function ta+es all the te/t in a specified file and copies it into the file
that uses the include function)
Example 1
Assume that you ha'e a standard header file. called 4header)php4) To include the
header file in a pa%e. use the include03 function. li+e this:
<html>
<body>
<?php incl!de*"header)php",; ?>
<h$>Welcome to my home pa9e</h$>
<p>2ome te"t</p>
</body>
</html>
Example
Bow. let7s assume we ha'e a standard menu file that should !e used on all pa%es
0include files usually ha'e a 4)php4 e/tension3) oo+ at the 4menu)php4 file !elow:
<html>
<body>
<a hre."http5//+++)+'schools)com/de.a!lt)php">Home</a> S
<a hre."http5//+++)+'schools)com/abo!t)php">Cbo!t Qs</a> S
<a hre."http5//+++)+'schools)com/contact)php">Bontact Qs</a>
The three files. 4default)php4. 4a!out)php4. and 4contact)php4 should all include the
4menu)php4 file) Here is the code in 4default)php4:
<?php incl!de*"men!)php",; ?>
<h$>Welcome to my home pa9e</h$>
<p>2ome te"t</p>
</body>
</html>
Page 31 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
,f you loo+ at the source code of the 4default)php4 in a !rowser. it will loo+
somethin% li+e this:
<html>
<body>
<a hre."de.a!lt)php">Home</a> S
<a hre."abo!t)php">Cbo!t Qs</a> S
<a hre."contact)php">Bontact Qs</a>
<h$>Welcome to my home pa9e</h$>
<p>2ome te"t</p>
</body>
</html>
And. of course. we would ha'e to do the same thin% for 4a!out)php4 and
4contact)php4) *y usin% include files. you simply ha'e to update the te/t in the
4menu)php4 file if you decide to rename or chan%e the order of the lin+s or add
another we! pa%e to the site)
The re=uire%& -unction
The re;uire03 function is identical to include03. e/cept that it handles errors
differently)
The include03 function %enerates a warnin% 0!ut the script will continue e/ecution3
while the re;uire03 function %enerates a fatal error 0and the script e/ecution will stop
after the error3)
,f you include a file with the include03 function and an error occurs. you mi%ht %et
an error messa%e li+e the one !elow)
PHP code:
<html>
<body>
<?php
incl!de*"+ron90ile)php",;
echo "Hello World#";
?>
</body>
</html>
Error messa%e:
Warning: incl!de*+ron90ile)php, ;.!nction)incl!de=5
.ailed to open stream5
Page 32 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
6o s!ch .ile or directory in B5ThomeT+ebsiteTtest)php on line
E
Warning: incl!de*, ;.!nction)incl!de=5
0ailed openin9 >+ron90ile)php> .or incl!sion
*incl!de_path>);B5TphpETpear>,
in B5ThomeT+ebsiteTtest)php on line E
Hello World#
Botice that the echo statement is still e/ecutedG This is !ecause a Warnin% does not
stop the script e/ecution)
Bow. let7s run the same e/ample with the re;uire03 function)
PHP code:
<html>
<body>
<?php
reU!ire*"+ron90ile)php",;
echo "Hello World#";
?>
</body>
</html>
Error messa%e:
Warning: reU!ire*+ron90ile)php, ;.!nction)reU!ire=5
.ailed to open stream5
6o s!ch .ile or directory in B5ThomeT+ebsiteTtest)php on line
E
Fatal error: reU!ire*, ;.!nction)reU!ire=5
0ailed openin9 reU!ired >+ron90ile)php>
*incl!de_path>);B5TphpETpear>,
in B5ThomeT+ebsiteTtest)php on line E
The echo statement was not e/ecuted !ecause the script e/ecution stopped after the
fatal error)
,t is recommended to use the re;uire03 function instead of include03. !ecause scripts
should not continue e/ecutin% if files are missin% or misnamed)
PHP -ile Handling
Page 33 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
The fopen03 function is used to open files in PHP)
7pening a -ile
The fopen03 function is used to open files in PHP)
The first parameter of this function contains the name of the file to !e opened and
the second parameter specifies in which mode the file should !e opened:
<html>
<body>
<?php
$.ile.open*"+elcome)t"t"-"r",;
?>
</body>
</html>
The file may !e opened in one of the followin% modes:
Modes $escription
r -ead only. 2tarts at the beginning o# the #ile
r: -ead;<rite. 2tarts at the beginning o# the #ile
w <rite only. O'ens and clears the contents o# #ile= or
creates a new #ile i# it doesn>t e$ist
w: -ead;<rite. O'ens and clears the contents o# #ile= or
creates a new #ile i# it doesn>t e$ist
a &''end. O'ens and writes to the end o# the #ile or
creates a new #ile i# it doesn>t e$ist
a:
-ead;&''end. Preser%es #ile content by writing to the
end o# the #ile
$ <rite only. ?reates a new #ile. -eturns 0&12/ and an
error i# #ile already e$ists
$: -ead;<rite. ?reates a new #ile. -eturns 0&12/ and an
Page 34 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
error i# #ile already e$ists
0ote5 ,f the fopen03 function is una!le to open the specified file. it returns E 0false3)
Example
The followin% e/ample %enerates a messa%e if the fopen03 function is una!le to
open the specified file:
<html>
<body>
<?php
$.ile.open*"+elcome)t"t"-"r", or e"it*"Qnable to open
.ile#",;
?>
</body>
</html>
$losing a -ile
The fclose03 function is used to close an open file:
<?php
$.ile .open*"test)t"t"-"r",;
//some code to be e"ec!ted
.close*$.ile,;
?>
$hec> 9nd-of-file
The feof03 function chec+s if the 4end(of(file4 0E1F3 has !een reached)
The feof03 function is useful for loopin% throu%h data of un+nown len%th)
0ote5 Tou cannot read from files opened in w. a. and / modeG
i. *.eo.*$.ile,, echo "Pnd o. .ile";
)eading a -ile "ine by "ine
The f%ets03 function is used to read a sin%le line from a file)
0ote5 After a call to this function the file pointer has mo'ed to the ne/t line)
Page 35 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
Example
The e/ample !elow reads a file line !y line. until the end of file is reached:
<?php
$.ile .open*"+elcome)t"t"- "r", or e"it*"Qnable to open
.ile#",;
//L!tp!t a line o. the .ile !ntil the end is reached
+hile*#.eo.*$.ile,,
1
echo .9ets*$.ile,) "<br />";
4
.close*$.ile,;
?>
)eading a -ile $haracter by $haracter
The f%etc03 function is used to read a sin%le character from a file)
0ote5 After a call to this function the file pointer mo'es to the ne/t character)
Example
The e/ample !elow reads a file character !y character. until the end of file is
reached:
<?php
$.ile.open*"+elcome)t"t"-"r", or e"it*"Qnable to open
.ile#",;
+hile *#.eo.*$.ile,,
1
echo .9etc*$.ile,;
4
.close*$.ile,;
?>
PHP -ilesystem )eference
For a full reference of the PHP filesystem functions. 'isit our PHP
Filesystem 6eference)
Page 36 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
PHP -ile 8pload
With PHP. it is possi!le to upload files to the ser'er)
$reate an 8pload--ile -orm
To allow users to upload files from a form can !e 'ery useful)
oo+ at the followin% HT# form for uploadin% files:
<html>
<body>
<.orm action"!pload_.ile)php" method"post"
enctype"m!ltipart/.ormRdata">
<label .or".ile">0ilename5</label>
<inp!t type".ile" name".ile" id".ile" />
<br />
<inp!t type"s!bmit" name"s!bmit" val!e"2!bmit" />
</.orm>
</body>
</html>
Botice the followin% a!out the HT# form a!o'e:
The enctype attri!ute of the <form> ta% specifies which content(type
to use when su!mittin% the form) 4multipart:form(data4 is used when
a form re;uires !inary data. li+e the contents of a file. to !e uploaded
The typeL4file4 attri!ute of the <input> ta% specifies that the input
should !e processed as a file) For e/ample. when 'iewed in a
!rowser. there will !e a !rowse(!utton ne/t to the input field
0ote5 Allowin% users to upload files is a !i% security ris+) 1nly permit
trusted users to perform file uploads)
$reate The 8pload cript
The 4uploadCfile)php4 file contains the code for uploadin% a file:
<?php
i. *$_0D@P2;".ile"=;"error"= > <,
1
echo "Prror5 " ) $_0D@P2;".ile"=;"error"= ) "<br />";
4
else
1
echo "Qpload5 " ) $_0D@P2;".ile"=;"name"= ) "<br />";
Page 37 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
echo "Type5 " ) $_0D@P2;".ile"=;"type"= ) "<br />";
echo "2iVe5 " ) *$_0D@P2;".ile"=;"siVe"= / $<&(, ) " Hb<br
/>";
echo "2tored in5 " ) $_0D@P2;".ile"=;"tmp_name"=;
4
?>
*y usin% the %lo!al PHP ACF,ES array you can upload files from a client
computer to the remote ser'er)
The first parameter is the form7s input name and the second inde/ can !e
either 4name4. 4type4. 4siDe4. 4tmpCname4 or 4error4) i+e this:
ACF,ESV4file4WV4name4W ( the name of the uploaded file
ACF,ESV4file4WV4type4W ( the type of the uploaded file
ACF,ESV4file4WV4siDe4W ( the siDe in !ytes of the uploaded file
ACF,ESV4file4WV4tmpCname4W ( the name of the temporary copy of
the file stored on the ser'er
ACF,ESV4file4WV4error4W ( the error code resultin% from the file
upload
This is a 'ery simple way of uploadin% files) For security reasons. you
should add restrictions on what the user is allowed to upload)
)estrictions on 8pload
,n this script we add some restrictions to the file upload) The user may only
upload )%if or )-pe% files and the file siDe must !e under ME +!:
<?php
i. ***$_0D@P2;".ile"=;"type"= "ima9e/9i.",
SS *$_0D@P2;".ile"=;"type"= "ima9e/Wpe9",
SS *$_0D@P2;".ile"=;"type"= "ima9e/pWpe9",,
OO *$_0D@P2;".ile"=;"siVe"= < &<<<<,,
1
i. *$_0D@P2;".ile"=;"error"= > <,
1
echo "Prror5 " ) $_0D@P2;".ile"=;"error"= ) "<br />";
4
else
1
echo "Qpload5 " ) $_0D@P2;".ile"=;"name"= ) "<br />";
echo "Type5 " ) $_0D@P2;".ile"=;"type"= ) "<br />";
echo "2iVe5 " ) *$_0D@P2;".ile"=;"siVe"= / $<&(, ) " Hb<br
/>";
echo "2tored in5 " ) $_0D@P2;".ile"=;"tmp_name"=;
Page 38 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
4
4
else
1
echo "Dnvalid .ile";
4
?>
0ote5 For ,E to reco%niDe -p% files the type must !e p-pe%. for FireFo/ it
must !e -pe%)
aving the 8ploaded -ile
The e/amples a!o'e create a temporary copy of the uploaded files in the
PHP temp folder on the ser'er)
The temporary copied files disappears when the script ends) To store the
uploaded file we need to copy it to a different location:
<?php
i. ***$_0D@P2;".ile"=;"type"= "ima9e/9i.",
SS *$_0D@P2;".ile"=;"type"= "ima9e/Wpe9",
SS *$_0D@P2;".ile"=;"type"= "ima9e/pWpe9",,
OO *$_0D@P2;".ile"=;"siVe"= < &<<<<,,
1
i. *$_0D@P2;".ile"=;"error"= > <,
1
echo "Iet!rn Bode5 " ) $_0D@P2;".ile"=;"error"= ) "<br
/>";
4
else
1
echo "Qpload5 " ) $_0D@P2;".ile"=;"name"= ) "<br />";
echo "Type5 " ) $_0D@P2;".ile"=;"type"= ) "<br />";
echo "2iVe5 " ) *$_0D@P2;".ile"=;"siVe"= / $<&(, ) " Hb<br
/>";
echo "Temp .ile5 " ) $_0D@P2;".ile"=;"tmp_name"= ) "<br
/>";
i. *.ile_e"ists*"!pload/" ) $_0D@P2;".ile"=;"name"=,,
1
echo $_0D@P2;".ile"=;"name"= ) " already e"ists) ";
4
else
1
move_!ploaded_.ile*$_0D@P2;".ile"=;"tmp_name"=-
"!pload/" ) $_0D@P2;".ile"=;"name"=,;
echo "2tored in5 " ) "!pload/" )
Page 39 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
$_0D@P2;".ile"=;"name"=;
4
4
4
else
1
echo "Dnvalid .ile";
4
?>
The script a!o'e chec+s if the file already e/ists. if it does not. it copies the
file to the specified folder)
0ote5 This e/ample sa'es the file to a new folder called 4upload4
PHP $oo>ies
A coo+ie is often used to identify a user)
!hat is a $oo>ie,
A coo+ie is often used to identify a user) A coo+ie is a small file that the
ser'er em!eds on the user7s computer) Each time the same computer re;uests
a pa%e with a !rowser. it will send the coo+ie too) With PHP. you can !oth
create and retrie'e coo+ie 'alues)
How to $reate a $oo>ie,
The setcoo+ie03 function is used to set a coo+ie)
0ote5 The setcoo+ie03 function must appear *EF16E the <html> ta%)
Syntax
setcookie*name- val!e- e"pire- path- domain,;
Page 40 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
Example 1
,n the e/ample !elow. we will create a coo+ie named 4user4 and assi%n the
'alue 4Ale/ Porter4 to it) We also specify that the coo+ie should e/pire after
one hour:
<?php
setcookie*"!ser"- "Cle" 7orter"- time*,F'%<<,;
?>
<html>
)))))
0ote5 The 'alue of the coo+ie is automatically 56encoded when sendin%
the coo+ie. and automatically decoded when recei'ed 0to pre'ent
56encodin%. use setrawcoo+ie03 instead3)
Example
Tou can also set the e/piration time of the coo+ie in another way) ,t may !e
easier than usin% seconds)
<?php
$e"piretime*,F%<*%<*&(*'<;
setcookie*"!ser"- "Cle" 7orter"- $e"pire,;
?>
<html>
)))))
,n the e/ample a!o'e the e/piration time is set to a month 060 sec * 60 min *
24 hours * 30 days3)
How to )etrieve a $oo>ie 6alue,
The PHP ACC11U,E 'aria!le is used to retrie'e a coo+ie 'alue)
,n the e/ample !elow. we retrie'e the 'alue of the coo+ie named 4user4 and
display it on a pa%e:
<?php
// 7rint a cookie
echo $_BLLHDP;"!ser"=;
// C +ay to vie+ all cookies
Page 41 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
print_r*$_BLLHDP,;
?>
,n the followin% e/ample we use the isset03 function to find out if a coo+ie
has !een set:
<html>
<body>
<?php
i. *isset*$_BLLHDP;"!ser"=,,
echo "Welcome " ) $_BLLHDP;"!ser"= ) "#<br />";
else
echo "Welcome 9!est#<br />";
?>
</body>
</html>
How to 1elete a $oo>ie,
When deletin% a coo+ie you should assure that the e/piration date is in the
past)
Delete e/ample:
<?php
// set the e"piration date to one ho!r a9o
setcookie*"!ser"- ""- time*,R'%<<,;
?>
!hat if a 2rowser 1oes 07T upport $oo>ies,
,f your application deals with !rowsers that do not support coo+ies. you will
ha'e to use other methods to pass information from one pa%e to another in
your application) 1ne method is to pass the data throu%h forms 0forms and
user input are descri!ed earlier in this tutorial3)
The form !elow passes the user input to 4welcome)php4 when the user clic+s
on the 4Su!mit4 !utton:
<html>
<body>
<.orm action"+elcome)php" method"post">
6ame5 <inp!t type"te"t" name"name" />
C9e5 <inp!t type"te"t" name"a9e" />
Page 42 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
<inp!t type"s!bmit" />
</.orm>
</body>
</html>
6etrie'e the 'alues in the 4welcome)php4 file li+e this:
<html>
<body>
Welcome <?php echo $_7L2T;"name"=; ?>)<br />
Mo! are <?php echo $_7L2T;"a9e"=; ?> years old)
</body>
</html>
PHP essions
A PHP session 'aria!le is used to store information a!out. or chan%e settin%s
for a user session) Session 'aria!les hold information a!out one sin%le user.
and are a'aila!le to all pa%es in one application)
PHP ession 6ariables
When you are wor+in% with an application. you open it. do some chan%es
and then you close it) This is much li+e a Session) The computer +nows who
you are) ,t +nows when you start the application and when you end) *ut on
the internet there is one pro!lem: the we! ser'er does not +now who you are
and what you do !ecause the HTTP address doesn7t maintain state)
A PHP session sol'es this pro!lem !y allowin% you to store user information
on the ser'er for later use 0i)e) username. shoppin% items. etc3) Howe'er.
session information is temporary and will !e deleted after the user has left
the we!site) ,f you need a permanent stora%e you may want to store the data
in a data!ase)
Sessions wor+ !y creatin% a uni;ue id 05,D3 for each 'isitor and store
'aria!les !ased on this 5,D) The 5,D is either stored in a coo+ie or is
propa%ated in the 56)
tarting a PHP ession
Page 43 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
*efore you can store user information in your PHP session. you must first
start up the session)
0ote5 The sessionCstart03 function must appear *EF16E the <html> ta%:
<?php session_start*,; ?>
<html>
<body>
</body>
</html>
The code a!o'e will re%ister the user7s session with the ser'er. allow you to
start sa'in% user information. and assi%n a 5,D for that user7s session)
toring a ession 6ariable
The correct way to store and retrie'e session 'aria!les is to use the PHP
ACSESS,1B 'aria!le:
<?php
session_start*,;
// store session data
$_2P22DL6;>vie+s>=$;
?>
<html>
<body>
<?php
//retrieve session data
echo "7a9evie+s") $_2P22DL6;>vie+s>=;
?>
</body>
</html>
1utput:
7a9evie+s$
,n the e/ample !elow. we create a simple pa%e('iews counter) The isset03
function chec+s if the 4'iews4 'aria!le has already !een set) ,f 4'iews4 has
!een set. we can increment our counter) ,f 4'iews4 doesn7t e/ist. we create a
4'iews4 'aria!le. and set it to J:
<?php
Page 44 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
session_start*,;
i.*isset*$_2P22DL6;>vie+s>=,,
$_2P22DL6;>vie+s>=$_2P22DL6;>vie+s>=F$;
else
$_2P22DL6;>vie+s>=$;
echo "Gie+s") $_2P22DL6;>vie+s>=;
?>
1estroying a ession
,f you wish to delete some session data. you can use the unset03 or the
sessionCdestroy03 function)
The unset03 function is used to free the specified session 'aria!le:
<?php
!nset*$_2P22DL6;>vie+s>=,;
?>
Tou can also completely destroy the session !y callin% the sessionCdestroy03
function:
<?php
session_destroy*,;
?>
0ote5 sessionCdestroy03 will reset your session and you will lose all your
stored session data)
PHP ending 9-mails
PHP allows you to send e(mails directly from a script)
The PHP mail%& -unction
The PHP mail03 function is used to send emails from inside a script)
ynta#
Page 45 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
mail*to-s!bWect-messa9e-headers-parameters,
Parameter 1escription
to 6e;uired) Specifies the recei'er : recei'ers of the email
su!-ect 6e;uired) Specifies the su!-ect of the email) 0ote5 This
parameter cannot contain any newline characters
messa%e 6e;uired) Defines the messa%e to !e sent) Each line should !e
separated with a F 0Xn3) ines should not e/ceed IE
characters
headers 1ptional) Specifies additional headers. li+e From. Cc. and
*cc) The additional headers should !e separated with a C6F
0XrXn3
parameters 1ptional) Specifies an additional parameter to the sendmail
pro%ram
0ote5 For the mail functions to !e a'aila!le. PHP re;uires an installed and
wor+in% email system) The pro%ram to !e used is defined !y the
confi%uration settin%s in the php)ini file) 6ead more in our PHP #ail
reference)
PHP imple 9-Mail
The simplest way to send an email with PHP is to send a te/t email)
,n the e/ample !elow we first declare the 'aria!les 0Ato. Asu!-ect. Amessa%e.
Afrom. Aheaders3. then we use the 'aria!les in the mail03 function to send an
e(mail:
<?php
$to "someoneXe"ample)com";
$s!bWect "Test mail";
$messa9e "Hello# This is a simple email messa9e)";
$.rom "someonelseXe"ample)com";
$headers "0rom5 $.rom";
mail*$to-$s!bWect-$messa9e-$headers,;
echo "3ail 2ent)";
?>
Page 46 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
PHP Mail -orm
With PHP. you can create a feed!ac+(form on your we!site) The e/ample
!elow sends a te/t messa%e to a specified e(mail address:
<html>
<body>
<?php
i. *isset*$_IP8QP2T;>email>=,,
//i. "email" is .illed o!t- send email
1
//send email
$email $_IP8QP2T;>email>= ;
$s!bWect $_IP8QP2T;>s!bWect>= ;
$messa9e $_IP8QP2T;>messa9e>= ;
mail* "someoneXe"ample)com"- "2!bWect5 $s!bWect"-
$messa9e- "0rom5 $email" ,;
echo "Thank yo! .or !sin9 o!r mail .orm";
4
else
//i. "email" is not .illed o!t- display the .orm
1
echo "<.orm method>post> action>mail.orm)php>>
Pmail5 <inp!t name>email> type>te"t> /><br />
2!bWect5 <inp!t name>s!bWect> type>te"t> /><br />
3essa9e5<br />
<te"tarea name>messa9e> ro+s>$E> cols>(<>>
</te"tarea><br />
<inp!t type>s!bmit> />
</.orm>";
4
?>
</body>
</html>
This is how the e/ample a!o'e wor+s:
First. chec+ if the email input field is filled out
,f it is not set 0li+e when the pa%e is first 'isited3Q output the HT#
form
,f it is set 0after the form is filled out3Q send the email from the form
When su!mit is pressed after the form is filled out. the pa%e reloads.
sees that the email input is set. and sends the email
0ote5 This is the simplest way to send e(mail. !ut it is not secure) ,n the ne/t
chapter of this tutorial you can read more a!out 'ulnera!ilities in e(mail
scripts. and how to 'alidate user input to ma+e it more secure)
Page 47 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
PHP Mail )eference
For more information a!out the PHP mail03 function. 'isit our PHP #ail
6eference)
PHP ecure 9-mails
There is a wea+ness in the PHP e(mail script in the pre'ious chapter)
PHP 9-mail 'n?ections
First. loo+ at the PHP code from the pre'ious chapter:
<html>
<body>
<?php
i. *isset*$_IP8QP2T;>email>=,,
//i. "email" is .illed o!t- send email
1
//send email
$email $_IP8QP2T;>email>= ;
$s!bWect $_IP8QP2T;>s!bWect>= ;
$messa9e $_IP8QP2T;>messa9e>= ;
mail*"someoneXe"ample)com"- "2!bWect5 $s!bWect"-
$messa9e- "0rom5 $email" ,;
echo "Thank yo! .or !sin9 o!r mail .orm";
4
else
//i. "email" is not .illed o!t- display the .orm
1
echo "<.orm method>post> action>mail.orm)php>>
Pmail5 <inp!t name>email> type>te"t> /><br />
2!bWect5 <inp!t name>s!bWect> type>te"t> /><br />
3essa9e5<br />
<te"tarea name>messa9e> ro+s>$E> cols>(<>>
</te"tarea><br />
<inp!t type>s!bmit> />
</.orm>";
4
?>
</body>
</html>
Page 48 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
The pro!lem with the code a!o'e is that unauthoriDed users can insert data
into the mail headers 'ia the input form)
What happens if the user adds the followin% te/t to the email input field in
the form=
someoneXe"ample)comY<CBc5person&Xe"ample)com
Y<CAcc5person'Xe"ample)com-person'Xe"ample)com-
anotherperson(Xe"ample)com-personEXe"ample)com
Y<CATo5person%Xe"ample)com
The mail03 function puts the te/t a!o'e into the mail headers as usual. and
now the header has an e/tra Cc:. *cc:. and To: field) When the user clic+s the
su!mit !utton. the e(mail will !e sent to all of the addresses a!o'eG
PHP topping 9-mail 'n?ections
The !est way to stop e(mail in-ections is to 'alidate the input)
The code !elow is the same as in the pre'ious chapter. !ut now we ha'e
added an input 'alidator that chec+s the email field in the form:
<html>
<body>
<?php
.!nction spamcheck*$.ield,
1
//.ilter_var*, sanitiVes the eRmail
//address !sin9 0D@TPI_2C6DTDZP_P3CD@
$.ield.ilter_var*$.ield- 0D@TPI_2C6DTDZP_P3CD@,;

//.ilter_var*, validates the eRmail
//address !sin9 0D@TPI_GC@D/CTP_P3CD@
i.*.ilter_var*$.ield- 0D@TPI_GC@D/CTP_P3CD@,,
1
ret!rn TIQP;
4
else
1
ret!rn 0C@2P;
4
4
i. *isset*$_IP8QP2T;>email>=,,
1//i. "email" is .illed o!t- proceed
//check i. the email address is invalid
$mailcheck spamcheck*$_IP8QP2T;>email>=,;
Page 49 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
i. *$mailcheck0C@2P,
1
echo "Dnvalid inp!t";
4
else
1//send email
$email $_IP8QP2T;>email>= ;
$s!bWect $_IP8QP2T;>s!bWect>= ;
$messa9e $_IP8QP2T;>messa9e>= ;
mail*"someoneXe"ample)com"- "2!bWect5 $s!bWect"-
$messa9e- "0rom5 $email" ,;
echo "Thank yo! .or !sin9 o!r mail .orm";
4
4
else
1//i. "email" is not .illed o!t- display the .orm
echo "<.orm method>post> action>mail.orm)php>>
Pmail5 <inp!t name>email> type>te"t> /><br />
2!bWect5 <inp!t name>s!bWect> type>te"t> /><br />
3essa9e5<br />
<te"tarea name>messa9e> ro+s>$E> cols>(<>>
</te"tarea><br />
<inp!t type>s!bmit> />
</.orm>";
4
?>
</body>
</html>
,n the code a!o'e we use PHP filters to 'alidate input:
The F,TE6CSAB,T,&ECE#A, filter remo'es all ille%al e(mail
characters from a strin%
The F,TE6C@A,DATECE#A, filter 'alidates 'alue as an e(mail
address
Tou can read more a!out filters in our PHP Filter chapter)
PHP 9rror Handling
The default error handlin% in PHP is 'ery simple) An error messa%e with
filename. line num!er and a messa%e descri!in% the error is sent to the
!rowser)
Page 50 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
PHP 9rror Handling
When creatin% scripts and we! applications. error handlin% is an important
part) ,f your code lac+s error chec+in% code. your pro%ram may loo+ 'ery
unprofessional and you may !e open to security ris+s)
This tutorial contains some of the most common error chec+in% methods in
PHP)
We will show different error handlin% methods:
Simple 4die034 statements
Custom errors and error tri%%ers
Error reportin%
2asic 9rror Handling5 8sing the die%& function
The first e/ample shows a simple script that opens a te/t file:
<?php
$.ile.open*"+elcome)t"t"-"r",;
?>
,f the file does not e/ist you mi%ht %et an error li+e this:
Warning5 .open*+elcome)t"t, ;.!nction).open=5 .ailed to open
stream5
6o s!ch .ile or directory in C:\webfolder\test.php on line 2
To a'oid that the user %ets an error messa%e li+e the one a!o'e. we test if the
file e/ist !efore we try to access it:
<?php
i.*#.ile_e"ists*"+elcome)t"t",,
1
die*"0ile not .o!nd",;
4
else
1
$.ile.open*"+elcome)t"t"-"r",;
4
?>
Bow if the file does not e/ist you %et an error li+e this:
Page 51 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
0ile not .o!nd
The code a!o'e is more efficient than the earlier code. !ecause it uses a
simple error handlin% mechanism to stop the script after the error)
Howe'er. simply stoppin% the script is not always the ri%ht way to %o) et7s
ta+e a loo+ at alternati'e PHP functions for handlin% errors)
$reating a $ustom 9rror Handler
Creatin% a custom error handler is ;uite simple) We simply create a special
function that can !e called when an error occurs in PHP)
This function must !e a!le to handle a minimum of two parameters 0error
le'el and error messa%e3 !ut can accept up to fi'e parameters 0optionally:
file. line(num!er. and the error conte/t3:
ynta#
error_.!nction*error_level-error_messa9e-
error_.ile-error_line-error_conte"t,

Parameter 1escription
errorCle'el 6e;uired) Specifies the error report le'el for the user(defined
error) #ust !e a 'alue num!er) See ta!le !elow for possi!le
error report le'els
errorCmessa%e 6e;uired) Specifies the error messa%e for the user(defined
error
errorCfile 1ptional) Specifies the filename in which the error occurred
errorCline 1ptional) Specifies the line num!er in which the error
occurred
errorCconte/t 1ptional) Specifies an array containin% e'ery 'aria!le. and
their 'alues. in use when the error occurred
9rror )eport levels
These error report le'els are the different types of error the user(defined error
handler can !e used for:
Page 52 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
6alue $onstant 1escription
M ECWA6B,B2 Bon(fatal run(time errors) E/ecution of
the script is not halted
P ECB1T,CE 6un(time notices) The script found
somethin% that mi%ht !e an error. !ut
could also happen when runnin% a
script normally
M9H EC5SE6CE6616 Fatal user(%enerated error) This is li+e
an ECE6616 set !y the pro%rammer
usin% the PHP function tri%%erCerror03
9JM EC5SE6CWA6B,B2 Bon(fatal user(%enerated warnin%) This
is li+e an ECWA6B,B2 set !y the
pro%rammer usin% the PHP function
tri%%erCerror03
JEMN EC5SE6CB1T,CE 5ser(%enerated notice) This is li+e an
ECB1T,CE set !y the pro%rammer
usin% the PHP function tri%%erCerror03
NEFH EC6EC1@E6A*ECE6616 Catcha!le fatal error) This is li+e an
ECE6616 !ut can !e cau%ht !y a user
defined handle 0see also
setCerrorChandler033
PJFJ ECA All errors and warnin%s. e/cept le'el
ECST6,CT 0ECST6,CT will !e part of
ECA as of PHP H)E3
Bow lets create a function to handle errors:
.!nction c!stomPrror*$errno- $errstr,
1
echo "<b>Prror5</b> ;$errno= $errstr<br />";
echo "Pndin9 2cript";
die*,;
4
The code a!o'e is a simple error handlin% function) When it is tri%%ered. it
%ets the error le'el and an error messa%e) ,t then outputs the error le'el and
messa%e and terminates the script)
Bow that we ha'e created an error handlin% function we need to decide when
it should !e tri%%ered)
Page 53 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
et 9rror Handler
The default error handler for PHP is the !uilt in error handler) We are %oin%
to ma+e the function a!o'e the default error handler for the duration of the
script)
,t is possi!le to chan%e the error handler to apply for only some errors. that
way the script can handle different errors in different ways) Howe'er. in this
e/ample we are %oin% to use our custom error handler for all errors:
set_error_handler*"c!stomPrror",;
Since we want our custom function to handle all errors. the
setCerrorChandler03 only needed one parameter. a second parameter could !e
added to specify an error le'el)
9#ample
Testin% the error handler !y tryin% to output 'aria!le that does not e/ist:
<?php
//error handler .!nction
.!nction c!stomPrror*$errno- $errstr,
1
echo "<b>Prror5</b> ;$errno= $errstr";
4
//set error handler
set_error_handler*"c!stomPrror",;
//tri99er error
echo*$test,;
?>
The output of the code a!o'e should !e somethin% li+e this:
Error: ;N= Qnde.ined variable5 test
Trigger an 9rror
,n a script where users can input data it is useful to tri%%er errors when an
ille%al input occurs) ,n PHP. this is done !y the tri%%erCerror03 function)
9#ample
Page 54 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
,n this e/ample an error occurs if the 4test4 'aria!le is !i%%er than 4J4:
<?php
$test&;
i. *$test>$,
1
tri99er_error*"Gal!e m!st be $ or belo+",;
4
?>
The output of the code a!o'e should !e somethin% li+e this:
Notice5 Gal!e m!st be $ or belo+
in C:\webfolder\test.php on line 6
An error can !e tri%%ered anywhere you wish in a script. and !y addin% a
second parameter. you can specify what error le'el is tri%%ered)
Possi!le error types:
EC5SE6CE6616 ( Fatal user(%enerated run(time error) Errors that
can not !e reco'ered from) E/ecution of the script is halted
EC5SE6CWA6B,B2 ( Bon(fatal user(%enerated run(time warnin%)
E/ecution of the script is not halted
EC5SE6CB1T,CE ( Default) 5ser(%enerated run(time notice) The
script found somethin% that mi%ht !e an error. !ut could also happen
when runnin% a script normally
9#ample
,n this e/ample an EC5SE6CWA6B,B2 occurs if the 4test4 'aria!le is
!i%%er than 4J4) ,f an EC5SE6CWA6B,B2 occurs we will use our custom
error handler and end the script:
<?php
//error handler .!nction
.!nction c!stomPrror*$errno- $errstr,
1
echo "<b>Prror5</b> ;$errno= $errstr<br />";
echo "Pndin9 2cript";
die*,;
4
//set error handler
set_error_handler*"c!stomPrror"-P_Q2PI_WCI6D6?,;
//tri99er error
Page 55 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
$test&;
i. *$test>$,
1
tri99er_error*"Gal!e m!st be $ or belo+"-P_Q2PI_WCI6D6?,;
4
?>

The output of the code a!o'e should !e somethin% li+e this:
Error: ;E$&= Gal!e m!st be $ or belo+
Pndin9 2cript
Bow that we ha'e learned to create our own errors and how to tri%%er them.
lets ta+e a loo+ at error lo%%in%)
9rror "ogging
*y default. PHP sends an error lo% to the ser'ers lo%%in% system or a file.
dependin% on how the errorClo% confi%uration is set in the php)ini file) *y
usin% the errorClo%03 function you can send error lo%s to a specified file or a
remote destination)
Sendin% errors messa%es to yourself !y e(mail can !e a %ood way of %ettin%
notified of specific errors)
end an 9rror Message by 9-Mail
,n the e/ample !elow we will send an e(mail with an error messa%e and end
the script. if a specific error occurs:
<?php
//error handler .!nction
.!nction c!stomPrror*$errno- $errstr,
1
echo "<b>Prror5</b> ;$errno= $errstr<br />";
echo "Webmaster has been noti.ied";
error_lo9*"Prror5 ;$errno= $errstr"-$-
"someoneXe"ample)com"-"0rom5 +ebmasterXe"ample)com",;
4
//set error handler
set_error_handler*"c!stomPrror"-P_Q2PI_WCI6D6?,;
//tri99er error
$test&;
i. *$test>$,
Page 56 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
1
tri99er_error*"Gal!e m!st be $ or belo+"-P_Q2PI_WCI6D6?,;
4
?>
The output of the code a!o'e should !e somethin% li+e this:
Error: ;E$&= Gal!e m!st be $ or belo+
Webmaster has been noti.ied
And the mail recei'ed from the code a!o'e loo+s li+e this:
Prror5 ;E$&= Gal!e m!st be $ or belo+
This should not !e used with all errors) 6e%ular errors should !e lo%%ed on
the ser'er usin% the default PHP lo%%in% system)
PHP 9#ception Handling
E/ceptions are used to chan%e the normal flow of a script if a specified error
occurs
!hat is an 9#ception
With PHP 9 came a new o!-ect oriented way of dealin% with errors)
E/ception handlin% is used to chan%e the normal flow of the code e/ecution
if a specified error 0e/ceptional3 condition occurs) This condition is called an
e/ception)
This is what normally happens when an e/ception is tri%%ered:
The current code state is sa'ed
The code e/ecution will switch to a predefined 0custom3 e/ception
handler function
Dependin% on the situation. the handler may then resume the
e/ecution from the sa'ed code state. terminate the script e/ecution or
continue the script from a different location in the code
We will show different error handlin% methods:
*asic use of E/ceptions
Creatin% a custom e/ception handler
#ultiple e/ceptions
Page 57 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
6e(throwin% an e/ception
Settin% a top le'el e/ception handler
0ote5 E/ceptions should only !e used with error conditions. and should not
!e used to -ump to another place in the code at a specified point)
2asic 8se of 9#ceptions
When an e/ception is thrown. the code followin% it will not !e e/ecuted. and
PHP will try to find the matchin% 4catch4 !loc+)
,f an e/ception is not cau%ht. a fatal error will !e issued with an 45ncau%ht
E/ception4 messa%e)
ets try to throw an e/ception without catchin% it:
<?php
//create .!nction +ith an e"ception
.!nction check6!m*$n!mber,
1
i.*$n!mber>$,
1
thro+ ne+ P"ception*"Gal!e m!st be $ or belo+",;
4
ret!rn tr!e;
4
//tri99er e"ception
check6!m*&,;
?>
The code a!o'e will %et an error li+e this:
Fatal error5 Qnca!9ht e"ception >P"ception>
+ith messa9e >Gal!e m!st be $ or belo+> in
B5T+eb.olderTtest)php5%
2tack trace5 [< B5T+eb.olderTtest)php*$&,5
check6!m*&N, [$ 1main4 thro+n in C:\webfolder\test.php on line
6
Try, throw and catch
To a'oid the error from the e/ample a!o'e. we need to create the proper
code to handle an e/ception)
Page 58 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
Proper e/ception code should include:
J) Try ( A function usin% an e/ception should !e in a 4try4 !loc+) ,f the
e/ception does not tri%%er. the code will continue as normal)
Howe'er if the e/ception tri%%ers. an e/ception is 4thrown4
M) Throw ( This is how you tri%%er an e/ception) Each 4throw4 must
ha'e at least one 4catch4
3) Catch ( A 4catch4 !loc+ retrie'es an e/ception and creates an o!-ect
containin% the e/ception information
ets try to tri%%er an e/ception with 'alid code:
<?php
//create .!nction +ith an e"ception
.!nction check6!m*$n!mber,
1
i.*$n!mber>$,
1
thro+ ne+ P"ception*"Gal!e m!st be $ or belo+",;
4
ret!rn tr!e;
4
//tri99er e"ception in a "try" block
try
1
check6!m*&,;
//D. the e"ception is thro+n- this te"t +ill not be sho+n
echo >D. yo! see this- the n!mber is $ or belo+>;
4
//catch e"ception
catch*P"ception $e,
1
echo >3essa9e5 > )$eR>9et3essa9e*,;
4
?>
The code a!o'e will %et an error li+e this:
3essa9e5 Gal!e m!st be $ or belo+
9#ample e#plained5
The code a!o'e throws an e/ception and catches it:
J) The chec+Bum03 function is created) ,t chec+s if a num!er is %reater
than J) ,f it is. an e/ception is thrown
Page 59 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
M) The chec+Bum03 function is called in a 4try4 !loc+
3) The e/ception within the chec+Bum03 function is thrown
N) The 4catch4 !loc+ retri'es the e/ception and creates an o!-ect 0Ae3
containin% the e/ception information
9) The error messa%e from the e/ception is echoed !y callin% Ae(
>%et#essa%e03 from the e/ception o!-ect
Howe'er. one way to %et around the 4e'ery throw must ha'e a catch4 rule is
to set a top le'el e/ception handler to handle errors that slip throu%h)
$reating a $ustom 9#ception $lass
Creatin% a custom e/ception handler is ;uite simple) We simply create a
special class with functions that can !e called when an e/ception occurs in
PHP) The class must !e an e/tension of the e/ception class)
The custom e/ception class inherits the properties from PHP7s e/ception
class and you can add custom functions to it)
ets create an e/ception class:
<?php
class c!stomP"ception e"tends P"ception
1
p!blic .!nction error3essa9e*,
1
//error messa9e
$error3s9 >Prror on line >)$thisR>9et@ine*,)> in >)$thisR
>9et0ile*,
)>5 <b>>)$thisR>9et3essa9e*,)></b> is not a valid PR3ail
address>;
ret!rn $error3s9;
4
4
$email "someoneXe"ample)))com";
try
1
//check i.
i.*.ilter_var*$email- 0D@TPI_GC@D/CTP_P3CD@, 0C@2P,
1
//thro+ e"ception i. email is not valid
thro+ ne+ c!stomP"ception*$email,;
4
4
catch *c!stomP"ception $e,
1
//display c!stom messa9e
Page 60 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
echo $eR>error3essa9e*,;
4
?>
The new class is a copy of the old e/ception class with an addition of the
error#essa%e03 function) Since 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 li+e %etine03 and %etFile03 and %et#essa%e03)
9#ample e#plained5
The code a!o'e throws an e/ception and catches it with a custom e/ception
class:
J) The customE/ception03 class is created as an e/tension of the old
e/ception class) This way it inherits all methods and properties from
the old e/ception class
M) The error#essa%e03 function is created) This function returns an error
messa%e if an e(mail address is in'alid
3) The Aemail 'aria!le is set to a strin% that is not a 'alid e(mail address
N) The 4try4 !loc+ is e/ecuted and an e/ception is thrown since the e(
mail address is in'alid
9) The 4catch4 !loc+ catches the e/ception and displays the error
messa%e
Multiple 9#ceptions
,t is possi!le for a script to use multiple e/ceptions to chec+ for multiple
conditions)
,t is possi!le to use se'eral if))else !loc+s. a switch. or nest multiple
e/ceptions) These e/ceptions can use different e/ception classes and return
different error messa%es:
<?php
class c!stomP"ception e"tends P"ception
1
p!blic .!nction error3essa9e*,
1
//error messa9e
$error3s9 >Prror on line >)$thisR>9et@ine*,)> in >)$thisR
>9et0ile*,
)>5 <b>>)$thisR>9et3essa9e*,)></b> is not a valid PR3ail
address>;
Page 61 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
ret!rn $error3s9;
4
4
$email "someoneXe"ample)com";
try
1
//check i.
i.*.ilter_var*$email- 0D@TPI_GC@D/CTP_P3CD@, 0C@2P,
1
//thro+ e"ception i. email is not valid
thro+ ne+ c!stomP"ception*$email,;
4
//check .or "e"ample" in mail address
i.*strpos*$email- "e"ample", # 0C@2P,
1
thro+ ne+ P"ception*"$email is an e"ample eRmail",;
4
4
catch *c!stomP"ception $e,
1
echo $eR>error3essa9e*,;
4
catch*P"ception $e,
1
echo $eR>9et3essa9e*,;
4
?>
9#ample e#plained5
The code a!o'e tests two conditions and throws an e/ception if any of the
conditions are not met:
J) The customE/ception03 class is created as an e/tension of the old
e/ception class) This way it inherits all methods and properties from
the old e/ception class
M) The error#essa%e03 function is created) This function returns an error
messa%e if an e(mail address is in'alid
3) The Aemail 'aria!le is set to a strin% that is a 'alid e(mail address. !ut
contains the strin% 4e/ample4
N) The 4try4 !loc+ is e/ecuted and an e/ception is not thrown on the
first condition
9) The second condition tri%%ers an e/ception since the e(mail contains
the strin% 4e/ample4
Page 62 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
H) The 4catch4 !loc+ catches the e/ception and displays the correct error
messa%e
,f there was no customE/ception catch. only the !ase e/ception catch. the
e/ception would !e handled there
)e-throwing 9#ceptions
Sometimes. when an e/ception is thrown. you may wish to handle it
differently than the standard way) ,t is possi!le to throw an e/ception a
second time within a 4catch4 !loc+)
A script should hide system errors from users) System errors may !e
important for the coder. !ut is of no interest to the user) To ma+e thin%s
easier for the user you can re(throw the e/ception with a user friendly
messa%e:
<?php
class c!stomP"ception e"tends P"ception
1
p!blic .!nction error3essa9e*,
1
//error messa9e
$error3s9 $thisR>9et3essa9e*,)> is not a valid PR3ail
address)>;
ret!rn $error3s9;
4
4
$email "someoneXe"ample)com";
try
1
try
1
//check .or "e"ample" in mail address
i.*strpos*$email- "e"ample", # 0C@2P,
1
//thro+ e"ception i. email is not valid
thro+ ne+ P"ception*$email,;
4
4
catch*P"ception $e,
1
//reRthro+ e"ception
thro+ ne+ c!stomP"ception*$email,;
4
4
catch *c!stomP"ception $e,
Page 63 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
1
//display c!stom messa9e
echo $eR>error3essa9e*,;
4
?>
9#ample e#plained5
The code a!o'e tests if the email(address contains the strin% 4e/ample4 in it.
if it does. the e/ception is re(thrown:
J) The customE/ception03 class is created as an e/tension of the old
e/ception class) This way it inherits all methods and properties from
the old e/ception class
M) The error#essa%e03 function is created) This function returns an error
messa%e if an e(mail address is in'alid
3) The Aemail 'aria!le is set to a strin% that is a 'alid e(mail address. !ut
contains the strin% 4e/ample4
N) The 4try4 !loc+ contains another 4try4 !loc+ to ma+e it possi!le to re(
throw the e/ception
9) The e/ception is tri%%ered since the e(mail contains the strin%
4e/ample4
H) The 4catch4 !loc+ catches the e/ception and re(throws a
4customE/ception4
I) The 4customE/ception4 is cau%ht and displays an error messa%e
,f the e/ception is not cau%ht in its current 4try4 !loc+. it will search for a
catch !loc+ on 4hi%her le'els4)
et a Top "evel 9#ception Handler
The setCe/ceptionChandler03 function sets a user(defined function to handle
all uncau%ht e/ceptions)
<?php
.!nction myP"ception*$e"ception,
1
echo "<b>P"ception5</b> " - $e"ceptionR>9et3essa9e*,;
4
set_e"ception_handler*>myP"ception>,;
thro+ ne+ P"ception*>Qnca!9ht P"ception occ!rred>,;
?>
The output of the code a!o'e should !e somethin% li+e this:
Page 64 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
Exception: Qnca!9ht P"ception occ!rred
,n the code a!o'e there was no 4catch4 !loc+) ,nstead. the top le'el
e/ception handler tri%%ered) This function should !e used to catch uncau%ht
e/ceptions)
)ules for e#ceptions
Code may !e surrounded in a try !loc+. to help catch potential
e/ceptions
Each try !loc+ or 4throw4 must ha'e at least one correspondin% catch
!loc+
#ultiple catch !loc+s can !e used to catch different classes of
e/ceptions
E/ceptions can !e thrown 0or re(thrown3 in a catch !loc+ within a try
!loc+
A simple rule: ,f you throw somethin%. you ha'e to catch it)
PHP -ilter
PHP filters are used to 'alidate and filter data comin% from insecure sources.
li+e user input)
!hat is a PHP -ilter,
A PHP filter is used to 'alidate and filter data comin% from insecure sources)
To test. 'alidate and filter user input or custom data is an important part of
any we! application)
The PHP filter e/tension is desi%ned to ma+e data filterin% easier and
;uic+er)
!hy use a -ilter,
Almost all we! applications depend on e/ternal input) 5sually this comes
from a user or another application 0li+e a we! ser'ice3) *y usin% filters you
can !e sure your application %ets the correct input type)
Page 65 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
*ou should always filter all e#ternal data(
,nput filterin% is one of the most important application security issues)
What is e/ternal data=
,nput data from a form
Coo+ies
We! ser'ices data
Ser'er 'aria!les
Data!ase ;uery results
-unctions and -ilters
To filter a 'aria!le. use one of the followin% filter functions:
filterC'ar03 ( Filters a sin%le 'aria!le with a specified filter
filterC'arCarray03 ( Filter se'eral 'aria!les with the same or different
filters
filterCinput ( 2et one input 'aria!le and filter it
filterCinputCarray ( 2et se'eral input 'aria!les and filter them with
the same or different filters
,n the e/ample !elow. we 'alidate an inte%er usin% the filterC'ar03 function:
<?php
$int $&';
i.*#.ilter_var*$int- 0D@TPI_GC@D/CTP_D6T,,
1
echo*"Dnte9er is not valid",;
4
else
1
echo*"Dnte9er is valid",;
4
?>
The code a!o'e uses the 4F,TE6C@A,DATEC,BT4 filter to filter the
'aria!le) Since the inte%er is 'alid. the output of the code a!o'e will !e:
4,nte%er is 'alid4)
,f we try with a 'aria!le that is not an inte%er 0li+e 4JM3a!c43. the output will
!e: 4,nte%er is not 'alid4)
For a complete list of functions and filters. 'isit our PHP Filter 6eference)
Page 66 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
6alidating and aniti@ing
There are two +inds of filters:
@alidatin% filters:
Are used to 'alidate user input
Strict format rules 0li+e 56 or E(#ail 'alidatin%3
6eturns the e/pected type on success or FASE on failure
SanitiDin% filters:
Are used to allow or disallow specified characters in a strin%
Bo data format rules
Always return the strin%
7ptions and -lags
1ptions and fla%s are used to add additional filterin% options to the specified
filters)
Different filters ha'e different options and fla%s)
,n the e/ample !elow. we 'alidate an inte%er usin% the filterC'ar03 and the
4minCran%e4 and 4ma/Cran%e4 options:
<?php
$var'<<;
$int_options array*
"options">array
*
"min_ran9e"><-
"ma"_ran9e">&E%
,
,;
i.*#.ilter_var*$var- 0D@TPI_GC@D/CTP_D6T- $int_options,,
1
echo*"Dnte9er is not valid",;
4
else
1
echo*"Dnte9er is valid",;
4
?>
Page 67 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
i+e the code a!o'e. options must !e put in an associati'e array with the
name 4options4) ,f a fla% is used it does not need to !e in an array)
Since the inte%er is 43EE4 it is not in the specified ran%e. and the output of
the code a!o'e will !e: 4,nte%er is not 'alid4)
For a complete list of functions and filters. 'isit our PHP Filter 6eference)
Chec+ each filter to see what options and fla%s are a'aila!le)
6alidate 'nput
et7s try 'alidatin% input from a form)
The first thin% we need to do is to confirm that the input data we are loo+in%
for e/ists)
Then we filter the input data usin% the filterCinput03 function)
,n the e/ample !elow. the input 'aria!le 4email4 is sent to the PHP pa%e:
<?php
i.*#.ilter_has_var*D67QT_?PT- "email",,
1
echo*"Dnp!t type does not e"ist",;
4
else
1
i. *#.ilter_inp!t*D67QT_?PT- "email"- 0D@TPI_GC@D/CTP_P3CD@,,
1
echo "PR3ail is not valid";
4
else
1
echo "PR3ail is valid";
4
4
?>
9#ample 9#plained
The e/ample a!o'e has an input 0email3 sent to it usin% the 42ET4 method:
J) Chec+ if an 4email4 input 'aria!le of the 42ET4 type e/ist
M) ,f the input 'aria!le e/ists. chec+ if it is a 'alid e(mail address
aniti@e 'nput
Page 68 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
et7s try cleanin% up an 56 sent from a form)
First we confirm that the input data we are loo+in% for e/ists)
Then we sanitiDe the input data usin% the filterCinput03 function)
,n the e/ample !elow. the input 'aria!le 4url4 is sent to the PHP pa%e:
<?php
i.*#.ilter_has_var*D67QT_7L2T- "!rl",,
1
echo*"Dnp!t type does not e"ist",;
4
else
1
$!rl .ilter_inp!t*D67QT_7L2T-
"!rl"- 0D@TPI_2C6DTDZP_QI@,;
4
?>
9#ample 9#plained
The e/ample a!o'e has an input 0url3 sent to it usin% the 4P1ST4 method:
J) Chec+ if the 4url4 input of the 4P1ST4 type e/ists
M) ,f the input 'aria!le e/ists. sanitiDe 0ta+e away in'alid characters3 and
store it in the Aurl 'aria!le
,f the input 'aria!le is a strin% li+e this 4http:::www)W3YYSchZZools)com:4.
the Aurl 'aria!le after the sanitiDin% will loo+ li+e this:
http5//+++)W'2chools)com/
-ilter Multiple 'nputs
A form almost always consist of more than one input field) To a'oid callin%
the filterC'ar or filterCinput functions o'er and o'er. we can use the
filterC'arCarray or the filterCinputCarray functions)
,n this e/ample we use the filterCinputCarray03 function to filter three 2ET
'aria!les) The recei'ed 2ET 'aria!les is a name. an a%e and an e(mail
address:
<?php
$.ilters array
Page 69 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
*
"name" > array
*
".ilter">0D@TPI_2C6DTDZP_2TID6?
,-
"a9e" > array
*
".ilter">0D@TPI_GC@D/CTP_D6T-
"options">array
*
"min_ran9e">$-
"ma"_ran9e">$&<
,
,-
"email"> 0D@TPI_GC@D/CTP_P3CD@-
,;
$res!lt .ilter_inp!t_array*D67QT_?PT- $.ilters,;
i. *#$res!lt;"a9e"=,
1
echo*"C9e m!st be a n!mber bet+een $ and $&<)<br />",;
4
elsei.*#$res!lt;"email"=,
1
echo*"PR3ail is not valid)<br />",;
4
else
1
echo*"Qser inp!t is valid",;
4
?>
9#ample 9#plained
The e/ample a!o'e has three inputs 0name. a%e and email3 sent to it usin%
the 42ET4 method:
J) Set an array containin% the name of input 'aria!les and the filters
used on the specified input 'aria!les
M) Call the filterCinputCarray03 function with the 2ET input 'aria!les
and the array we -ust set
3) Chec+ the 4a%e4 and 4email4 'aria!les in the Aresult 'aria!le for
in'alid inputs) 0,f any of the input 'aria!les are in'alid. that input
'aria!le will !e FASE after the filterCinputCarray03 function3
The second parameter of the filterCinputCarray03 function can !e an array or
a sin%le filter ,D)
Page 70 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
,f the parameter is a sin%le filter ,D all 'alues in the input array are filtered
!y the specified filter)
,f the parameter is an array it must follow these rules:
#ust !e an associati'e array containin% an input 'aria!le as an array
+ey 0li+e the 4a%e4 input 'aria!le3
The array 'alue must !e a filter ,D or an array specifyin% the filter.
fla%s and options
8sing -ilter $allbac>
,t is possi!le to call a user defined function and use it as a filter usin% the
F,TE6CCA*ACU filter) This way. we ha'e full control of the data
filterin%)
Tou can create your own user defined function or use an e/istin% PHP
function
The function you wish to use to filter is specified the same way as an option
is specified) ,n an associati'e array with the name 4options4
,n the e/ample !elow. we use a user created function to con'ert all 4C4 to
whitespaces:
<?php
.!nction convert2pace*$strin9,
1
ret!rn str_replace*"_"- " "- $strin9,;
4
$strin9 "7eter_is_a_9reat_9!y#";
echo .ilter_var*$strin9- 0D@TPI_BC@@ACBH-
array*"options">"convert2pace",,;
?>
The result from the code a!o'e should loo+ li+e this:
7eter is a 9reat 9!y#
9#ample 9#plained
Page 71 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
The e/ample a!o'e con'erts all 4C4 to whitespaces:
J) Create a function to replace 4C4 to whitespaces
M) Call the filterC'ar03 function with the F,TE6CCA*ACU filter
and an array containin% our function
PHP My." 'ntroduction
#yS$ is the most popular open(source data!ase system)
!hat is My.",
#yS$ is a data!ase)
The data in #yS$ is stored in data!ase o!-ects called ta!les)
A ta!le is a collections of related data entries and it consists of columns and
rows)
Data!ases are useful when storin% information cate%orically) A company may
ha'e a data!ase with the followin% ta!les: 4Employees4. 4Products4.
4Customers4 and 41rders4)
1atabase Tables
A data!ase most often contains one or more ta!les) Each ta!le is identified
!y a name 0e)%) 4Customers4 or 41rders43) Ta!les contain records 0rows3
with data)
*elow is an e/ample of a ta!le called 4Persons4:
"ast0ame -irst0ame Address $ity
Hansen 1la Timotei'n JE Sandnes
S'endson To'e *or%'n M3 Sandnes
Pettersen Uari Stor%t ME Sta'an%er
The ta!le a!o'e contains three records 0one for each person3 and four
columns 0astBame. FirstBame. Address. and City3)
.ueries
A ;uery is a ;uestion or a re;uest)
Page 72 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
With #yS$. we can ;uery a data!ase for specific information and ha'e a
recordset returned)
oo+ at the followin% ;uery:
2P@PBT @ast6ame 0IL3 7ersons
The ;uery a!o'e selects all the data in the 4astBame4 column from the
4Persons4 ta!le. and will return a recordset li+e this:
"ast0ame
Hansen
S'endson
Pettersen
1ownload My." 1atabase
,f you don7t ha'e a PHP ser'er with a #yS$ Data!ase. you can download
#yS$ for free here: http:::www)mys;l)com:downloads:inde/)html
-acts About My." 1atabase
1ne %reat thin% a!out #yS$ is that it can !e scaled down to support
em!edded data!ase applications) Perhaps it is !ecause of this reputation that
many people !elie'e that #yS$ can only handle small to medium(siDed
systems)
The truth is that #yS$ is the de(facto standard data!ase for we! sites that
support hu%e 'olumes of !oth data and end users 0li+e Friendster. Tahoo.
2oo%le3)
oo+ at http:::www)mys;l)com:customers: for an o'er'iew of companies
usin% #yS$)
PHP My." $onnect to a 1atabase
The free #yS$ data!ase is 'ery often used with PHP)
Page 73 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
$reate a $onnection to a My." 1atabase
*efore you can access data in a data!ase. you must create a connection to the
data!ase)
,n PHP. this is done with the mys;lCconnect03 function)
Syntax
mysUl_connect*servername-!sername-pass+ord,;
Parameter $escription
ser%ername O'tional. 2'eci#ies the ser%er to connect to. De#ault
%alue is 3localhost,33@3
username O'tional. 2'eci#ies the username to log in with.
De#ault %alue is the name o# the user that owns the
ser%er 'rocess
'assword O'tional. 2'eci#ies the 'assword to log in with.
De#ault is 33
0ote5 There are more a'aila!le parameters. !ut the ones listed a!o'e are the
most important) @isit our full PHP #yS$ 6eference for more details)
Example
,n the followin% e/ample we store the connection in a 'aria!le 0Acon3 for
later use in the script) The 4die4 part will !e e/ecuted if the connection fails:
<?php
$con mysUl_connect*"localhost"-"peter"-"abc$&'",;
i. *#$con,
1
die*>Bo!ld not connect5 > ) mysUl_error*,,;
4
// some code
?>
Page 74 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
$losing a $onnection
The connection will !e closed automatically when the script ends) To close
the connection !efore. use the mys;lCclose03 function:
<?php
$con mysUl_connect*"localhost"-"peter"-"abc$&'",;
i. *#$con,
1
die*>Bo!ld not connect5 > ) mysUl_error*,,;
4
// some code
mysUl_close*$con,;
?>
PHP My." $reate 1atabase and Tables
A data!ase holds one or multiple ta!les)
$reate a 1atabase
The C6EATE DATA*ASE statement is used to create a data!ase in #yS$)
Syntax
BIPCTP /CTCAC2P database_name
To learn more about 2A1, 'lease %isit our 2A1 tutorial.
To %et PHP to e/ecute the statement a!o'e we must use the mys;lC;uery03
function) This function is used to send a ;uery or command to a #yS$
connection)
Page 75 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
Example
The followin% e/ample creates a data!ase called 4myCd!4:
<?php
$con mysUl_connect*"localhost"-"peter"-"abc$&'",;
i. *#$con,
1
die*>Bo!ld not connect5 > ) mysUl_error*,,;
4
i. *mysUl_U!ery*"BIPCTP /CTCAC2P my_db"-$con,,
1
echo "/atabase created";
4
else
1
echo "Prror creatin9 database5 " ) mysUl_error*,;
4
mysUl_close*$con,;
?>
$reate a Table
The C6EATE TA*E statement is used to create a ta!le in #yS$)
Syntax
BIPCTP TCA@P table_name
*
col!mn_name$ data_type-
col!mn_name& data_type-
col!mn_name' data_type-
....
,
To learn more a!out S$. please 'isit our S$ tutorial)
We must add the C6EATE TA*E statement to the mys;lC;uery03 function
to e/ecute the command)
Example
The followin% e/ample creates a ta!le named 4Persons4. with three columns)
The column names will !e 4FirstBame4. 4astBame4 and 4A%e4:
Page 76 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
<?php
$con mysUl_connect*"localhost"-"peter"-"abc$&'",;
i. *#$con,
1
die*>Bo!ld not connect5 > ) mysUl_error*,,;
4
// Breate database
i. *mysUl_U!ery*"BIPCTP /CTCAC2P my_db"-$con,,
1
echo "/atabase created";
4
else
1
echo "Prror creatin9 database5 " ) mysUl_error*,;
4
// Breate table
mysUl_select_db*"my_db"- $con,;
$sUl "BIPCTP TCA@P 7ersons
*
0irst6ame varchar*$E,-
@ast6ame varchar*$E,-
C9e int
,";
// P"ec!te U!ery
mysUl_U!ery*$sUl-$con,;
mysUl_close*$con,;
?>
'mportant5 A data!ase must !e selected !efore a ta!le can !e created) The
data!ase is selected with the mys;lCselectCd!03 function)
0ote5 When you create a data!ase field of type 'archar. you must specify the
ma/imum len%th of the field. e)%) 'archar0J93)
The data type specifies what type of data the column can hold) For a
complete reference of all the data types a'aila!le in #yS$. %o to our
complete Data Types reference)
Primary +eys and Auto 'ncrement -ields
Each ta!le should ha'e a primary +ey field)
A primary +ey is used to uni;uely identify the rows in a ta!le) Each primary
+ey 'alue must !e uni;ue within the ta!le) Furthermore. the primary +ey
Page 77 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
field cannot !e null !ecause the data!ase en%ine re;uires a 'alue to locate the
record)
The followin% e/ample sets the person,D field as the primary +ey field) The
primary +ey field is often an ,D num!er. and is often used with the
A5T1C,BC6E#EBT settin%) A5T1C,BC6E#EBT automatically
increases the 'alue of the field !y J each time a new record is added) To
ensure that the primary +ey field cannot !e null. we must add the B1T
B5 settin% to the field)
Example
$sUl "BIPCTP TCA@P 7ersons
*
personD/ int 6LT 6Q@@ CQTL_D6BIP3P6T-
7ID3CIM HPM*personD/,-
0irst6ame varchar*$E,-
@ast6ame varchar*$E,-
C9e int
,";
mysUl_U!ery*$sUl-$con,;
PHP My." 'nsert 'nto
The ,BSE6T ,BT1 statement is used to insert new records in a ta!le)
'nsert 1ata 'nto a 1atabase Table
The ,BSE6T ,BT1 statement is used to add new records to a data!ase ta!le)
Syntax
,t is possi!le to write the ,BSE6T ,BT1 statement in two forms)
The first form doesn7t specify the column names where the data will !e
inserted. only their 'alues:
D62PIT D6TL table_name
GC@QP2 *val!e$- val!e&- val!e'-))),
Page 78 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
The second form specifies !oth the column names and the 'alues to !e
inserted:
D62PIT D6TL table_name *col!mn$- col!mn&- col!mn'-))),
GC@QP2 *val!e$- val!e&- val!e'-))),
To learn more about 2A1, 'lease %isit our 2A1 tutorial.
To %et PHP to e/ecute the statements a!o'e we must use the mys;lC;uery03
function) This function is used to send a ;uery or command to a #yS$
connection)
Example
,n the pre'ious chapter we created a ta!le named 4Persons4. with three
columnsQ 4Firstname4. 4astname4 and 4A%e4) We will use the same ta!le in
this e/ample) The followin% e/ample adds two new records to the 4Persons4
ta!le:
<?php
$con mysUl_connect*"localhost"-"peter"-"abc$&'",;
i. *#$con,
1
die*>Bo!ld not connect5 > ) mysUl_error*,,;
4
mysUl_select_db*"my_db"- $con,;
mysUl_U!ery*"D62PIT D6TL 7ersons *0irst6ame- @ast6ame- C9e,
GC@QP2 *>7eter>- >?ri..in>- >'E>,",;
mysUl_U!ery*"D62PIT D6TL 7ersons *0irst6ame- @ast6ame- C9e,
GC@QP2 *>?lenn>- >8!a9mire>- >''>,",;
mysUl_close*$con,;
?>
'nsert 1ata -rom a -orm 'nto a 1atabase
Bow we will create an HT# form that can !e used to add new records to
the 4Persons4 ta!le)
Here is the HT# form:
<html>
<body>
<.orm action"insert)php" method"post">
0irstname5 <inp!t type"te"t" name".irstname" />
Page 79 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
@astname5 <inp!t type"te"t" name"lastname" />
C9e5 <inp!t type"te"t" name"a9e" />
<inp!t type"s!bmit" />
</.orm>
</body>
</html>
When a user clic+s the su!mit !utton in the HT# form in the e/ample
a!o'e. the form data is sent to 4insert)php4)
The 4insert)php4 file connects to a data!ase. and retrie'es the 'alues from the
form with the PHP ACP1ST 'aria!les)
Then. the mys;lC;uery03 function e/ecutes the ,BSE6T ,BT1 statement. and
a new record will !e added to the 4Persons4 ta!le)
Here is the 4insert)php4 pa%e:
<?php
$con mysUl_connect*"localhost"-"peter"-"abc$&'",;
i. *#$con,
1
die*>Bo!ld not connect5 > ) mysUl_error*,,;
4
mysUl_select_db*"my_db"- $con,;
$sUl"D62PIT D6TL 7ersons *0irst6ame- @ast6ame- C9e,
GC@QP2
*>$_7L2T;.irstname=>->$_7L2T;lastname=>->$_7L2T;a9e=>,";
i. *#mysUl_U!ery*$sUl-$con,,
1
die*>Prror5 > ) mysUl_error*,,;
4
echo "$ record added";
mysUl_close*$con,
?>
PHP My." elect
The SEECT statement is used to select data from a data!ase)
elect 1ata -rom a 1atabase Table
Page 80 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
The SEECT statement is used to select data from a data!ase)
Syntax
2P@PBT col!mn_name*s,
0IL3 table_name
To learn more a!out S$. please 'isit our S$ tutorial)
To %et PHP to e/ecute the statement a!o'e we must use the mys;lC;uery03
function) This function is used to send a ;uery or command to a #yS$
connection)
Example
The followin% e/ample selects all the data stored in the 4Persons4 ta!le 0The
? character selects all the data in the ta!le3:
<?php
$con mysUl_connect*"localhost"-"peter"-"abc$&'",;
i. *#$con,
1
die*>Bo!ld not connect5 > ) mysUl_error*,,;
4
mysUl_select_db*"my_db"- $con,;
$res!lt mysUl_U!ery*"2P@PBT * 0IL3 7ersons",;
+hile*$ro+ mysUl_.etch_array*$res!lt,,
1
echo $ro+;>0irst6ame>= ) " " ) $ro+;>@ast6ame>=;
echo "<br />";
4
mysUl_close*$con,;
?>
The e/ample a!o'e stores the data returned !y the mys;lC;uery03 function in
the Aresult 'aria!le)
Be/t. we use the mys;lCfetchCarray03 function to return the first row from
the recordset as an array) Each call to mys;lCfetchCarray03 returns the ne/t
row in the recordset) The while loop loops throu%h all the records in the
recordset) To print the 'alue of each row. we use the PHP Arow 'aria!le
0ArowV7FirstBame7W and ArowV7astBame7W3)
The output of the code a!o'e will !e:
Page 81 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
7eter ?ri..in
?lenn 8!a9mire
1isplay the )esult in an HTM" Table
The followin% e/ample selects the same data as the e/ample a!o'e. !ut will
display the data in an HT# ta!le:
<?php
$con mysUl_connect*"localhost"-"peter"-"abc$&'",;
i. *#$con,
1
die*>Bo!ld not connect5 > ) mysUl_error*,,;
4
mysUl_select_db*"my_db"- $con,;
$res!lt mysUl_U!ery*"2P@PBT * 0IL3 7ersons",;
echo "<table border>$>>
<tr>
<th>0irstname</th>
<th>@astname</th>
</tr>";
+hile*$ro+ mysUl_.etch_array*$res!lt,,
1
echo "<tr>";
echo "<td>" ) $ro+;>0irst6ame>= ) "</td>";
echo "<td>" ) $ro+;>@ast6ame>= ) "</td>";
echo "</tr>";
4
echo "</table>";
mysUl_close*$con,;
?>
The output of the code a!o'e will !e:
%irstna
me
&astnam
e
Blenn
Auagmir
e
Peter Bri##in
Page 82 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
PHP My." The !here $lause
The WHE6E clause is used to filter records)
The !H9)9 clause
The WHE6E clause is used to e/tract only those records that fulfill a
specified criterion)
Syntax
2P@PBT col!mn_name*s,
0IL3 table_name
WHPIP col!mn_name operator val!e
To learn more a!out S$. please 'isit our S$ tutorial)
To %et PHP to e/ecute the statement a!o'e we must use the mys;lC;uery03
function) This function is used to send a ;uery or command to a #yS$
connection)
Example
The followin% e/ample selects all rows from the 4Persons4 ta!le where
4FirstBameL7Peter7:
<?php
$con mysUl_connect*"localhost"-"peter"-"abc$&'",;
i. *#$con,
1
die*>Bo!ld not connect5 > ) mysUl_error*,,;
4
mysUl_select_db*"my_db"- $con,;
$res!lt mysUl_U!ery*"2P@PBT * 0IL3 7ersons
WHPIP 0irst6ame>7eter>",;
+hile*$ro+ mysUl_.etch_array*$res!lt,,
1
echo $ro+;>0irst6ame>= ) " " ) $ro+;>@ast6ame>=;
echo "<br />";
Page 83 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
4
?>
The output of the code a!o'e will !e:
7eter ?ri..in
PHP My." 7rder 2y +eyword
The 16DE6 *T +eyword is used to sort the data in a recordset)
The 7)19) 2* +eyword
The 16DE6 *T +eyword is used to sort the data in a recordset)
The 16DE6 *T +eyword sort the records in ascendin% order !y default)
,f you want to sort the records in a descendin% order. you can use the DESC
+eyword)
Syntax
2P@PBT col!mn_name*s,
0IL3 table_name
LI/PI AM col!mn_name*s, C2BS/P2B
To learn more a!out S$. please 'isit our S$ tutorial)
Example
The followin% e/ample selects all the data stored in the 4Persons4 ta!le. and
sorts the result !y the 4A%e4 column:
<?php
$con mysUl_connect*"localhost"-"peter"-"abc$&'",;
i. *#$con,
1
die*>Bo!ld not connect5 > ) mysUl_error*,,;
4
Page 84 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
mysUl_select_db*"my_db"- $con,;
$res!lt mysUl_U!ery*"2P@PBT * 0IL3 7ersons LI/PI AM a9e",;
+hile*$ro+ mysUl_.etch_array*$res!lt,,
1
echo $ro+;>0irst6ame>=;
echo " " ) $ro+;>@ast6ame>=;
echo " " ) $ro+;>C9e>=;
echo "<br />";
4
mysUl_close*$con,;
?>
The output of the code a!o'e will !e:
?lenn 8!a9mire ''
7eter ?ri..in 'E
7rder by Two $olumns
,t is also possi!le to order !y more than one column) When orderin% !y more
than one column. the second column is only used if the 'alues in the first
column are e;ual:
2P@PBT col!mn_name*s,
0IL3 table_name
LI/PI AM col!mn$- col!mn&
PHP My." 8pdate
The 5PDATE statement is used to modify data in a ta!le)
8pdate 1ata 'n a 1atabase
The 5PDATE statement is used to update e/istin% records in a ta!le)
Syntax
Q7/CTP table_name
2PT col!mn$val!e- col!mn&val!e&-)))
WHPIP some_col!mnsome_val!e
Page 85 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
Note# Notice the <H/-/ clause in the .PD&T/ synta$. The <H/-/
clause s'eci#ies which record or records that should be u'dated. *#
you omit the <H/-/ clause, all records will be u'datedC
To learn more a!out S$. please 'isit our S$ tutorial)
To %et PHP to e/ecute the statement a!o'e we must use the mys;lC;uery03
function) This function is used to send a ;uery or command to a #yS$
connection)
Example
Earlier in the tutorial we created a ta!le named 4Persons4) Here is how it
loo+s:
%irstName &astName A'e
Peter Bri##in 3D
Blenn Auagmire 33
The followin% e/ample updates some data in the 4Persons4 ta!le:
<?php
$con mysUl_connect*"localhost"-"peter"-"abc$&'",;
i. *#$con,
1
die*>Bo!ld not connect5 > ) mysUl_error*,,;
4
mysUl_select_db*"my_db"- $con,;
mysUl_U!ery*"Q7/CTP 7ersons 2PT C9e >'%>
WHPIP 0irst6ame >7eter> C6/ @ast6ame >?ri..in>",;
mysUl_close*$con,;
?>
After the update. the 4Persons4 ta!le will loo+ li+e this:
%irstName &astName A'e
Peter Bri##in 3@
Page 86 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
Blenn Auagmire 33
PHP My." 1elete
The DEETE statement is used to delete records in a ta!le)
1elete 1ata 'n a 1atabase
The DEETE F61# statement is used to delete records from a data!ase
ta!le)
Syntax
/P@PTP 0IL3 table_name
WHPIP some_col!mn some_val!e
Note# Notice the <H/-/ clause in the D/1/T/ synta$. The <H/-/
clause s'eci#ies which record or records that should be deleted. *#
you omit the <H/-/ clause, all records will be deletedC
To learn more a!out S$. please 'isit our S$ tutorial)
To %et PHP to e/ecute the statement a!o'e we must use the mys;lC;uery03
function) This function is used to send a ;uery or command to a #yS$
connection)
Example
oo+ at the followin% 4Persons4 ta!le:
%irstName &astName A'e
Peter Bri##in 3D
Blenn Auagmire 33
Page 87 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
The followin% e/ample deletes all the records in the 4Persons4 ta!le where
astBameL72riffin7:
<?php
$con mysUl_connect*"localhost"-"peter"-"abc$&'",;
i. *#$con,
1
die*>Bo!ld not connect5 > ) mysUl_error*,,;
4
mysUl_select_db*"my_db"- $con,;
mysUl_U!ery*"/P@PTP 0IL3 7ersons WHPIP @ast6ame>?ri..in>",;
mysUl_close*$con,;
?>
After the deletion. the ta!le will loo+ li+e this:
%irstName &astName A'e
Blenn Auagmire 33
PHP 1atabase 712$
1D*C is an Application Pro%rammin% ,nterface 0AP,3 that allows you to
connect to a data source 0e)%) an #S Access data!ase3)
$reate an 712$ $onnection
Page 88 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
With an 1D*C connection. you can connect to any data!ase. on any
computer in your networ+. as lon% as an 1D*C connection is a'aila!le)
Here is how to create an 1D*C connection to a #S Access Data!ase:
8. O'en the Administrative Tools icon in your ?ontrol Panel.
2. Double"clic+ on the $ata Sources ()$*+, icon inside.
3. ?hoose the System $SN tab.
E. ?lic+ on Add in the 2ystem D2N tab.
D. 2elect the Microsoft Access $river. ?lic+ %inis".
@. *n the ne$t screen, clic+ Select to locate the database.
F. Bi%e the database a $ata Source Name ($SN,.
G. ?lic+ )-.
Bote that this confi%uration has to !e done on the computer where your we!
site is located) ,f you are runnin% ,nternet ,nformation Ser'er 0,,S3 on your
own computer. the instructions a!o'e will wor+. !ut if your we! site is
located on a remote ser'er. you ha'e to ha'e physical access to that ser'er. or
as+ your we! host to to set up a DSB for you to use)
$onnecting to an 712$
The od!cCconnect03 function is used to connect to an 1D*C data source)
The function ta+es four parameters: the data source name. username.
password. and an optional cursor type)
The od!cCe/ec03 function is used to e/ecute an S$ statement)
Example
The followin% e/ample creates a connection to a DSB called northwind. with
no username and no password) ,t then creates an S$ and e/ecutes it:
$connodbc_connect*>north+ind>->>->>,;
$sUl"2P@PBT * 0IL3 c!stomers";
$rsodbc_e"ec*$conn-$sUl,;
)etrieving )ecords
The od!cCfetchCrow03 function is used to return records from the result(set)
This function returns true if it is a!le to return rows. otherwise false)
Page 89 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
The function ta+es two parameters: the 1D*C result identifier and an
optional row num!er:
odbc_.etch_ro+*$rs,
)etrieving -ields from a )ecord
The od!cCresult03 function is used to read fields from a record) This function
ta+es two parameters: the 1D*C result identifier and a field num!er or
name)
The code line !elow returns the 'alue of the first field from the record:
$compnameodbc_res!lt*$rs-$,;
The code line !elow returns the 'alue of a field called 4CompanyBame4:
$compnameodbc_res!lt*$rs-"Bompany6ame",;
$losing an 712$ $onnection
The od!cCclose03 function is used to close an 1D*C connection)
odbc_close*$conn,;
An 712$ 9#ample
The followin% e/ample shows how to first create a data!ase connection. then
a result(set. and then display the data in an HT# ta!le)
<html>
<body>
<?php
$connodbc_connect*>north+ind>->>->>,;
i. *#$conn,
1e"it*"Bonnection 0ailed5 " ) $conn,;4
$sUl"2P@PBT * 0IL3 c!stomers";
$rsodbc_e"ec*$conn-$sUl,;
i. *#$rs,
1e"it*"Prror in 28@",;4
echo "<table><tr>";
echo "<th>Bompanyname</th>";
echo "<th>Bontactname</th></tr>";
Page 90 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
+hile *odbc_.etch_ro+*$rs,,
1
$compnameodbc_res!lt*$rs-"Bompany6ame",;
$connameodbc_res!lt*$rs-"Bontact6ame",;
echo "<tr><td>$compname</td>";
echo "<td>$conname</td></tr>";
4
odbc_close*$conn,;
echo "</table>";
?>
</body>
</html>
PHP AM" 9#pat Parser
The !uilt(in E/pat parser ma+es it possi!le to process "# documents in
PHP)
!hat is AM",
"# is used to descri!e data and to focus on what data is) An "# file
descri!es the structure of the data)
,n "#. no ta%s are predefined) Tou must define your own ta%s)
,f you want to learn more a!out "#. please 'isit our "# tutorial)
!hat is 9#pat,
To read and update ( create and manipulate ( an "# document. you will
need an "# parser)
There are two !asic types of "# parsers:
Tree"based 'arser, This 'arser trans#orms an HM1 document
into a tree structure. *t analyzes the whole document, and
'ro%ides access to the tree elements. e.g. the Document
ObIect Model (DOM)
/%ent"based 'arser, 6iews an HM1 document as a series o#
e%ents. <hen a s'eci#ic e%ent occurs, it calls a #unction to
handle it
Page 91 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
The E/pat parser is an e'ent(!ased parser)
E'ent(!ased parsers focus on the content of the "# documents. not their
structure) *ecause of this. e'ent(!ased parsers can access data faster than
tree(!ased parsers)
oo+ at the followin% "# fraction:
<.rom>:ani</.rom>
An e'ent(!ased parser reports the "# a!o'e as a series of three e'ents:
2tart element, #rom
2tart ?D&T& section, %alue, Jani
?lose element, #rom
The "# e/ample a!o'e contains well(formed "#) Howe'er. the
e/ample is not 'alid "#. !ecause there is no Document Type Definition
0DTD3 associated with it)
Howe'er. this ma+es no difference when usin% the E/pat parser) E/pat is a
non('alidatin% parser. and i%nores any DTDs)
As an e'ent(!ased. non('alidatin% "# parser. E/pat is fast and small. and a
perfect match for PHP we! applications)
0ote5 "# documents must !e well(formed or E/pat will %enerate an error)
'nstallation
The "# E/pat parser functions are part of the PHP core) There is no
installation needed to use these functions)
An AM" -ile
The "# file !elow will !e used in our e/ample:
<?"ml version"$)<" encodin9"D2LRNNE\R$"?>
<note>
<to>Tove</to>
<.rom>:ani</.rom>
<headin9>Ieminder</headin9>
<body>/on>t .or9et me this +eekend#</body>
</note>
Page 92 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
'nitiali@ing the AM" Parser
We want to initialiDe the "# parser in PHP. define some handlers for
different "# e'ents. and then parse the "# file)
Example
<?php
//DnitialiVe the ]3@ parser
$parser"ml_parser_create*,;
//0!nction to !se at the start o. an element
.!nction start*$parser-$element_name-$element_attrs,
1
s+itch*$element_name,
1
case "6LTP"5
echo "RR 6ote RR<br />";
break;
case "TL"5
echo "To5 ";
break;
case "0IL3"5
echo "0rom5 ";
break;
case "HPC/D6?"5
echo "Headin95 ";
break;
case "AL/M"5
echo "3essa9e5 ";
4
4
//0!nction to !se at the end o. an element
.!nction stop*$parser-$element_name,
1
echo "<br />";
4
//0!nction to !se +hen .indin9 character data
.!nction char*$parser-$data,
1
echo $data;
4
//2peci.y element handler
"ml_set_element_handler*$parser-"start"-"stop",;
//2peci.y data handler
"ml_set_character_data_handler*$parser-"char",;
//Lpen ]3@ .ile
$.p.open*"test)"ml"-"r",;
//Iead data
+hile *$data.read*$.p-(<\%,,
Page 93 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
1
"ml_parse*$parser-$data-.eo.*$.p,, or
die *sprint.*"]3@ Prror5 Ys at line Yd"-
"ml_error_strin9*"ml_9et_error_code*$parser,,-
"ml_9et_c!rrent_line_n!mber*$parser,,,;
4
//0ree the ]3@ parser
"ml_parser_.ree*$parser,;
?>
The output of the code a!o'e will !e:
RR 6ote RR
To5 Tove
0rom5 :ani
Headin95 Ieminder
3essa9e5 /on>t .or9et me this +eekend#
How it wor+s:
8. *nitialize the HM1 'arser with the $mlK'arserKcreate()
#unction
2. ?reate #unctions to use with the di##erent e%ent handlers
3. &dd the $mlKsetKelementKhandler() #unction to s'eci#y
which #unction will be e$ecuted when the 'arser encounters
the o'ening and closing tags
E. &dd the $mlKsetKcharacterKdataKhandler() #unction to
s'eci#y which #unction will e$ecute when the 'arser
encounters character data
D. Parse the #ile 3test.$ml3 with the $mlK'arse() #unction
@. *n case o# an error, add $mlKerrorKstring() #unction to
con%ert an HM1 error to a te$tual descri'tion
F. ?all the $mlK'arserK#ree() #unction to release the memory
allocated with the $mlK'arserKcreate() #unction
More PHP 9#pat Parser
For more information a!out the PHP E/pat functions. 'isit our PHP "#
Parser 6eference)
PHP AM" 17M
Page 94 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
The !uilt(in D1# parser ma+es it possi!le to process "# documents in
PHP)
!hat is 17M,
The W3C D1# pro'ides a standard set of o!-ects for HT# and "#
documents. and a standard interface for accessin% and manipulatin% them)
The W3C D1# is separated into different parts 0Core. "#. and HT#3
and different le'els 0D1# e'el J:M:33:
? Core D1# ( defines a standard set of o!-ects for any structured document
? "# D1# ( defines a standard set of o!-ects for "# documents
? HT# D1# ( defines a standard set of o!-ects for HT# documents
,f you want to learn more a!out the "# D1#. please 'isit our "# D1#
tutorial)
AM" Parsing
To read and update ( create and manipulate ( an "# document. you will
need an "# parser)
There are two !asic types of "# parsers:
Tree"based 'arser, This 'arser trans#orms an HM1 document
into a tree structure. *t analyzes the whole document, and
'ro%ides access to the tree elements
/%ent"based 'arser, 6iews an HM1 document as a series o#
e%ents. <hen a s'eci#ic e%ent occurs, it calls a #unction to
handle it
The D1# parser is an tree(!ased parser)
oo+ at the followin% "# document fraction:
<?"ml version"$)<" encodin9"D2LRNNE\R$"?>
<.rom>:ani</.rom>
The "# D1# sees the "# a!o'e as a tree structure:
1e%el 8, HM1 Document
1e%el 2, -oot element, L#romM
1e%el 3, Te$t element, 3Jani3
Page 95 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
'nstallation
The D1# "# parser functions are part of the PHP core) There is no
installation needed to use these functions)
An AM" -ile
The "# file !elow will !e used in our e/ample:
<?"ml version"$)<" encodin9"D2LRNNE\R$"?>
<note>
<to>Tove</to>
<.rom>:ani</.rom>
<headin9>Ieminder</headin9>
<body>/on>t .or9et me this +eekend#</body>
</note>
"oad and 7utput AM"
We want to initialiDe the "# parser. load the /ml. and output it:
Example
<?php
$"ml/oc ne+ /L3/oc!ment*,;
$"ml/ocR>load*"note)"ml",;
print $"ml/ocR>save]3@*,;
?>
The output of the code a!o'e will !e:
Tove :ani Ieminder /on>t .or9et me this +eekend#
,f you select 4@iew source4 in the !rowser window. you will see the
followin% HT#:
<?"ml version"$)<" encodin9"D2LRNNE\R$"?>
<note>
<to>Tove</to>
<.rom>:ani</.rom>
<headin9>Ieminder</headin9>
<body>/on>t .or9et me this +eekend#</body>
</note>
Page 96 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
The e/ample a!o'e creates a D1#Document(1!-ect and loads the "#
from 4note)/ml4 into it)
Then the sa'e"#03 function to puts the internal "# document into a
strin%. so that we can print it)
"ooping through AM"
We want to initialiDe the "# parser. load the "#. and loop throu%h all
elements of the <note> element:
Example
<?php
$"ml/oc ne+ /L3/oc!ment*,;
$"ml/ocR>load*"note)"ml",;
$" $"ml/ocR>doc!mentPlement;
.oreach *$"R>child6odes C2 $item,
1
print $itemR>node6ame ) " " ) $itemR>nodeGal!e ) "<br />";
4
?>
The output of the code a!o'e will !e:
[te"t
to Tove
[te"t
.rom :ani
[te"t
headin9 Ieminder
[te"t
body /on>t .or9et me this +eekend#
[te"t
,n the e/ample a!o'e you see that there are empty te/t nodes !etween each
element)
When "# %enerates. it often contains white(spaces !etween the nodes) The
"# D1# parser treats these as ordinary elements. and if you are not aware
of them. they sometimes cause pro!lems)
,f you want to learn more a!out the "# D1#. please 'isit our "# D1#
tutorial)
Page 97 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
PHP impleAM"
Simple"# handles the most common "# tas+s and lea'es the rest for
other e/tensions)
!hat is impleAM",
Simple"# is new in PHP 9) ,t is an easy way of %ettin% an element7s
attri!utes and te/t. if you +now the "# document7s layout)
Compared to D1# or the E/pat parser. Simple"# -ust ta+es a few lines of
code to read te/t data from an element)
Simple"# con'erts the "# document into an o!-ect. li+e this:
Elements ( Are con'erted to sin%le attri!utes of the
Simple"#Element o!-ect) When there7s more than one element on
one le'el. they7re placed inside an array
Attri!utes ( Are accessed usin% associati'e arrays. where an inde/
corresponds to the attri!ute name
Element Data ( Te/t data from elements are con'erted to strin%s) ,f an
element has more than one te/t node. they will !e arran%ed in the
order they are found
Simple"# is fast and easy to use when performin% !asic tas+s li+e:
6eadin% "# files
E/tractin% data from "# strin%s
Editin% te/t nodes or attri!utes
Page 98 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
Howe'er. when dealin% with ad'anced "#. li+e namespaces. you are
!etter off usin% the E/pat parser or the "# D1#)
'nstallation
As of PHP 9)E. the Simple"# functions are part of the PHP core) There is
no installation needed to use these functions)
8sing impleAM"
*elow is an "# file:
<?"ml version"$)<" encodin9"D2LRNNE\R$"?>
<note>
<to>Tove</to>
<.rom>:ani</.rom>
<headin9>Ieminder</headin9>
<body>/on>t .or9et me this +eekend#</body>
</note>
We want to output the element names and data from the "# file a!o'e)
Here7s what to do:
J) oad the "# file
M) 2et the name of the first element
3) Create a loop that will tri%%er on each child node. usin% the children03
function
N) 1utput the element name and data for each child node
9#ample
<?php
$"ml simple"ml_load_.ile*"test)"ml",;
echo $"mlR>9et6ame*, ) "<br />";
.oreach*$"mlR>children*, as $child,
1
echo $childR>9et6ame*, ) "5 " ) $child ) "<br />";
4
?>
The output of the code a!o'e will !e:
note
to5 Tove
.rom5 :ani
Page 99 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
headin95 Ieminder
body5 /on>t .or9et me this +eekend#
More PHP impleAM"
For more information a!out the PHP Simple"# functions. 'isit our PHP
Simple"# 6eference)
ABAA 'ntroduction
ABAA C Asynchronous Bavacript And AM"
A8A" is an acronym for Asynchronous Ba'aScript And A#)
A8A" is not a new pro%rammin% lan%ua%e. !ut simply a new techni;ue for
creatin% !etter. faster. and more interacti'e we! applications)
A8A" uses 8a'aScript to send and recei'e data !etween a we! !rowser and a
we! ser'er)
The A8A" techni;ue ma+es we! pa%es more responsi'e !y e/chan%in% data
with the we! ser'er !ehind the scenes. instead of reloadin% an entire we!
pa%e each time a user ma+es a chan%e)
ABAA 's 2ased 7n 7pen tandards
A8A" is !ased on the followin% open standards:
Bavacript
AM"
HTM"
$
The open standards used in A8A" are well defined. and supported !y all
ma-or !rowsers) A8A" applications are !rowser and platform independent)
0Cross(Platform. Cross(*rowser technolo%y3
ABAA 's About 2etter 'nternet Applications
Page 100 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
We! applications ha'e many !enefits o'er des+top applications:
they can reach a lar%er audience
they are easier to install and support
they are easier to de'elop
Howe'er. ,nternet applications are not always as 4rich4 and user(friendly as
traditional des+top applications)
With A8A". ,nternet applications can !e made richer 0smaller. faster. and
easier to use3)
*ou $an tart 8sing ABAA Today
There is nothin% new to learn)
A8A" is !ased on open standards) These standards ha'e !een used !y most
de'elopers for se'eral years)
#ost e/istin% we! applications can !e rewritten to use A8A" technolo%y
instead of traditional HT# forms)
ABAA 8ses AM" And HTTP )e=uests
A traditional we! application will su!mit input 0usin% an HT# form3 to a
we! ser'er) After the we! ser'er has processed the data. it will return a
completely new we! pa%e to the user)
*ecause the ser'er returns a new we! pa%e each time the user su!mits input.
traditional we! applications often run slowly and tend to !e less user
friendly)
With A8A". we! applications can send and retrie'e data without reloadin%
the whole we! pa%e) This is done !y sendin% HTTP re;uests to the ser'er
0!ehind the scenes3. and !y modifyin% only parts of the we! pa%e usin%
8a'aScript when the ser'er returns data)
"# is commonly used as the format for recei'in% ser'er data. althou%h any
format. includin% plain te/t. can !e used)
Tou will learn more a!out how this is done in the ne/t chapters of this
tutorial)
PHP and ABAA
Page 101 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
There is no such thin% as an A8A" ser'er)
A8A" is a technolo%y that runs in your !rowser) ,t uses asynchronous data
transfer 0HTTP re;uests3 !etween the !rowser and the we! ser'er. allowin%
we! pa%es to re;uest small !its of information from the ser'er instead of
whole pa%es)
A8A" is a we! !rowser technolo%y independent of we! ser'er software)
Howe'er. in this tutorial we will focus more on actual e/amples runnin% on a
PHP ser'er. and less on how A8A" wor+s)
To read more a!out how A8A" wor+s. 'isit our A8A" tutorial)
ABAA AM"Http)e=uest
The "#Http6e;uest o!-ect ma+es A8A" possi!le)
The AM"Http)e=uest
The "#Http6e;uest o!-ect is the +ey to A8A")
,t has !een a'aila!le e'er since ,nternet E/plorer 9)9 was released in 8uly
MEEE. !ut not fully disco'ered !efore people started to tal+ a!out A8A" and
We! M)E in MEE9)
$reating An AM"Http)e=uest 7b?ect
Different !rowsers use different methods to create an AM"Http)e=uest
o!-ect)
,nternet E/plorer uses an ActiveA7b?ect)
1ther !rowsers uses a !uilt in 8a'aScript o!-ect called AM"Http)e=uest)
Here is the simplest code you can use to o'ercome this pro!lem:
var ]3@Httpn!ll
i. *+indo+)]3@HttpIeU!est,
1
]3@Httpne+ ]3@HttpIeU!est*,
4
Page 102 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
else i. *+indo+)Cctive]LbWect,
1
]3@Httpne+ Cctive]LbWect*"3icroso.t)]3@HTT7",
4
E/ample a!o'e e/plained:
8. First create a 'aria!le AM"Http to use as your "#Http6e;uest
o!-ect) Set the 'alue to null)
2. Then test if the o!-ect window.AM"Http)e=uest is a'aila!le) This
o!-ect is a'aila!le in newer 'ersions of Firefo/. #oDilla. 1pera. and
Safari)
3. ,f it7s a'aila!le. use it to create a new o!-ect: AM"HttpCnew
AM"Http)e=uest%&
E. ,f it7s not a'aila!le. test if an o!-ect window.ActiveA7b?ect is
a'aila!le) This o!-ect is a'aila!le in ,nternet E/plorer 'ersion 9)9 and
later)
D. ,f it is a'aila!le. use it to create a new o!-ect: AM"HttpCnew
ActiveA7b?ect%&
A 2etter 9#ample,
Some pro%rammers will prefer to use the newest and fastest 'ersion of the
"#Http6e;uest o!-ect)
The e/ample !elow tries to load #icrosoft7s latest 'ersion
4#s/mlM)"#HTTP4. a'aila!le in ,nternet E/plorer H. !efore it falls !ac+
to 4#icrosoft)"#HTTP4. a'aila!le in ,nternet E/plorer 9)9 and later)
.!nction ?et]mlHttpLbWect*,
1
var "mlHttpn!ll;
try
1
// 0ire.o"- Lpera N)<F- 2a.ari
"mlHttpne+ ]3@HttpIeU!est*,;
4
catch *e,
1
// Dnternet P"plorer
try
1
"mlHttpne+ Cctive]LbWect*"3s"ml&)]3@HTT7",;
4
catch *e,
1
Page 103 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
"mlHttpne+ Cctive]LbWect*"3icroso.t)]3@HTT7",;
4
4
ret!rn "mlHttp;
4
E/ample a!o'e e/plained:
8. First create a 'aria!le AM"Http to use as your "#Http6e;uest
o!-ect) Set the 'alue to null)
2. Try to create the o!-ect accordin% to we! standards 0#oDilla. 1pera
and Safari3:AM"HttpCnew AM"Http)e=uest%&
3. Try to create the o!-ect the #icrosoft way. a'aila!le in ,nternet
E/plorer H and later:AM"HttpCnew
ActiveA7b?ect%DMs#mlE.AM"HTTPD&
E. ,f this catches an error. try the older 0,nternet E/plorer 9)93 way:
AM"HttpCnew ActiveA7b?ect%DMicrosoft.AM"HTTPD&
More about the AM"Http)e=uest ob?ect
,f you want to read more a!out the "#Http6e;uest. 'isit our A8A"
tutorial)
PHP and ABAA uggest
ABAA uggest
,n the A8A" e/ample !elow we will demonstrate how a we! pa%e can
communicate with a we! ser'er online as a user enters data into a we! form)
Type a 0ame in the 2o# 2elow
First Bame:
Su%%estions:
This e/ample consists of three pa%es:
a simple HT# form
a 8a'aScript
a PHP pa%e
Page 104 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
The HTM" -orm
This is the HT# pa%e) ,t contains a simple HT# form and a lin+ to a
8a'aScript:
<html>
<head>
<script src"clienthint)Ws"></script>
</head>
<body>
<.orm>
0irst 6ame5
<inp!t type"te"t" id"t"t$"
onkey!p"sho+Hint*this)val!e,">
</.orm>
<p>2!99estions5 <span id"t"tHint"></span></p>
</body>
</html>
9#ample 9#plained - The HTM" -orm
As you can see. the HT# pa%e a!o'e contains a simple HT# form with
an input field called 4t/tJ4)
The form wor+s li+e this:
J) An e'ent is tri%%ered when the user presses. and releases a +ey in the
input field
M) When the e'ent is tri%%ered. a function called showHint03 is e/ecuted)
3) *elow the form is a <span> called 4t/tHint4) This is used as a
placeholder for the return data of the showHint03 function)
The Bavacript
The 8a'aScript code is stored in 4clienthint)-s4 and lin+ed to the HT#
document:
var "mlHttp;
.!nction sho+Hint*str,
1
i. *str)len9th<,
1
doc!ment)9etPlementAyDd*"t"tHint",)innerHT3@"";
ret!rn;
Page 105 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
4
"mlHttp?et]mlHttpLbWect*,;
i. *"mlHttpn!ll,
1
alert *"Aro+ser does not s!pport HTT7 IeU!est",;
ret!rn;
4
var !rl"9ethint)php";
!rl!rlF"?U"Fstr;
!rl!rlF"Osid"F3ath)random*,;
"mlHttp)onreadystatechan9estateBhan9ed;
"mlHttp)open*"?PT"-!rl-tr!e,;
"mlHttp)send*n!ll,;
4
.!nction stateBhan9ed*,
1
i. *"mlHttp)ready2tate( SS "mlHttp)ready2tate"complete",
1
doc!ment)9etPlementAyDd*"t"tHint",)innerHT3@"mlHttp)responseT
e"t;
4
4
.!nction ?et]mlHttpLbWect*,
1
var "mlHttpn!ll;
try
1
// 0ire.o"- Lpera N)<F- 2a.ari
"mlHttpne+ ]3@HttpIeU!est*,;
4
catch *e,
1
// Dnternet P"plorer
try
1
"mlHttpne+ Cctive]LbWect*"3s"ml&)]3@HTT7",;
4
catch *e,
1
"mlHttpne+ Cctive]LbWect*"3icroso.t)]3@HTT7",;
4
4
ret!rn "mlHttp;
4
9#ample 9#plained
The showHint%& -unction
Page 106 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
This function e/ecutes e'ery time a character is entered in the input field)
,f there is some input in the te/t field 0str)len%th > E3 the function e/ecutes
the followin%:
J) Defines the url 0filename3 to send to the ser'er
M) Adds a parameter 0;3 to the url with the content of the input field
3) Adds a random num!er to pre'ent the ser'er from usin% a cached file
N) Calls on the 2et"mlHttp1!-ect function to create an "#HTTP
o!-ect. and tells the o!-ect to e/ecute a function called stateChan%ed
when a chan%e is tri%%ered
9) 1pens the "#HTTP o!-ect with the %i'en url)
H) Sends an HTTP re;uest to the ser'er
,f the input field is empty. the function simply clears the content of the
t/tHint placeholder)
The state$hanged%& -unction
This function e/ecutes e'ery time the state of the "#HTTP o!-ect
chan%es)
When the state chan%es to N 0or to 4complete43. the content of the t/tHint
placeholder is filled with the response te/t)
The <etAmlHttp7b?ect%& -unction
A8A" applications can only run in we! !rowsers with complete "#
support)
The code a!o'e called a function called 2et"mlHttp1!-ect03)
The purpose of the function is to sol'e the pro!lem of creatin% different
"#HTTP o!-ects for different !rowsers)
This is e/plained in the pre'ious chapter)
The PHP Page
The ser'er pa%e called !y the 8a'aScript code is a simple PHP file called
4%ethint)php4)
Page 107 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
The code in the 4%ethint)php4 chec+s an array of names and returns the
correspondin% names to the client:
<?php
// 0ill !p array +ith names
$a;="Cnna";
$a;="Arittany";
$a;="Binderella";
$a;="/iana";
$a;="Pva";
$a;="0iona";
$a;="?!nda";
$a;="He9e";
$a;="Dn9a";
$a;=":ohanna";
$a;="Hitty";
$a;="@inda";
$a;="6ina";
$a;="Lphelia";
$a;="7et!nia";
$a;="Cmanda";
$a;="IaU!el";
$a;="Bindy";
$a;="/oris";
$a;="Pve";
$a;="Pvita";
$a;="2!nniva";
$a;="Tove";
$a;="Qnni";
$a;="Giolet";
$a;="@iVa";
$a;="PliVabeth";
$a;="Pllen";
$a;="Wenche";
$a;="Gicky";
//9et the U parameter .rom QI@
$U$_?PT;"U"=;
//look!p all hints .rom array i. len9th o. U><
i. *strlen*$U, > <,
1
$hint"";
.or*$i<; $i<co!nt*$a,; $iFF,
1
i. *strtolo+er*$U,strtolo+er*s!bstr*$a;$i=-<-strlen*$U,,,,
1
i. *$hint"",
1
$hint$a;$i=;
4
Page 108 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
else
1
$hint$hint)" - ")$a;$i=;
4
4
4
4
//2et o!tp!t to "no s!99estion" i. no hint +ere .o!nd
//or to the correct val!es
i. *$hint "",
1
$response"no s!99estion";
4
else
1
$response$hint;
4
//o!tp!t the response
echo $response;
?>
,f there is any te/t sent from the 8a'aScript 0strlen0A;3 > E3 the followin%
happens:
J) Find a name matchin% the characters sent from the 8a'aScript
M) ,f more than one name is found. include all names in the response
strin%
3) ,f no matchin% names were found. set response to 4no su%%estion4
N) ,f one or more matchin% names were found. set response to these
names
9) The response is sent to the 4t/tHint4 placeholder
PHP and ABAA AM" 9#ample
A8A" can !e used for interacti'e communication with an "# file)
ABAA AM" 9#ample
,n the A8A" e/ample !elow we will demonstrate how a we! pa%e can fetch
information from an "# file usin% A8A" technolo%y)
elect a $1 in the 2o# 2elow
Page 109 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
Select a CD:
T,TE: The 'ery !est of
A6T,ST: Cat Ste'ens
C15BT6T: 5U
C1#PABT: ,sland
P6,CE: P)FE
TEA6: JFFE
This e/ample consists of four pa%es:
a simple HT# form
an "# file
a 8a'aScript
a PHP pa%e
The HTM" -orm
The e/ample a!o'e contains a simple HT# form and a lin+ to a 8a'aScript:
<html>
<head>
<script src"selectcd)Ws"></script>
</head>
<body>
<.orm>
2elect a B/5
<select name"cds" onchan9e"sho+B/*this)val!e,">
<option val!e"Aob /ylan">Aob /ylan</option>
<option val!e"Aee ?ees">Aee ?ees</option>
<option val!e"Bat 2tevens">Bat 2tevens</option>
</select>
</.orm>
<p>
<div id"t"tHint"><b>B/ in.o +ill be listed here)</b></div>
</p>
</body>
</html>
9#ample 9#plained
As you can see it is -ust a simple HT# form with a simple drop down !o/
called 4cds4)
The para%raph !elow the form contains a di' called 4t/tHint4) The di' is
used as a placeholder for info retrie'ed from the we! ser'er)
Page 110 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
When the user selects data. a function called 4showCD4 is e/ecuted) The
e/ecution of the function is tri%%ered !y the 4onchan%e4 e'ent)
,n other words: Each time the user chan%es the 'alue in the drop down !o/.
the function showCD is called)
The AM" -ile
The "# file is 4cdCcatalo%)/ml4) This document contains a CD collection)
The Bavacript
This is the 8a'aScript code stored in the file 4selectcd)-s4:
var "mlHttp
.!nction sho+B/*str,
1
"mlHttp?et]mlHttpLbWect*,
i. *"mlHttpn!ll,
1
alert *"Aro+ser does not s!pport HTT7 IeU!est",
ret!rn
4
var !rl"9etcd)php"
!rl!rlF"?U"Fstr
!rl!rlF"Osid"F3ath)random*,
"mlHttp)onreadystatechan9estateBhan9ed
"mlHttp)open*"?PT"-!rl-tr!e,
"mlHttp)send*n!ll,
4
.!nction stateBhan9ed*,
1
i. *"mlHttp)ready2tate( SS "mlHttp)ready2tate"complete",
1
doc!ment)9etPlementAyDd*"t"tHint",)innerHT3@"mlHttp)responseT
e"t
4
4
.!nction ?et]mlHttpLbWect*,
1
var "mlHttpn!ll;
try
1
// 0ire.o"- Lpera N)<F- 2a.ari
"mlHttpne+ ]3@HttpIeU!est*,;
4
catch *e,
Page 111 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
1
// Dnternet P"plorer
try
1
"mlHttpne+ Cctive]LbWect*"3s"ml&)]3@HTT7",;
4
catch *e,
1
"mlHttpne+ Cctive]LbWect*"3icroso.t)]3@HTT7",;
4
4
ret!rn "mlHttp;
4
9#ample 9#plained
The stateChan%ed03 and 2et"mlHttp1!-ect functions are the same as in the
last chapter. you can %o to the pre'ious pa%e for an e/planation of those
The show$1%& -unction
,f an item in the drop down !o/ is selected the function e/ecutes the
followin%:
J) Calls on the 2et"mlHttp1!-ect function to create an "#HTTP
o!-ect
M) Defines the url 0filename3 to send to the ser'er
3) Adds a parameter 0;3 to the url with the content of the input field
N) Adds a random num!er to pre'ent the ser'er from usin% a cached file
9) Call stateChan%ed when a chan%e is tri%%ered
H) 1pens the "#HTTP o!-ect with the %i'en url)
I) Sends an HTTP re;uest to the ser'er
The PHP Page
The ser'er pa%ed called !y the 8a'aScript. is a simple PHP file called
4%etcd)php4)
The pa%e is written in PHP usin% the "# D1# to load the "# document
4cdCcatalo%)/ml4)
The code runs a ;uery a%ainst the "# file and returns the result as HT#:
<?php
$U$_?PT;"U"=;
Page 112 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
$"ml/oc ne+ /L3/oc!ment*,;
$"ml/ocR>load*"cd_catalo9)"ml",;
$"$"ml/ocR>9etPlementsAyTa96ame*>CITD2T>,;
.or *$i<; $i<$"R>len9thR$; $iFF,
1
//7rocess only element nodes
i. *$"R>item*$i,R>nodeType$,
1
i. *$"R>item*$i,R>child6odesR>item*<,R>nodeGal!e $U,
1
$y*$"R>item*$i,R>parent6ode,;
4
4
4
$cd*$yR>child6odes,;
.or *$i<;$i<$cdR>len9th;$iFF,
1
//7rocess only element nodes
i. *$cdR>item*$i,R>nodeType$,
1
echo*$cdR>item*$i,R>node6ame,;
echo*"5 ",;
echo*$cdR>item*$i,R>child6odesR>item*<,R>nodeGal!e,;
echo*"<br />",;
4
4
?>
9#ample 9#plained
When the ;uery is sent from the 8a'aScript to the PHP pa%e the followin%
happens:
J) PHP creates an "# D1# o!-ect of the 4cdCcatalo%)/ml4 file
M) All 4artist4 elements 0nodetypes L J3 are looped throu%h to find a
name matchin% the one sent from the 8a'aScript)
3) The CD containin% the correct artist is found
N) The al!um information is output and sent to the 4t/tHint4 placeholder
PHP and ABAA My." 1atabase 9#ample
A8A" can !e used for interacti'e communication with a data!ase)
ABAA 1atabase 9#ample
Page 113 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
,n the A8A" e/ample !elow we will demonstrate how a we! pa%e can fetch
information from a #yS$ data!ase usin% A8A" technolo%y)
elect a 0ame in the 2o# 2elow
Select a 5ser:
-irstname "astname Age Hometown Bob
8oseph Swanson 3F $uaho% Police 1fficer
This e/ample consists of four elements:
a #yS$ data!ase
a simple HT# form
a 8a'aScript
a PHP pa%e
The 1atabase
The data!ase we will !e usin% in this e/ample loo+s li+e this:
id -irst0ame "ast0ame Age Hometown Bob
J Peter 2riffin NJ $uaho% *rewery
M ois 2riffin NE Bewport Piano Teacher
3 8oseph Swanson 3F $uaho% Police 1fficer
N 2lenn $ua%mire NJ $uaho% Pilot
The HTM" -orm
The e/ample a!o'e contains a simple HT# form and a lin+ to a 8a'aScript:
<html>
<head>
<script src"select!ser)Ws"></script>
</head>
<body>
<.orm>
2elect a Qser5
<select name"!sers" onchan9e"sho+Qser*this)val!e,">
<option val!e"$">7eter ?ri..in</option>
<option val!e"&">@ois ?ri..in</option>
<option val!e"'">?lenn 8!a9mire</option>
<option val!e"(">:oseph 2+anson</option>
</select>
Page 114 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
</.orm>
<p>
<div id"t"tHint"><b>Qser in.o +ill be listed here)</b></div>
</p>
</body>
</html>
9#ample 9#plained - The HTM" -orm
As you can see it is -ust a simple HT# form with a drop down !o/ called
4users4 with names and the 4id4 from the data!ase as option 'alues)
The para%raph !elow the form contains a di' called 4t/tHint4) The di' is
used as a placeholder for info retrie'ed from the we! ser'er)
When the user selects data. a function called 4show5ser034 is e/ecuted) The
e/ecution of the function is tri%%ered !y the 4onchan%e4 e'ent)
,n other words: Each time the user chan%es the 'alue in the drop down !o/.
the function show5ser03 is called)
The Bavacript
This is the 8a'aScript code stored in the file 4selectuser)-s4:
var "mlHttp
.!nction sho+Qser*str,
1
"mlHttp?et]mlHttpLbWect*,
i. *"mlHttpn!ll,
1
alert *"Aro+ser does not s!pport HTT7 IeU!est",
ret!rn
4
var !rl"9et!ser)php"
!rl!rlF"?U"Fstr
!rl!rlF"Osid"F3ath)random*,
"mlHttp)onreadystatechan9estateBhan9ed
"mlHttp)open*"?PT"-!rl-tr!e,
"mlHttp)send*n!ll,
4
.!nction stateBhan9ed*,
1
i. *"mlHttp)ready2tate( SS "mlHttp)ready2tate"complete",
1
doc!ment)9etPlementAyDd*"t"tHint",)innerHT3@"mlHttp)responseT
Page 115 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
e"t
4
4
.!nction ?et]mlHttpLbWect*,
1
var "mlHttpn!ll;
try
1
// 0ire.o"- Lpera N)<F- 2a.ari
"mlHttpne+ ]3@HttpIeU!est*,;
4
catch *e,
1
//Dnternet P"plorer
try
1
"mlHttpne+ Cctive]LbWect*"3s"ml&)]3@HTT7",;
4
catch *e,
1
"mlHttpne+ Cctive]LbWect*"3icroso.t)]3@HTT7",;
4
4
ret!rn "mlHttp;
4
9#ample 9#plained
The stateChan%ed03 and 2et"mlHttp1!-ect functions are the same as in the
PHP A8A" Su%%est chapter. you can %o to there for an e/planation of those)
The show8ser%& -unction
,f an item in the drop down !o/ is selected the function e/ecutes the
followin%:
J) Calls on the 2et"mlHttp1!-ect function to create an "#HTTP
o!-ect
M) Defines the url 0filename3 to send to the ser'er
3) Adds a parameter 0;3 to the url with the content of the dropdown !o/
N) Adds a random num!er to pre'ent the ser'er from usin% a cached file
9) Call stateChan%ed when a chan%e is tri%%ered
H) 1pens the "#HTTP o!-ect with the %i'en url)
I) Sends an HTTP re;uest to the ser'er
The PHP Page
Page 116 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
The ser'er pa%e called !y the 8a'aScript. is a simple PHP file called
4%etuser)php4)
The pa%e is written in PHP and uses a #yS$ data!ase)
The code runs a S$ ;uery a%ainst a data!ase and returns the result as an
HT# ta!le:
<?php
$U$_?PT;"U"=;
$con mysUl_connect*>localhost>- >peter>- >abc$&'>,;
i. *#$con,
1
die*>Bo!ld not connect5 > ) mysUl_error*,,;
4
mysUl_select_db*"aWa"_demo"- $con,;
$sUl"2P@PBT * 0IL3 !ser WHPIP id >")$U)">";
$res!lt mysUl_U!ery*$sUl,;
echo "<table border>$>>
<tr>
<th>0irstname</th>
<th>@astname</th>
<th>C9e</th>
<th>Hometo+n</th>
<th>:ob</th>
</tr>";
+hile*$ro+ mysUl_.etch_array*$res!lt,,
1
echo "<tr>";
echo "<td>" ) $ro+;>0irst6ame>= ) "</td>";
echo "<td>" ) $ro+;>@ast6ame>= ) "</td>";
echo "<td>" ) $ro+;>C9e>= ) "</td>";
echo "<td>" ) $ro+;>Hometo+n>= ) "</td>";
echo "<td>" ) $ro+;>:ob>= ) "</td>";
echo "</tr>";
4
echo "</table>";
mysUl_close*$con,;
?>
Page 117 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
9#ample 9#plained
When the ;uery is sent from the 8a'aScript to the PHP pa%e the followin%
happens:
J) PHP opens a connection to a #yS$ ser'er
M) The 4user4 with the specified name is found
3) A ta!le is created and the data is inserted and sent to the 4t/tHint4
placeholder
PHP and ABAA responseAM" 9#ample
A8A" can !e used to return data!ase information as "#)
ABAA 1atabase as AM" 9#ample
,n the A8A" e/ample !elow we will demonstrate how a we! pa%e can fetch
information from a #yS$ data!ase. con'ert it to an "# document. and
use it to display information in se'eral different places)
This e/ample my seem a lot li+e the 4PHP A8A" Data!ase4 e/ample in the
last chapter. howe'er there is a !i% difference: in this e/ample we %et the
data from the PHP pa%e as "# usin% the response"# function)
6ecei'in% the response as an "# document allows us to update this pa%e
se'eral places. instead of -ust recei'in% a PHP output and displayin% it)
Page 118 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
,n this e/ample we will update se'eral <span> elements with the information
we recei'e from the data!ase)
elect a 0ame in the 2o# 2elow
Select a 5ser:
<lenn .uagmire
Pilot
A%e: NJ
From: $uaho%
This e/ample consists of four elements:
a #yS$ data!ase
a simple HT# form
a 8a'aScript
a PHP pa%e
The 1atabase
The data!ase we will !e usin% in this e/ample loo+s li+e this:
id -irst0ame "ast0ame Age Hometown Bob
J Peter 2riffin NJ $uaho% *rewery
M ois 2riffin NE Bewport Piano Teacher
3 8oseph Swanson 3F $uaho% Police 1fficer
N 2lenn $ua%mire NJ $uaho% Pilot
The HTM" -orm
The e/ample a!o'e contains a simple HT# form and a lin+ to a 8a'aScript:
<html>
<head>
<script src"response"ml)Ws"></script>
</head>
<body>
<.orm>
2elect a Qser5
<select name"!sers" onchan9e"sho+Qser*this)val!e,">
Page 119 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
<option val!e"$">7eter ?ri..in</option>
<option val!e"&">@ois ?ri..in</option>
<option val!e"'">?lenn 8!a9mire</option>
<option val!e"(">:oseph 2+anson</option>
</select>
</.orm>
<h&><span id".irstname"></span>
Onbsp;<span id"lastname"></span></h&>
<span id"Wob"></span>
<div style"te"tRali9n5 ri9ht">
<span id"a9e_te"t"></span>
<span id"a9e"></span>
<span id"hometo+n_te"t"></span>
<span id"hometo+n"></span>
</div>
</body>
</html>
9#ample 9#plained - The HTM" -orm
The HT# form is a drop down !o/ called 4users4 with names and
the 4id4 from the data!ase as option 'alues)
*elow the form there are se'eral different <span> elements which are
used to as placeholders for the different 'alues we will retri'e)
When the user selects data. a function called 4show5ser034 is
e/ecuted) The e/ecution of the function is tri%%ered !y the
4onchan%e4 e'ent)
,n other words: Each time the user chan%es the 'alue in the drop down !o/.
the function show5ser03 is called and outputs the result in the specified
<span> elements)
The Bavacript
This is the 8a'aScript code stored in the file 4response/ml)-s4:
var "mlHttp
.!nction sho+Qser*str,
1
"mlHttp?et]mlHttpLbWect*,
i. *"mlHttpn!ll,
1
alert *"Aro+ser does not s!pport HTT7 IeU!est",
ret!rn
4
var !rl"response"ml)php"
Page 120 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
!rl!rlF"?U"Fstr
!rl!rlF"Osid"F3ath)random*,
"mlHttp)onreadystatechan9estateBhan9ed
"mlHttp)open*"?PT"-!rl-tr!e,
"mlHttp)send*n!ll,
4
.!nction stateBhan9ed*,
1
i. *"mlHttp)ready2tate( SS "mlHttp)ready2tate"complete",
1
"ml/oc"mlHttp)response]3@;
doc!ment)9etPlementAyDd*".irstname",)innerHT3@
"ml/oc)9etPlementsAyTa96ame*".irstname",;<=)child6odes;<=)node
Gal!e;
doc!ment)9etPlementAyDd*"lastname",)innerHT3@
"ml/oc)9etPlementsAyTa96ame*"lastname",;<=)child6odes;<=)nodeG
al!e;
doc!ment)9etPlementAyDd*"Wob",)innerHT3@
"ml/oc)9etPlementsAyTa96ame*"Wob",;<=)child6odes;<=)nodeGal!e;
doc!ment)9etPlementAyDd*"a9e_te"t",)innerHT3@"C9e5 ";
doc!ment)9etPlementAyDd*"a9e",)innerHT3@
"ml/oc)9etPlementsAyTa96ame*"a9e",;<=)child6odes;<=)nodeGal!e;
doc!ment)9etPlementAyDd*"hometo+n_te"t",)innerHT3@"<br/>0rom5
";
doc!ment)9etPlementAyDd*"hometo+n",)innerHT3@
"ml/oc)9etPlementsAyTa96ame*"hometo+n",;<=)child6odes;<=)nodeG
al!e;
4
4
.!nction ?et]mlHttpLbWect*,
1
var obW]3@Httpn!ll
i. *+indo+)]3@HttpIeU!est,
1
obW]3@Httpne+ ]3@HttpIeU!est*,
4
else i. *+indo+)Cctive]LbWect,
1
obW]3@Httpne+ Cctive]LbWect*"3icroso.t)]3@HTT7",
4
ret!rn obW]3@Http
4
9#ample 9#plained
The show5ser03 and 2et"mlHttp1!-ect functions are the same as in the PHP
A8A" Data!ase chapter. you can %o to there for an e/planation of those)
Page 121 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
The state$hanged%& -unction
,f an item in the drop down !o/ is selected the function e/ecutes the
followin%:
J) Defines the 4/mlDoc4 'aria!le as an /ml document usin% the
response"# function
M) 6etrie'es data from the /ml documents and places them in the correct
<span> elements
The PHP Page
The ser'er pa%e called !y the 8a'aScript. is a simple PHP file called
4response/ml)php4)
The pa%e is written in PHP and uses a #yS$ data!se)
The code runs a S$ ;uery a%ainst a data!ase and returns the result as an
"# document:
<?php
header*>BontentRType5 te"t/"ml>,;
header*"BacheRBontrol5 noRcache- m!stRrevalidate",;
//C date in the past
header*"P"pires5 3on- &% :!l $\\K <E5<<5<< ?3T",;
$U$_?PT;"U"=;
$con mysUl_connect*>localhost>- >peter>- >abc$&'>,;
i. *#$con,
1
die*>Bo!ld not connect5 > ) mysUl_error*,,;
4
mysUl_select_db*"aWa"_demo"- $con,;
$sUl"2P@PBT * 0IL3 !ser WHPIP id ")$U)"";
$res!lt mysUl_U!ery*$sUl,;
echo ><?"ml version"$)<" encodin9"D2LRNNE\R$"?>
<person>>;
+hile*$ro+ mysUl_.etch_array*$res!lt,,
1
echo "<.irstname>" ) $ro+;>0irst6ame>= ) "</.irstname>";
echo "<lastname>" ) $ro+;>@ast6ame>= ) "</lastname>";
echo "<a9e>" ) $ro+;>C9e>= ) "</a9e>";
echo "<hometo+n>" ) $ro+;>Hometo+n>= ) "</hometo+n>";
echo "<Wob>" ) $ro+;>:ob>= ) "</Wob>";
4
echo "</person>";
Page 122 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
mysUl_close*$con,;
?>
9#ample 9#plained
When the ;uery is sent from the 8a'aScript to the PHP pa%e the followin%
happens:
J) The content(type of the PHP document is set to !e 4te/t:/ml4
M) The PHP document is set to 4no(cache4 to pre'ent cachin%
3) The A; 'aria!le is set to !e the data sent from the html pa%e
N) PHP opens a connection to a #yS$ ser'er
9) The 4user4 with the specified id is found
H) The data is outputted as an /ml document
PHP and ABAA "ive earch
A8A" can !e used for a more user friendly and interacti'e search)
ABAA "ive earch
,n the A8A" e/ample !elow we will demonstrate a li'e search. where the
ser'er %ets search results while the user types)
i'e search has many !enefits compared to traditional searchin%:
#atchin% results are shown as you type
6esults narrow as you continue typin%
,f results !ecome too narrow. remo'e characters to see a !roader
result
earch for a !Fchools page in the 2o# 2elow
This e/ample consists of four pa%es:
a simple HT# form
a 8a'aScript
a PHP pa%e
an "# document
Page 123 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
,n this e/ample the results are found in an "# document 0lin+s)/ml3) To
ma+e this e/ample small and simple. only ei%ht results are a'aila!le)
The HTM" -orm
This is the HT# pa%e) ,t contains a simple HT# form. style for the form
and a lin+ to a 8a'aScript:
<html>
<head>
<script src"livesearch)Ws"></script>
<style type"te"t/css">
[livesearch
1
mar9in5<p";
+idth5$\(p";
4
[t"t$
1
mar9in5<p";
4
</style>
</head>
<body>
<.orm>
<inp!t type"te"t" id"t"t$" siVe"'<"
onkey!p"sho+Ies!lt*this)val!e,">
<div id"livesearch"></div>
</.orm>
</body>
</html>
9#ample 9#plained - The HTM" -orm
As you can see. the HT# pa%e a!o'e contains a simple HT# form with
an input field called 4t/tJ4)
The form wor+s li+e this:
J) An e'ent is tri%%ered when the user presses. and releases a +ey in the
input field
M) When the e'ent is tri%%ered. a function called show6esult03 is
e/ecuted)
3) *elow the form is a <di'> called 4li'esearch4) This is used as a
placeholder for the return data of the show6esult03 function)
The Bavacript
Page 124 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
The 8a'aScript code is stored in 4li'esearch)-s4 and lin+ed to the HT#
document:
var "mlHttp
.!nction sho+Ies!lt*str,
1
i. *str)len9th<,
1
doc!ment)9etPlementAyDd*"livesearch",)
innerHT3@"";
doc!ment)9etPlementAyDd*"livesearch",)
style)border"<p"";
ret!rn
4
"mlHttp?et]mlHttpLbWect*,
i. *"mlHttpn!ll,
1
alert *"Aro+ser does not s!pport HTT7 IeU!est",
ret!rn
4
var !rl"livesearch)php"
!rl!rlF"?U"Fstr
!rl!rlF"Osid"F3ath)random*,
"mlHttp)onreadystatechan9estateBhan9ed
"mlHttp)open*"?PT"-!rl-tr!e,
"mlHttp)send*n!ll,
4
.!nction stateBhan9ed*,
1
i. *"mlHttp)ready2tate( SS "mlHttp)ready2tate"complete",
1
doc!ment)9etPlementAyDd*"livesearch",)
innerHT3@"mlHttp)responseTe"t;
doc!ment)9etPlementAyDd*"livesearch",)
style)border"$p" solid [CECBA&";
4
4
.!nction ?et]mlHttpLbWect*,
1
var "mlHttpn!ll;
try
1
// 0ire.o"- Lpera N)<F- 2a.ari
"mlHttpne+ ]3@HttpIeU!est*,;
4
catch *e,
1
// Dnternet P"plorer
Page 125 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
try
1
"mlHttpne+ Cctive]LbWect*"3s"ml&)]3@HTT7",;
4
catch *e,
1
"mlHttpne+ Cctive]LbWect*"3icroso.t)]3@HTT7",;
4
4
ret!rn "mlHttp;
4
9#ample 9#plained
The 2et"mlHttp1!-ect function is the same as in the PHP A8A" Su%%est
chapter)
The show)esult%& -unction
This function e/ecutes e'ery time a character is entered in the input field)
,f there is no input in the te/t field 0str)len%th LL E3 the function sets the
return field to empty and remo'es any !order around it)
Howe'er. if there is any input in the te/t field the function e/ecutes the
followin%:
J) Defines the url 0filename3 to send to the ser'er
M) Adds a parameter 0;3 to the url with the content of the input field
3) Adds a random num!er to pre'ent the ser'er from usin% a cached file
N) Calls on the 2et"mlHttp1!-ect function to create an "#HTTP
o!-ect. and tells the o!-ect to e/ecute a function called stateChan%ed
when a chan%e is tri%%ered
9) 1pens the "#HTTP o!-ect with the %i'en url)
H) Sends an HTTP re;uest to the ser'er
The state$hanged%& -unction
This function e/ecutes e'ery time the state of the "#HTTP o!-ect
chan%es)
When the state chan%es to N 0or to 4complete43. the content of the t/tHint
placeholder is filled with the response te/t. and a !order is set around the
return field)
Page 126 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
The PHP Page
The ser'er pa%e called !y the 8a'aScript code is a PHP file called
4li'esearch)php4)
The code in the 4li'esearch)php4 chec+s the "# document 4lin+s)/ml4)
This document contains titles and 567s of some pa%es on W3Schools)com)
The code searches the "# file for titles matchin% the search strin% and
returns the result as HT#:
<?php
$"ml/oc ne+ /L3/oc!ment*,;
$"ml/ocR>load*"links)"ml",;
$"$"ml/ocR>9etPlementsAyTa96ame*>link>,;
//9et the U parameter .rom QI@
$U$_?PT;"U"=;
//look!p all links .rom the "ml .ile i. len9th o. U><
i. *strlen*$U, > <,
1
$hint"";
.or*$i<; $i<*$"R>len9th,; $iFF,
1
$y$"R>item*$i,R>9etPlementsAyTa96ame*>title>,;
$V$"R>item*$i,R>9etPlementsAyTa96ame*>!rl>,;
i. *$yR>item*<,R>nodeType$,
1
//.ind a link matchin9 the search te"t
i. *stristr*$yR>item*<,R>child6odesR>item*<,R>nodeGal!e-$U,,
1
i. *$hint"",
1
$hint"<a hre.>" )
$VR>item*<,R>child6odesR>item*<,R>nodeGal!e )
"> tar9et>_blank>>" )
$yR>item*<,R>child6odesR>item*<,R>nodeGal!e ) "</a>";
4
else
1
$hint$hint ) "<br /><a hre.>" )
$VR>item*<,R>child6odesR>item*<,R>nodeGal!e )
"> tar9et>_blank>>" )
$yR>item*<,R>child6odesR>item*<,R>nodeGal!e ) "</a>";
4
4
4
4
Page 127 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
4
// 2et o!tp!t to "no s!99estion" i. no hint +ere .o!nd
// or to the correct val!es
i. *$hint "",
1
$response"no s!99estion";
4
else
1
$response$hint;
4
//o!tp!t the response
echo $response;
?>
,f there is any te/t sent from the 8a'aScript 0strlen0A;3 > E3 the followin%
happens:
J) PHP creates an "# D1# o!-ect of the 4lin+s)/ml4 file
M) All 4title4 elements 0nodetypes L J3 are looped throu%h to find a
name matchin% the one sent from the 8a'aScript
3) The lin+ containin% the correct title is found and set as the
4Aresponse4 'aria!le) ,f more than one match is found. all matches
are added to the 'aria!le
N) ,f no matches are found the Aresponse 'aria!le is set to 4no
su%%estion4
9) The Aresult 'aria!le is output and sent to the 4li'esearch4 placeholder
PHP and ABAA ) )eader
An 6SS 6eader is used to read 6SS Feeds
6SS allows fast !rowsin% for news and updates
ABAA ) )eader
,n the A8A" e/ample !elow we will demonstrate an 6SS reader where the
content from the 6SS is loaded into the we!pa%e without refreshin%)
elect an ) 0ews -eed in the 2o# 2elow
Select an 6SS(Feed:
Page 128 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
msn!c)com: Top msn!c)com headlines
#sn!c)com is a leader in !rea+in% news and ori%inal -ournalism)
5neasy alliance !ehind 2aDa stri+es
The ,sraeli campai%n on 2aDa is !ein% led !y an unli+ely
%roup of three ,sraeli leaders who ha'e all !ut sta+ed their
political futures on the hi%hly ris+y military operation)
*la%o-e'ich ma+es Senate pic+
Defyin% 5)S) Senate leaders and his own state7s lawma+ers.
2o') 6od *la%o-e'ich announced Tuesday the appointment
of a Senate replacement for President(elect *arac+ 1!ama)
,srael mulls halt in 2aDa stri+es
,srael is considerin% haltin% its 2aDa offensi'e temporarily to
%i'e Hamas militants an openin% to halt roc+et fire on ,srael.
an ,sraeli defense official said Tuesday)
This e/ample consists of three pa%es:
a simple HT# form
a 8a'aScript
a PHP pa%e)
The HTM" -orm
This is the HT# pa%e) ,t contains a simple HT# form and a lin+ to a
8a'aScript:
<html>
<head>
<script type"te"t/Wavascript" src"9etrss)Ws"></script>
</head>
<body>
<.orm>
2elect an I22R0eed5
<select onchan9e"sho+I22*this)val!e,">
<option val!e"?oo9le">?oo9le 6e+s</option>
<option val!e"326AB">326AB 6e+s</option>
</select>
</.orm>
Page 129 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
<p><div id"rssL!tp!t">
<b>I22 0eed +ill be listed here)</b></div></p>
</body>
</html>
9#ample 9#plained - The HTM" -orm
As you can see. the HT# pa%e a!o'e contains a simple HT# form with a
drop(down !o/)
The form wor+s li+e this:
J) An e'ent is tri%%ered when the user selects an option in the drop
down !o/
M) When the e'ent is tri%%ered. a function called show6SS03 is e/ecuted)
3) *elow the form is a <di'> called 4rss1utput4) This is used as a
placeholder for the return data of the show6SS03 function)
The Bavacript
The 8a'aScript code is stored in 4%etrss)-s4 and lin+ed to the HT#
document:
var "mlHttp
.!nction sho+I22*str,
1
"mlHttp?et]mlHttpLbWect*,
i. *"mlHttpn!ll,
1
alert *"Aro+ser does not s!pport HTT7 IeU!est",
ret!rn
4
var !rl"9etrss)php"
!rl!rlF"?U"Fstr
!rl!rlF"Osid"F3ath)random*,
"mlHttp)onreadystatechan9estateBhan9ed
"mlHttp)open*"?PT"-!rl-tr!e,
"mlHttp)send*n!ll,
4
.!nction stateBhan9ed*,
1
i. *"mlHttp)ready2tate( SS "mlHttp)ready2tate"complete",
1
doc!ment)9etPlementAyDd*"rssL!tp!t",
)innerHT3@"mlHttp)responseTe"t
Page 130 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
4
4
.!nction ?et]mlHttpLbWect*,
1
var "mlHttpn!ll;
try
1
// 0ire.o"- Lpera N)<F- 2a.ari
"mlHttpne+ ]3@HttpIeU!est*,;
4
catch *e,
1
// Dnternet P"plorer
try
1
"mlHttpne+ Cctive]LbWect*"3s"ml&)]3@HTT7",;
4
catch *e,
1
"mlHttpne+ Cctive]LbWect*"3icroso.t)]3@HTT7",;
4
4
ret!rn "mlHttp;
4
9#ample 9#plained
The stateChan%ed03 and 2et"mlHttp1!-ect functions are the same as in the
PHP A8A" Su%%est chapter)
The show)%& -unction
E'ery time an option is selected in the input field this function e/ecutes the
followin%:
J) Defines the url 0filename3 to send to the ser'er
M) Adds a parameter 0;3 to the url with the selected option from the drop
down !o/
3) Adds a random num!er to pre'ent the ser'er from usin% a cached file
N) Calls on the 2et"mlHttp1!-ect function to create an "#HTTP
o!-ect. and tells the o!-ect to e/ecute a function called stateChan%ed
when a chan%e is tri%%ered
9) 1pens the "#HTTP o!-ect with the %i'en url)
H) Sends an HTTP re;uest to the ser'er
Page 131 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
The PHP Page
The ser'er pa%e called !y the 8a'aScript code is a PHP file called
4%etrss)php4:
<?php
//9et the U parameter .rom QI@
$U$_?PT;"U"=;
//.ind o!t +hich .eed +as selected
i.*$U"?oo9le",
1
$"ml*"http5//ne+s)9oo9le)com/ne+s?ned!sOtopichOo!tp!trss",
;
4
elsei.*$U"326AB",
1
$"ml*"http5//rss)msnbc)msn)com/id/'<'&<\$/device/rss/rss)"ml"
,;
4
$"ml/oc ne+ /L3/oc!ment*,;
$"ml/ocR>load*$"ml,;
//9et elements .rom "<channel>"
$channel$"ml/ocR>9etPlementsAyTa96ame*>channel>,R>item*<,;
$channel_title $channelR>9etPlementsAyTa96ame*>title>,
R>item*<,R>child6odesR>item*<,R>nodeGal!e;
$channel_link $channelR>9etPlementsAyTa96ame*>link>,
R>item*<,R>child6odesR>item*<,R>nodeGal!e;
$channel_desc $channelR>9etPlementsAyTa96ame*>description>,
R>item*<,R>child6odesR>item*<,R>nodeGal!e;
//o!tp!t elements .rom "<channel>"
echo*"<p><a hre.>" ) $channel_link
) ">>" ) $channel_title ) "</a>",;
echo*"<br />",;
echo*$channel_desc ) "</p>",;
//9et and o!tp!t "<item>" elements
$"$"ml/ocR>9etPlementsAyTa96ame*>item>,;
.or *$i<; $i<&; $iFF,
1
$item_title$"R>item*$i,R>9etPlementsAyTa96ame*>title>,
R>item*<,R>child6odesR>item*<,R>nodeGal!e;
$item_link$"R>item*$i,R>9etPlementsAyTa96ame*>link>,
R>item*<,R>child6odesR>item*<,R>nodeGal!e;
$item_desc$"R>item*$i,R>9etPlementsAyTa96ame*>description>,
R>item*<,R>child6odesR>item*<,R>nodeGal!e;
echo *"<p><a hre.>" ) $item_link
) ">>" ) $item_title ) "</a>",;
echo *"<br />",;
echo *$item_desc ) "</p>",;
Page 132 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
4
?>
9#ample 9#plained - The PHP Page
When an option is sent from the 8a'aScript the followin% happens:
J) PHP finds out which 6SS feed was selected
M) An "# D1# o!-ect is created for the selected 6SS feed
3) The elements from the 6SS channel are found and outputted
N) The three first elements from the 6SS items are looped throu%h and
outputted
PHP and ABAA Poll
ABAA uggest
,n the A8A" e/ample !elow we will demonstrate a poll where the we! pa%e
can %et the result without reloadin%)
1o you li>e PHP and ABAA so far,
Tes:
Bo:
This e/ample consists of four pa%es:
a simple HT# form
a 8a'aScript
a PHP pa%e
a te/t file to store the results
The HTM" -orm
This is the HT# pa%e) ,t contains a simple HT# form and a lin+ to a
8a'aScript:
<html>
<head>
<script src"poll)Ws"></script>
</head>
<body>
Page 133 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
<div id"poll">
<h&>/o yo! like 7H7 and C:C] so .ar?</h&>
<.orm>
Mes5
<inp!t type"radio" name"vote"
val!e"<" onclick"9etGote*this)val!e,">
<br />6o5
<inp!t type"radio" name"vote"
val!e"$" onclick"9etGote*this)val!e,">
</.orm>
</div>
</body>
</html>
9#ample 9#plained - The HTM" -orm
As you can see. the HT# pa%e a!o'e contains a simple HT# form inside
a 4<di'>4 with two radio !uttons)
The form wor+s li+e this:
J) An e'ent is tri%%ered when the user selects the 4yes4 or 4no4 option
M) When the e'ent is tri%%ered. a function called %et@ote03 is e/ecuted)
3) Around the form is a <di'> called 4poll4) When the data is returned
from the %et@ote03 function. the return data will replace the form)
The Te#t -ile
The te/t file 0pollCresult)t/t3 is where we store the data from the poll)
,t is stored li+e this:
<SS<
The first num!er represents the 4Tes4 'otes. the second num!er represents
the 4Bo4 'otes)
0ote5 6emem!er to allow your we! ser'er to edit the te/t file) Do 07T %i'e
e'eryone access. -ust the we! ser'er 0PHP3)
The Bavacript
The 8a'aScript code is stored in 4poll)-s4 and lin+ed to in the HT#
document:
Page 134 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
var "mlHttp
.!nction 9etGote*int,
1
"mlHttp?et]mlHttpLbWect*,
i. *"mlHttpn!ll,
1
alert *"Aro+ser does not s!pport HTT7 IeU!est",
ret!rn
4
var !rl"poll_vote)php"
!rl!rlF"?vote"Fint
!rl!rlF"Osid"F3ath)random*,
"mlHttp)onreadystatechan9estateBhan9ed
"mlHttp)open*"?PT"-!rl-tr!e,
"mlHttp)send*n!ll,
4
.!nction stateBhan9ed*,
1
i. *"mlHttp)ready2tate( SS "mlHttp)ready2tate"complete",
1
doc!ment)9etPlementAyDd*"poll",)
innerHT3@"mlHttp)responseTe"t;
4
4
.!nction ?et]mlHttpLbWect*,
1
var obW]3@Httpn!ll
i. *+indo+)]3@HttpIeU!est,
1
obW]3@Httpne+ ]3@HttpIeU!est*,
4
else i. *+indo+)Cctive]LbWect,
1
obW]3@Httpne+ Cctive]LbWect*"3icroso.t)]3@HTT7",
4
ret!rn obW]3@Http
4
9#ample 9#plained
The stateChan%ed03 and 2et"mlHttp1!-ect functions are the same as in the
PHP A8A" Su%%est chapter)
The get6ote%& -unction
Page 135 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
This function e/ecutes when 4yes4 or 4no4 is selected in the HT# form)
J) Defines the url 0filename3 to send to the ser'er
M) Adds a parameter 0'ote3 to the url with the content of the input field
3) Adds a random num!er to pre'ent the ser'er from usin% a cached file
N) Calls on the 2et"mlHttp1!-ect function to create an "#HTTP
o!-ect. and tells the o!-ect to e/ecute a function called stateChan%ed
when a chan%e is tri%%ered
9) 1pens the "#HTTP o!-ect with the %i'en url)
H) Sends an HTTP re;uest to the ser'er
The PHP Page
The ser'er pa%e called !y the 8a'aScript code is a simple PHP file called
4pollC'ote)php4)
<?php
$vote $_IP8QP2T;>vote>=;
//9et content o. te"t.ile
$.ilename "poll_res!lt)t"t";
$content .ile*$.ilename,;
//p!t content in array
$array e"plode*"SS"- $content;<=,;
$yes $array;<=;
$no $array;$=;
i. *$vote <,
1
$yes $yes F $;
4
i. *$vote $,
1
$no $no F $;
4
//insert votes to t"t .ile
$insertvote $yes)"SS")$no;
$.p .open*$.ilename-"+",;
.p!ts*$.p-$insertvote,;
.close*$.p,;
?>
<h&>Ies!lt5</h&>
<table>
<tr>
<td>Mes5</td>
<td>
<im9 src"poll)9i."
+idth><?php echo*$<<*ro!nd*$yes/*$noF$yes,-&,,; ?>>
Page 136 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
hei9ht>&<>>
<?php echo*$<<*ro!nd*$yes/*$noF$yes,-&,,; ?>Y
</td>
</tr>
<tr>
<td>6o5</td>
<td>
<im9 src"poll)9i."
+idth><?php echo*$<<*ro!nd*$no/*$noF$yes,-&,,; ?>>
hei9ht>&<>>
<?php echo*$<<*ro!nd*$no/*$noF$yes,-&,,; ?>Y
</td>
</tr>
</table>
The selected 'alue is sent from the 8a'aScript and the followin% happens:
J) 2et the content of the 4pollCresult)t/t4 file
M) Put the content of the file in 'aria!les and add one to the selected
'aria!le
3) Write the result to the 4pollCresult)t/t4 file
N) 1utput a %raphical representation of the poll result
PHP Array -unctions
PHP Array 'ntroduction
The array functions allow you to manipulate arrays)
PHP supports !oth simple and multi(dimensional arrays) There are also
specific functions for populatin% arrays from data!ase ;ueries)
'nstallation
The array functions are part of the PHP core) There is no installation needed
to use these functions)
PHP Array -unctions
PHP: indicates the earliest 'ersion of PHP that supports the function)
-unction 1escription PHP
array03 Creates an array 3
Page 137 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
arrayCchan%eC+eyCcase03 6eturns an array with all +eys in lowercase
or uppercase
N
arrayCchun+03 Splits an array into chun+s of arrays N
arrayCcom!ine03 Creates an array !y usin% one array for +eys
and another for its 'alues
9
arrayCcountC'alues03 6eturns an array with the num!er of
occurrences for each 'alue
N
arrayCdiff03 Compares array 'alues. and returns the
differences
N
arrayCdiffCassoc03 Compares array +eys and 'alues. and returns
the differences
N
arrayCdiffC+ey03 Compares array +eys. and returns the
differences
9
arrayCdiffCuassoc03 Compares array +eys and 'alues. with an
additional user(made function chec+. and
returns the differences
9
arrayCdiffCu+ey03 Compares array +eys. with an additional
user(made function chec+. and returns the
differences
9
arrayCfill03 Fills an array with 'alues N
arrayCfilter03 Filters elements of an array usin% a user(
made function
N
arrayCflip03 E/chan%es all +eys with their associated
'alues in an array
N
arrayCintersect03 Compares array 'alues. and returns the
matches
N
arrayCintersectCassoc03 Compares array +eys and 'alues. and returns
the matches
N
arrayCintersectC+ey03 Compares array +eys. and returns the
matches
9
arrayCintersectCuassoc03 Compares array +eys and 'alues. with an
additional user(made function chec+. and
returns the matches
9
arrayCintersectCu+ey03 Compares array +eys. with an additional
user(made function chec+. and returns the
matches
9
Page 138 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
arrayC+eyCe/ists03 Chec+s if the specified +ey e/ists in the array N
arrayC+eys03 6eturns all the +eys of an array N
arrayCmap03 Sends each 'alue of an array to a user(made
function. which returns new 'alues
N
arrayCmer%e03 #er%es one or more arrays into one array N
arrayCmer%eCrecursi'e03 #er%es one or more arrays into one array N
arrayCmultisort03 Sorts multiple or multi(dimensional arrays N
arrayCpad03 ,nserts a specified num!er of items. with a
specified 'alue. to an array
N
arrayCpop03 Deletes the last element of an array N
arrayCproduct03 Calculates the product of the 'alues in an
array
9
arrayCpush03 ,nserts one or more elements to the end of an
array
N
arrayCrand03 6eturns one or more random +eys from an
array
N
arrayCreduce03 6eturns an array as a strin%. usin% a user(
defined function
N
arrayCre'erse03 6eturns an array in the re'erse order N
arrayCsearch03 Searches an array for a %i'en 'alue and
returns the +ey
N
arrayCshift03 6emo'es the first element from an array. and
returns the 'alue of the remo'ed element
N
arrayCslice03 6eturns selected parts of an array N
arrayCsplice03 6emo'es and replaces specified elements of
an array
N
arrayCsum03 6eturns the sum of the 'alues in an array N
arrayCudiff03 Compares array 'alues in a user(made
function and returns an array
9
arrayCudiffCassoc03 Compares array +eys. and compares array
'alues in a user(made function. and returns
an array
9
arrayCudiffCuassoc03 Compares array +eys and array 'alues in
user(made functions. and returns an array
9
arrayCuintersect03 Compares array 'alues in a user(made 9
Page 139 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
function and returns an array
arrayCuintersectCassoc03 Compares array +eys. and compares array
'alues in a user(made function. and returns
an array
9
arrayCuintersectCuassoc03 Compares array +eys and array 'alues in
user(made functions. and returns an array
9
arrayCuni;ue03 6emo'es duplicate 'alues from an array N
arrayCunshift03 Adds one or more elements to the !e%innin%
of an array
N
arrayC'alues03 6eturns all the 'alues of an array N
arrayCwal+03 Applies a user function to e'ery mem!er of
an array
3
arrayCwal+Crecursi'e03 Applies a user function recursi'ely to e'ery
mem!er of an array
9
arsort03 Sorts an array in re'erse order and maintain
inde/ association
3
asort03 Sorts an array and maintain inde/ association 3
compact03 Create array containin% 'aria!les and their
'alues
N
count03 Counts elements in an array. or properties in
an o!-ect
3
current03 6eturns the current element in an array 3
each03 6eturns the current +ey and 'alue pair from
an array
3
end03 Sets the internal pointer of an array to its last
element
3
e/tract03 ,mports 'aria!les into the current sym!ol
ta!le from an array
3
inCarray03 Chec+s if a specified 'alue e/ists in an array N
+ey03 Fetches a +ey from an array 3
+rsort03 Sorts an array !y +ey in re'erse order 3
+sort03 Sorts an array !y +ey 3
list03 Assi%ns 'aria!les as if they were an array 3
natcasesort03 Sorts an array usin% a case insensiti'e
4natural order4 al%orithm
N
Page 140 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
natsort03 Sorts an array usin% a 4natural order4
al%orithm
N
ne/t03 Ad'ance the internal array pointer of an
array
3
pos03 Alias of current03 3
pre'03 6ewinds the internal array pointer 3
ran%e03 Creates an array containin% a ran%e of
elements
3
reset03 Sets the internal pointer of an array to its first
element
3
rsort03 Sorts an array in re'erse order 3
shuffle03 Shuffles an array 3
siDeof03 Alias of count03 3
sort03 Sorts an array 3
uasort03 Sorts an array with a user(defined function
and maintain inde/ association
3
u+sort03 Sorts an array !y +eys usin% a user(defined
function
3
usort03 Sorts an array !y 'alues usin% a user(defined
function
3
PHP Array $onstants
PHP: indicates the earliest 'ersion of PHP that supports the constant)
$onstant 1escription PHP
CASEC1WE6 5sed with arrayCchan%eC+eyCcase03 to
con'ert array +eys to lower case

CASEC5PPE6 5sed with arrayCchan%eC+eyCcase03 to
con'ert array +eys to upper case

S16TCASC 5sed with arrayCmultisort03 to sort in
ascendin% order

S16TCDESC 5sed with arrayCmultisort03 to sort in
descendin% order

S16TC6E25A6 5sed to compare items normally
S16TCB5#E6,C 5sed to compare items numerically
Page 141 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
S16TCST6,B2 5sed to compare items as strin%s
S16TC1CAECST6,B2 5sed to compare items as strin%s. !ased
on the current locale
N
C15BTCB16#A
C15BTC6EC56S,@E
E"T6C1@E6W6,TE
E"T6CSU,P
E"T6CP6EF,"CSA#E
E"T6CP6EF,"CA
E"T6CP6EF,"C,B@A,D
E"T6CP6EF,"C,FCE",STS
E"T6C,FCE",STS
E"T6C6EFS
PHP $alendar -unctions
PHP $alendar 'ntroduction
The calendar functions are useful when wor+in% with different calendar
formats) The standard it is !ased on is the 8ulian day count 08ulian day count
is a count of days startin% from 8anuary J. NIJ3 *)C)3) Bote that the 8ulian
day count is not the same as the 8ulian calendarG
0ote5 To con'ert !etween calendar formats. you must first con'ert to 8ulian
day count. then to the calendar format)
'nstallation
The windows 'ersion of PHP has !uilt(in support for the calendar e/tension)
So. the calendar functions will wor+ automatically)
Howe'er. if you are runnin% the inu/ 'ersion of PHP. you will ha'e to
compile PHP with --enable-calendar to %et the calendar functions to wor+)
PHP $alendar -unctions
Page 142 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
PHP: indicates the earliest 'ersion of PHP that supports the function)
-unction 1escription PHP
calCdaysCinCmonth03 6eturns the num!er of days in a month for a
specified year and calendar
N
calCfromC-d03 Con'erts a 8ulian day count into a date of a
specified calendar
N
calCinfo03 6eturns information a!out a %i'en calendar N
calCtoC-d03 Con'erts a date to 8ulian day count N
easterCdate03 6eturns the 5ni/ timestamp for midni%ht on
Easter of a specified year
3
easterCdays03 6eturns the num!er of days after #arch MJ. on
which Easter falls for a specified year
3
FrenchTo8D03 Con'erts a French 6epu!lican date to a 8ulian
day count
3
2re%orianTo8D03 Con'erts a 2re%orian date to a 8ulian day count 3
8DDay1fWee+03 6eturns the day of a wee+ 3
8D#onthBame03 6eturns a month name 3
8DToFrench03 Con'erts a 8ulian day count to a French
6epu!lican date
3
8DTo2re%orian03 Con'erts a 8ulian day count to a 2re%orian date 3
-dto-ewish03 Con'erts a 8ulian day count to a 8ewish date 3
8DTo8ulian03 Con'erts a 8ulian day count to a 8ulian date 3
-dtouni/03 Con'erts a 8ulian day count to a 5ni/ timestamp N
8ewishTo8D03 Con'erts a 8ewish date to a 8ulian day count 3
8ulianTo8D03 Con'erts a 8ulian date to a 8ulian day count 3
uni/to-d03 Con'erts a 5ni/ timestamp to a 8ulian day count N
PHP $alendar $onstants
PHP: indicates the earliest 'ersion of PHP that supports the constant)
$onstant 1escription PHP
CAC26E216,AB 2re%orian calendar 3
CAC85,AB 8ulian calendar 3
Page 143 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
CAC8EW,SH 8ewish calendar 3
CACF6EBCH French 6epu!lican
calendar
3
CACB5#CCAS 3
CACD1WCDATB1 3
CACD1WCSH16T 3
CACD1WC1B2 3
CAC#1BTHC26E216,ABCSH16T 3
CAC#1BTHC26E216,ABC1B2 3
CAC#1BTHC85,ABCSH16T 3
CAC#1BTHC85,ABC1B2 3
CAC#1BTHC8EW,SH 3
CAC#1BTHCF6EBCH 3
CACEASTE6CDEFA5T N
CACEASTE6CDEFA5T N
CACEASTE6C61#AB N
CACEASTE6CAWATSC26E216,AB N
CACEASTE6CAWATSC85,AB N
CAC8EW,SHCADDCAAF,#C2E6ESH 9
CAC8EW,SHCADDCAAF,# 9
CAC8EW,SHCADDC2E6ESHAT,# 9
PHP 1ate G Time -unctions
PHP 1ate G Time 'ntroduction
The date:time functions allow you to e/tract and format the date and time on
the ser'er)
0ote5 These functions depend on the locale settin%s of the ser'erG
'nstallation
Page 144 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
The date:time functions are part of the PHP core) There is no installation
needed to use these functions)
)untime $onfiguration
The !eha'ior of the date:time functions is affected !y settin%s in php)ini)
Date:Time confi%uration options:
0ame 1efault 1escription $hangeable
date)defaultClatitude 43J)IHHI4 Specifies the default
latitude 0a'aila!le since
PHP 93) This option is
used !y dateCsunrise03 and
dateCsunset03
PHPC,B,CA
date)defaultClon%itude 439)M3334 Specifies the default
lon%itude 0a'aila!le since
PHP 93) This option is
used !y dateCsunrise03 and
dateCsunset03
PHPC,B,CA
date)sunriseCDenith 4FE)P34 Specifies the default
sunrise Denith 0a'aila!le
since PHP 93) This option
is used !y dateCsunrise03
and dateCsunset03
PHPC,B,CA
date)sunsetCDenith 4FE)P34 Specifies the default sunset
Denith 0a'aila!le since
PHP 93) This option is
used !y dateCsunrise03 and
dateCsunset03
PHPC,B,CA
date)timeDone 44 Specifies the default
timeDone 0a'aila!le since
PHP 9)J3
PHPC,B,CA
PHP 1ate G Time -unctions
PHP: indicates the earliest 'ersion of PHP that supports the function)
-unction 1escription PHP
chec+date03 @alidates a 2re%orian date 3
dateCdefaultCtimeDoneC%et03 6eturns the default time Done 9
Page 145 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
dateCdefaultCtimeDoneCset03 Sets the default time Done 9
dateCsunrise03 6eturns the time of sunrise for a %i'en day
: location
9
dateCsunset03 6eturns the time of sunset for a %i'en day
: location
9
date03 Formats a local time:date 3
%etdate03 6eturns an array that contains date and
time information for a 5ni/ timestamp
3
%ettimeofday03 6eturns an array that contains current time
information
3
%mdate03 Formats a 2#T:5TC date:time 3
%mm+time03 6eturns the 5ni/ timestamp for a 2#T
date
3
%mstrftime03 Formats a 2#T:5TC time:date accordin%
to locale settin%s
3
idate03 Formats a local time:date as inte%er 9
localtime03 6eturns an array that contains the time
components of a 5ni/ timestamp
N
microtime03 6eturns the microseconds for the current
time
3
m+time03 6eturns the 5ni/ timestamp for a date 3
strftime03 Formats a local time:date accordin% to
locale settin%s
3
strptime03 Parses a time:date %enerated with
strftime03
9
strtotime03 Parses an En%lish te/tual date or time into
a 5ni/ timestamp
3
time03 6eturns the current time as a 5ni/
timestamp
3
PHP 1ate G Time $onstants
PHP: indicates the earliest 'ersion of PHP that supports the constant)
$onstant 1escription PHP
DATECAT1# Atom 0e/ample: MEE9(EP(
J9TJH:J3:E3KEEEE3

Page 146 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
DATECC11U,E HTTP Coo+ies 0e/ample: Sun. JN Au%
MEE9 JH:J3:E3 5TC3

DATEC,S1PHEJ ,S1(PHEJ 0e/ample: MEE9(EP(
JNTJH:J3:E3KEEEE3

DATEC6FCPMM 6FC PMM 0e/ample: Sun. JN Au% MEE9
JH:J3:E3 5TC3

DATEC6FCP9E 6FC P9E 0e/ample: Sunday. JN(Au%(E9
JH:J3:E3 5TC3

DATEC6FCJE3H 6FC JE3H 0e/ample: Sunday. JN(Au%(E9
JH:J3:E3 5TC3

DATEC6FCJJM3 6FC JJM3 0e/ample: Sun. JN Au% MEE9
JH:J3:E3 5TC3

DATEC6FCMPMM 6FC MPMM 0Sun. JN Au% MEE9 JH:J3:E3
KEEEE3

DATEC6SS 6SS 0Sun. JN Au% MEE9 JH:J3:E3 5TC3
DATECW3C World Wide We! Consortium 0e/ample:
MEE9(EP(JNTJH:J3:E3KEEEE3

PHP 1irectory -unctions
PHP 1irectory 'ntroduction
The directory functions allow you to retrie'e information a!out directories
and their contents)
'nstallation
The directory functions are part of the PHP core) There is no installation
needed to use these functions)
PHP 1irectory -unctions
PHP: indicates the earliest 'ersion of PHP that supports the function)
-unction 1escription PHP
chdir03 Chan%es the current directory 3
Page 147 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
chroot03 Chan%es the root directory of the current
process
N
dir03 1pens a directory handle and returns an
o!-ect
3
closedir03 Closes a directory handle 3
%etcwd03 6eturns the current directory N
opendir03 1pens a directory handle 3
readdir03 6eturns an entry from a directory handle 3
rewinddir03 6esets a directory handle 3
scandir03 ists files and directories inside a specified
path
9
PHP 1irectory $onstants
PHP: indicates the earliest 'ersion of PHP that supports the constant)
$onstant 1escription PHP
D,6ECT16TCSEPA6AT16 3
PATHCSEPA6AT16 N
PHP 9rror and "ogging -unctions
PHP 9rror and "ogging 'ntroduction
The error and lo%%in% functions allows error handlin% and lo%%in%)
The error functions allow users to define error handlin% rules. and modify the
way the errors can !e lo%%ed)
The lo%%in% functions allow users to lo% applications and send lo% messa%es
to email. system lo%s or other machines)
'nstallation
Page 148 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
The error and lo%%in% functions are part of the PHP core) There is no
installation needed to use these functions)
PHP 9rror and "ogging -unctions
PHP: indicates the earliest 'ersion of PHP that supports the function)
-unction 1escription PHP
de!u%C!ac+trace03 2enerates a !ac+trace N
de!u%CprintC!ac+trace03 Prints a !ac+trace 9
errorC%etClast03 2ets the last error occurred 9
errorClo%03 Sends an error to the ser'er error(lo%. to
a file or to a remote destination
N
errorCreportin%03 Specifies which errors are reported N
restoreCerrorChandler03 6estores the pre'ious error handler N
restoreCe/ceptionChandler03 6estores the pre'ious e/ception handler 9
setCerrorChandler03 Sets a user(defined function to handle
errors
N
setCe/ceptionChandler03 Sets a user(defined function to handle
e/ceptions
9
tri%%erCerror03 Creates a user(defined error messa%e N
userCerror03 Alias of tri%%erCerror03 N
PHP 9rror and "ogging $onstants
PHP: indicates the earliest 'ersion of PHP that supports the constant)
6alue $onstant 1escription PHP
J ECE6616 Fatal run(time errors) Errors that
cannot !e reco'ered from)
E/ecution of the script is halted

M ECWA6B,B2 Bon(fatal run(time errors)
E/ecution of the script is not
halted

N ECPA6SE Compile(time parse errors) Parse
errors should only !e %enerated
!y the parser

P ECB1T,CE 6un(time notices) The script
Page 149 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
found somethin% that mi%ht !e an
error. !ut could also happen when
runnin% a script normally
JH ECC16ECE6616 Fatal errors at PHP startup) This
is li+e an ECE6616 in the PHP
core
N
3M ECC16ECWA6B,B2 Bon(fatal errors at PHP startup)
This is li+e an ECWA6B,B2 in
the PHP core
N
HN ECC1#P,ECE6616 Fatal compile(time errors) This is
li+e an ECE6616 %enerated !y
the &end Scriptin% En%ine
N
JMP ECC1#P,ECWA6B,B2 Bon(fatal compile(time errors)
This is li+e an ECWA6B,B2
%enerated !y the &end Scriptin%
En%ine
N
M9H EC5SE6CE6616 Fatal user(%enerated error) This is
li+e an ECE6616 set !y the
pro%rammer usin% the PHP
function tri%%erCerror03
N
9JM EC5SE6CWA6B,B2 Bon(fatal user(%enerated
warnin%) This is li+e an
ECWA6B,B2 set !y the
pro%rammer usin% the PHP
function tri%%erCerror03
N
JEMN EC5SE6CB1T,CE 5ser(%enerated notice) This is
li+e an ECB1T,CE set !y the
pro%rammer usin% the PHP
function tri%%erCerror03
N
MENP ECST6,CT 6un(time notices) PHP su%%est
chan%es to your code to help
interopera!ility and compati!ility
of the code
9
NEFH EC6EC1@E6A*ECE6616 Catcha!le fatal error) This is li+e
an ECE6616 !ut can !e cau%ht
!y a user defined handle 0see also
setCerrorChandler033
9
PJFJ ECA All errors and warnin%s. e/cept 9
Page 150 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
of le'el ECST6,CT
PHP -ilesystem -unctions
PHP -ilesystem 'ntroduction
The filesystem functions allow you to access and manipulate the filesystem)
'nstallation
The filesystem functions are part of the PHP core) There is no installation
needed to use these functions)
)untime $onfiguration
The !eha'ior of the filesystem functions is affected !y settin%s in php)ini)
Filesystem confi%uration options:
0ame 1efault 1escription $hangeable
allowCurlCfopen 4J4 Allows fopen03(type
functions to wor+
with 56s 0a'aila!le
since PHP N)E)N3
PHPC,B,CSTSTE#
userCa%ent B5 Defines the user
a%ent for PHP to send
0a'aila!le since PHP
N)33
PHPC,B,CA
defaultCsoc+etCtimeout 4HE4 Sets the default
timeout. in seconds.
for soc+et !ased
streams 0a'aila!le
since PHP N)33
PHPC,B,CA
from 44 Defines the
anonymous FTP
password 0your email
address3
PHPC,B,CA
autoCdetectClineCendin%s 4E4 When set to 4J4. PHP
will e/amine the data
read !y f%ets03 and
PHPC,B,CA
Page 151 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
file03 to see if it is
usin% 5ni/. #S(Dos
or #ac line(endin%
characters 0a'aila!le
since PHP N)33
8ni# G !indows $ompatibility
When specifyin% a path on 5ni/ platforms. the forward slash 0:3 is used as
directory separator) Howe'er. on Windows platforms. !oth forward slash 0:3
and !ac+slash 0X3 can !e used)
PHP -ilesystem -unctions
PHP: indicates the earliest 'ersion of PHP that supports the function)
-unction 1escription PHP
!asename03 6eturns the filename component of a path 3
ch%rp03 Chan%es the file %roup 3
chmod03 Chan%es the file mode 3
chown03 Chan%es the file owner 3
clearstatcache03 Clears the file status cache 3
copy03 Copies a file 3
delete03 See unlin+03 or unset03
dirname03 6eturns the directory name component of a path 3
dis+CfreeCspace03 6eturns the free space of a directory N
dis+CtotalCspace03 6eturns the total siDe of a directory N
dis+freespace03 Alias of dis+CfreeCspace03 3
fclose03 Closes an open file 3
feof03 Tests for end(of(file on an open file 3
fflush03 Flushes !uffered output to an open file N
f%etc03 6eturns a character from an open file 3
f%etcs'03 Parses a line from an open file. chec+in% for 3
Page 152 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
CS@ fields
f%ets03 6eturns a line from an open file 3
f%etss03 6eturns a line. with HT# and PHP ta%s
remo'ed. from an open file
3
file03 6eads a file into an array 3
fileCe/ists03 Chec+s whether or not a file or directory e/ists 3
fileC%etCcontents03 6eads a file into a strin% N
fileCputCcontents Writes a strin% to a file 9
fileatime03 6eturns the last access time of a file 3
filectime03 6eturns the last chan%e time of a file 3
file%roup03 6eturns the %roup ,D of a file 3
fileinode03 6eturns the inode num!er of a file 3
filemtime03 6eturns the last modification time of a file 3
fileowner03 6eturns the user ,D 0owner3 of a file 3
fileperms03 6eturns the permissions of a file 3
filesiDe03 6eturns the file siDe 3
filetype03 6eturns the file type 3
floc+03 oc+s or releases a file 3
fnmatch03 #atches a filename or strin% a%ainst a specified
pattern
N
fopen03 1pens a file or 56 3
fpassthru03 6eads from an open file. until E1F. and writes
the result to the output !uffer
3
fputcs'03 Formats a line as CS@ and writes it to an open
file
9
fputs03 Alias of fwrite03 3
fread03 6eads from an open file 3
fscanf03 Parses input from an open file accordin% to a
specified format
N
fsee+03 See+s in an open file 3
fstat03 6eturns information a!out an open file N
ftell03 6eturns the current position in an open file 3
ftruncate03 Truncates an open file to a specified len%th N
Page 153 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
fwrite03 Writes to an open file 3
%lo!03 6eturns an array of filenames : directories
matchin% a specified pattern
N
isCdir03 Chec+s whether a file is a directory 3
isCe/ecuta!le03 Chec+s whether a file is e/ecuta!le 3
isCfile03 Chec+s whether a file is a re%ular file 3
isClin+03 Chec+s whether a file is a lin+ 3
isCreada!le03 Chec+s whether a file is reada!le 3
isCuploadedCfile03 Chec+s whether a file was uploaded 'ia HTTP
P1ST
3
isCwrita!le03 Chec+s whether a file is writea!le N
isCwritea!le03 Alias of isCwrita!le03 3
lin+03 Creates a hard lin+ 3
lin+info03 6eturns information a!out a hard lin+ 3
lstat03 6eturns information a!out a file or sym!olic lin+ 3
m+dir03 Creates a directory 3
mo'eCuploadedCfile03 #o'es an uploaded file to a new location N
parseCiniCfile03 Parses a confi%uration file N
pathinfo03 6eturns information a!out a file path N
pclose03 Closes a pipe opened !y popen03 3
popen03 1pens a pipe 3
readfile03 6eads a file and writes it to the output !uffer 3
readlin+03 6eturns the tar%et of a sym!olic lin+ 3
realpath03 6eturns the a!solute pathname N
rename03 6enames a file or directory 3
rewind03 6ewinds a file pointer 3
rmdir03 6emo'es an empty directory 3
setCfileC!uffer03 Sets the !uffer siDe of an open file 3
stat03 6eturns information a!out a file 3
symlin+03 Creates a sym!olic lin+ 3
tempnam03 Creates a uni;ue temporary file 3
tmpfile03 Creates a uni;ue temporary file 3
Page 154 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
touch03 Sets access and modification time of a file 3
umas+03 Chan%es file permissions for files 3
unlin+03 Deletes a file 3
PHP -ilesystem $onstants
PHP: indicates the earliest 'ersion of PHP that supports the constant)
$onstant 1escription PHP
21*C*6ACE
21*C1BTD,6
21*C#A6U
21*CB1S16T
21*CB1CHECU
21*CB1ESCAPE
PATH,BF1CD,6BA#E
PATH,BF1C*ASEBA#E
PATH,BF1CE"TEBS,1B
F,EC5SEC,BC5DECPATH
F,ECAPPEBD
F,EC,2B16ECBEWC,BES
F,ECSU,PCE#PTTC,BES
PHP -ilter -unctions
PHP -ilter 'ntroduction
This PHP filters is used to 'alidate and filter data comin% from insecure
sources. li+e user input)
'nstallation
Page 155 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
The filter functions are part of the PHP core) There is no installation needed
to use these functions)
PHP -ilter -unctions
PHP: indicates the earliest 'ersion of PHP that supports the function)
-unction 1escription PHP
filterChasC'ar03 Chec+s if a 'aria!le of a specified input type
e/ist
9
filterCid03 6eturns the ,D num!er of a specified filter 9
filterCinput03 2et input from outside the script and filter it 9
filterCinputCarray03 2et multiple inputs from outside the script and
filters them
9
filterClist03 6eturns an array of all supported filters 9
filterC'arCarray03 2et multiple 'aria!les and filter them 9
filterC'ar03 2et a 'aria!le and filter it 9
PHP -ilters
'1 0ame 1escription
F,TE6CCA*ACU Call a user(defined function to
filter data
F,TE6CSAB,T,&ECST6,B2 Strip ta%s. optionally strip or
encode special characters
F,TE6CSAB,T,&ECST6,PPED Alias of 4strin%4 filter
F,TE6CSAB,T,&ECEBC1DED 56(encode strin%. optionally
strip or encode special characters
F,TE6CSAB,T,&ECSPEC,ACCHA6S HT#(escape 74<>R and
characters with ASC,, 'alue less
than 3M
F,TE6CSAB,T,&ECE#A, 6emo'e all characters. e/cept
letters. di%its and G[AOR7?K(
:L=\C]^S_`a)VW
F,TE6CSAB,T,&EC56 6emo'e all characters. e/cept
letters. di%its and A(C)KG?703.^_S
Page 156 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
XX\`VW]<>[O4Q:=:aRL
F,TE6CSAB,T,&ECB5#*E6C,BT 6emo'e all characters. e/cept
di%its and K(
F,TE6CSAB,T,&ECB5#*E6CF1AT 6emo'e all characters. e/cept
di%its. K( and optionally ).eE
F,TE6CSAB,T,&EC#A2,CC$51TES Apply addslashes03
F,TE6C5BSAFEC6AW Do nothin%. optionally strip or
encode special characters
F,TE6C@A,DATEC,BT @alidate 'alue as inte%er.
optionally from the specified ran%e
F,TE6C@A,DATEC*11EAB 6eturn T65E for 4J4. 4true4. 4on4
and 4yes4. FASE for 4E4. 4false4.
4off4. 4no4. and 44. B5
otherwise
F,TE6C@A,DATECF1AT @alidate 'alue as float
F,TE6C@A,DATEC6E2E"P @alidate 'alue a%ainst re%e/p. a
Perl(compati!le re%ular e/pression
F,TE6C@A,DATEC56 @alidate 'alue as 56. optionally
with re;uired components
F,TE6C@A,DATECE#A, @alidate 'alue as e(mail
F,TE6C@A,DATEC,P @alidate 'alue as ,P address.
optionally only ,P'N or ,P'H or not
from pri'ate or reser'ed ran%es
PHP -TP -unctions
PHP -TP 'ntroduction
The FTP functions %i'e client access to file ser'ers throu%h the File Transfer
Protocol 0FTP3)
The FTP functions are used to open. lo%in and close connections. as well as
upload. download. rename. delete. and %et information on files from file
Page 157 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
ser'ers) Bot all of the FTP functions will wor+ with e'ery ser'er or return
the same results) The FTP functions !ecame a'aila!le with PHP 3)
These functions are meant for detailed access to an FTP ser'er) ,f you only
wish to read from or write to a file on an FTP ser'er. consider usin% the ftp:::
wrapper with the Filesystem functions)
'nstallation
The windows 'ersion of PHP has !uilt(in support for the FTP e/tension) So.
the FTP functions will wor+ automatically)
Howe'er. if you are runnin% the inu/ 'ersion of PHP. you will ha'e to
compile PHP with --enable-ftp 0PHP NK3 or --with-ftp 0PHP 33 to %et the FTP
functions to wor+)
PHP -TP -unctions
PHP: indicates the earliest 'ersion of PHP that supports the function)
-unction 1escription PHP
ftpCalloc03 Allocates space for a file to !e uploaded to the
FTP ser'er
9
ftpCcdup03 Chan%es the current directory to the parent
directory on the FTP ser'er
3
ftpCchdir03 Chan%es the current directory on the FTP ser'er 3
ftpCchmod03 Sets permissions on a file 'ia FTP 9
ftpCclose03 Closes an FTP connection N
ftpCconnect03 1pens an FTP connection 3
ftpCdelete03 Deletes a file on the FTP ser'er 3
ftpCe/ec03 E/ecutes a pro%ram:command on the FTP ser'er N
ftpCf%et03 Downloads a file from the FTP ser'er and sa'es
it to an open file
3
ftpCfput03 5ploads from an open file and sa'es it to a file
on the FTP ser'er
3
ftpC%etCoption03 6eturns runtime !eha'iors of the FTP connection N
ftpC%et03 Downloads a file from the FTP ser'er 3
ftpClo%in03 o%s on to an FTP connection 3
Page 158 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
ftpCmdtm03 6eturns the last modified time of a specified file 3
ftpCm+dir03 Creates a new directory on the FTP ser'er 3
ftpCn!Ccontinue03 Continues retrie'in%:sendin% a file 0non(
!loc+in%3
N
ftpCn!Cf%et03 Downloads a file from the FTP ser'er and sa'es
it to an open file 0non(!loc+in%3
N
ftpCn!Cfput03 5ploads from an open file and sa'es it to a file
on the FTP ser'er 0non(!loc+in%3
N
ftpCn!C%et03 Downloads a file from the FTP ser'er 0non(
!loc+in%3
N
ftpCn!Cput03 5ploads a file to the FTP ser'er 0non(!loc+in%3 N
ftpCnlist03 ists the files in a specified directory on the FTP
ser'er
3
ftpCpas'03 Turns passi'e mode on or off 3
ftpCput03 5ploads a file to the FTP ser'er 3
ftpCpwd03 6eturns the current directory name 3
ftpC;uit03 Alias of ftpCclose03 3
ftpCraw03 Sends a raw command to the FTP ser'er 9
ftpCrawlist03 6eturns a detailed list of files in the specified
directory
3
ftpCrename03 6enames a file or directory on the FTP ser'er 3
ftpCrmdir03 6emo'es a directory on the FTP ser'er 3
ftpCsetCoption03 Sets runtime options for the FTP connection N
ftpCsite03 Sends a S,TE command to the ser'er 3
ftpCsiDe03 6eturns the siDe of the specified file 3
ftpCsslCconnect03 1pens a secure SS(FTP connection N
ftpCsystype03 6eturns the system type identifier of the FTP
ser'er
3
PHP -TP $onstants
PHP: indicates the earliest 'ersion of PHP that supports the constant)
$onstant 1escription PHP
FTPCASC,, 3
Page 159 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
FTPCTE"T 3
FTPC*,BA6T 3
FTPC,#A2E 3
FTPCT,#E15TCSEC 3
FTPCA5T1SEEU N
FTPCA5T16ES5#E Determine resume position and start position for
%et and put re;uests automatically
N
FTPCFA,ED Asynchronous transfer has failed N
FTPCF,B,SHED Asynchronous transfer has finished N
FTPC#16EDATA Asynchronous transfer is still acti'e N
PHP HTTP -unctions
PHP HTTP 'ntroduction
The HTTP functions let you manipulate information sent to the !rowser !y
the We! ser'er. !efore any other output has !een sent)
'nstallation
The directory functions are part of the PHP core) There is no installation
needed to use these functions)
PHP HTTP -unctions
PHP: indicates the earliest 'ersion of PHP that supports the function)
-unction 1escription PHP
header03 Sends a raw HTTP header to a client 3
headersClist03 6eturns a list of response headers sent 0or
ready to send3
9
headersCsent03 Chec+s if : where the HTTP headers ha'e
!een sent
3
setcoo+ie03 Sends an HTTP coo+ie to a client 3
setrawcoo+ie03 Sends an HTTP coo+ie without 56 9
Page 160 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
encodin% the coo+ie 'alue
PHP HTTP $onstants
0one.
PHP lib#ml -unctions
PHP lib#ml 'ntroduction
The li!/ml functions and constants are used to%ether with Simple"#.
"ST and D1# functions)
'nstallation
These functions re;uire the li!/ml pac+a%e) Download at /mlsoft)or%
PHP lib#ml -unctions
PHP: indicates the earliest 'ersion of PHP that supports the function)
-unction 1escription PHP
li!/mlCclearCerrors03 Clear li!/ml error !uffer 9
li!/mlC%etCerrors03 6etrie'e array of errors 9
li!/mlC%etClastCerror03 6etrie'e last error from li!/ml 9
li!/mlCsetCstreamsCconte/t03 Set the streams conte/t for the ne/t
li!/ml document load or write
9
li!/mlCuseCinternalCerrors03 Disa!le li!/ml errors and allow user to
fetch error information as needed
9
PHP lib#ml $onstants
-unction 1escription PHP
,*"#CC1#PACT Set small nodes allocation
optimiDation) This may impro'e the
application performance
9
,*"#CDTDATT6 Set default DTD attri!utes 9
Page 161 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
,*"#CDTD1AD oad e/ternal su!set 9
,*"#CDTD@A,D @alidate with the DTD 9
,*"#CB1*ABUS 6emo'e !lan+ nodes 9
,*"#CB1CDATA Set CDATA as te/t nodes 9
,*"#CB1E#PTTTA2 Chan%e empty ta%s 0e)%) <!r:> to
<!r><:!r>3. only a'aila!le in the
D1#Document(>sa'e03 and
D1#Document(>sa'e"#03
functions
9
,*"#CB1EBT Su!stitute entities 9
,*"#CB1E6616 Do not show error reports 9
,*"#CB1BET Stop networ+ access while loadin%
documents
9
,*"#CB1WA6B,B2 Do not show warnin% reports 9
,*"#CB1"#DEC Drop the "# declaration when
sa'in% a document
9
,*"#CBSCEAB 6emo'e e/cess namespace
declarations
9
,*"#C",BC5DE 5se ",nclude su!stitution 9
,*"#CE66CE6616 2et reco'era!le errors 9
,*"#CE66CFATA 2et fatal errors 9
,*"#CE66CB1BE 2et no errors 9
,*"#CE66CWA6B,B2 2et simple warnin%s 9
,*"#C@E6S,1B 2et li!/ml 'ersion 0e)%) MEHE9 or
MEHJI3
9
,*"#CD1TTEDC@E6S,1B 2et dotted li!/ml 'ersion 0e)%) M)H)9
or M)H)JI3
9
PHP Mail -unctions
PHP Mail 'ntroduction
The mail03 function allows you to send emails directly from a script)
Page 162 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
)e=uirements
For the mail functions to !e a'aila!le. PHP re;uires an installed and wor+in%
email system) The pro%ram to !e used is defined !y the confi%uration
settin%s in the php)ini file)
'nstallation
The mail functions are part of the PHP core) There is no installation needed
to use these functions)
)untime $onfiguration
The !eha'ior of the mail functions is affected !y settin%s in the php)ini file)
#ail confi%uration options:
0ame 1efault 1escription $hangeable
S#TP 4localhost4 Windows only: The DBS
name or ,P address of the
S#TP ser'er
PHPC,B,CA
smtpCport 4M94 Windows only: The S#TP
port num!er) A'aila!le since
PHP N)3
PHPC,B,CA
sendmailCfrom B5 Windows only: Specifies the
4from4 address to !e used in
email sent from PHP
PHPC,B,CA
sendmailCpath B5 5ni/ systems only: Specifies
where the sendmail pro%ram
can !e found 0usually
:usr:s!in:sendmail or
:usr:li!:sendmail3
PHPC,B,CSTSTE#
PHP Mail -unctions
PHP: indicates the earliest 'ersion of PHP that supports the function)
-unction 1escription PHP
eDmlmChash03 Calculates the hash 'alue needed !y the E&##
mailin% list system
3
mail03 Allows you to send emails directly from a script 3
Page 163 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
PHP Mail $onstants
0one.
PHP Math -unctions
PHP Math 'ntroduction
The math functions can handle 'alues within the ran%e of inte%er and float
types)
'nstallation
The math functions are part of the PHP core) There is no installation needed
to use these functions)
PHP Math -unctions
PHP: indicates the earliest 'ersion of PHP that supports the function)
-unction 1escription PHP
a!s03 6eturns the a!solute 'alue of a num!er 3
acos03 6eturns the arccosine of a num!er 3
acosh03 6eturns the in'erse hyper!olic cosine of a
num!er
N
asin03 6eturns the arcsine of a num!er 3
asinh03 6eturns the in'erse hyper!olic sine of a num!er N
atan03 6eturns the arctan%ent of a num!er as a numeric
'alue !etween (P,:M and P,:M radians
3
atanM03 6eturns the an%le theta of an 0/.y3 point as a
numeric 'alue !etween (P, and P, radians
3
atanh03 6eturns the in'erse hyper!olic tan%ent of a
num!er
N
!aseCcon'ert03 Con'erts a num!er from one !ase to another 3
!indec03 Con'erts a !inary num!er to a decimal num!er 3
ceil03 6eturns the 'alue of a num!er rounded upwards
to the nearest inte%er
3
Page 164 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
cos03 6eturns the cosine of a num!er 3
cosh03 6eturns the hyper!olic cosine of a num!er N
dec!in03 Con'erts a decimal num!er to a !inary num!er 3
deche/03 Con'erts a decimal num!er to a he/adecimal
num!er
3
decoct03 Con'erts a decimal num!er to an octal num!er 3
de%Mrad03 Con'erts a de%ree to a radian num!er 3
e/p03 6eturns the 'alue of E
/
3
e/pmJ03 6eturns the 'alue of E
/
( J N
floor03 6eturns the 'alue of a num!er rounded
downwards to the nearest inte%er
3
fmod03 6eturns the remainder 0modulo3 of the di'ision
of the ar%uments
N
%etrandma/03 6eturns the ma/imum random num!er that can
!e returned !y a call to the rand03 function
3
he/dec03 Con'erts a he/adecimal num!er to a decimal
num!er
3
hypot03 6eturns the len%th of the hypotenuse of a ri%ht(
an%le trian%le
N
isCfinite03 6eturns true if a 'alue is a finite num!er N
isCinfinite03 6eturns true if a 'alue is an infinite num!er N
isCnan03 6eturns true if a 'alue is not a num!er N
lc%C'alue03 6eturns a pseudo random num!er in the ran%e of
0E.J3
N
lo%03 6eturns the natural lo%arithm 0!ase E3 of a
num!er
3
lo%JE03 6eturns the !ase(JE lo%arithm of a num!er 3
lo%Jp03 6eturns lo%0JKnum!er3 N
ma/03 6eturns the num!er with the hi%hest 'alue of two
specified num!ers
3
min03 6eturns the num!er with the lowest 'alue of two
specified num!ers
3
mtC%etrandma/03 6eturns the lar%est possi!le 'alue that can !e
returned !y mtCrand03
3
Page 165 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
mtCrand03 6eturns a random inte%er usin% #ersenne
Twister al%orithm
3
mtCsrand03 Seeds the #ersenne Twister random num!er
%enerator
3
octdec03 Con'erts an octal num!er to a decimal num!er 3
pi03 6eturns the 'alue of P, 3
pow03 6eturns the 'alue of / to the power of y 3
radMde%03 Con'erts a radian num!er to a de%ree 3
rand03 6eturns a random inte%er 3
round03 6ounds a num!er to the nearest inte%er 3
sin03 6eturns the sine of a num!er 3
sinh03 6eturns the hyper!olic sine of a num!er N
s;rt03 6eturns the s;uare root of a num!er 3
srand03 Seeds the random num!er %enerator 3
tan03 6eturns the tan%ent of an an%le 3
tanh03 6eturns the hyper!olic tan%ent of an an%le N
PHP Math $onstants
PHP: indicates the earliest 'ersion of PHP that supports the constant)
$onstant 1escription PHP
#CE 6eturns e 0appro/) M)IJP3 N
#CE5E6 6eturns Euler7s constant 0appro/) E)9II3 N
#CBP, 6eturns the natural lo%arithm of P, 0appro/)
J)JNN3
N
#CBM 6eturns the natural lo%arithm of M 0appro/)
E)HF33
N
#CBJE 6eturns the natural lo%arithm of JE 0appro/)
M)3EM3
N
#C12ME 6eturns the !ase(M lo%arithm of E 0appro/)
J)NNM3
N
#C12JEE 6eturns the !ase(JE lo%arithm of E 0appro/)
E)N3N3
N
#CP, 6eturns P, 0appro/) 3)JNJ9F3 3
Page 166 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
#CP,CM 6eturns P,:M 0appro/) J)9IE3 N
#CP,CN 6eturns P,:N 0appro/) E)IP93 N
#CJCP, 6eturns J:P, 0appro/) E)3JP3 N
#CMCP, 6eturns M:P, 0appro/) E)H3H3 N
#CS$6TP, 6eturns the s;uare root of P, 0appro/) J)IIM3 N
#CMCS$6TP, 6eturns M:s;uare root of P, 0appro/) J)JMP3 N
#CS$6TJCM 6eturns the s;uare root of J:M 0appro/) E)IEI3 N
#CS$6TM 6eturns the s;uare root of M 0appro/) J)NJN3 N
#CS$6T3 6eturns the s;uare root of 3 0appro/) J)I3M3 N
PHP Misc. -unctions
PHP Miscellaneous 'ntroduction
The misc) functions were only placed here !ecause none of the other
cate%ories seemed to fit)
'nstallation
The misc functions are part of the PHP core) There is no installation needed
to use these functions)
)untime $onfiguration
The !eha'ior of the misc functions is affected !y settin%s in the php)ini file)
#isc) confi%uration options:
0ame 1efault 1escription $hangeable
i%noreCuserCa!ort 4E4 FASE indicates that
scripts will !e
terminated as soon as
they try to output
somethin% after a client
PHPC,B,CA
Page 167 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
has a!orted their
connection
hi%hli%ht)strin% 4[DDEEEE4 Color for hi%hli%htin% a
strin% in PHP synta/
PHPC,B,CA
hi%hli%ht)comment 4[FFPEEE4 Color for hi%hli%htin%
PHP comments
PHPC,B,CA
hi%hli%ht)+eyword 4[EEIIEE4 Color for synta/
hi%hli%htin% PHP
+eywords 0e)%)
parenthesis and
semicolon3
PHPC,B,CA
hi%hli%ht)!% 4[FFFFFF4 Color for !ac+%round PHPC,B,CA
hi%hli%ht)default 4[EEEE**4 Default color for PHP
synta/
PHPC,B,CA
hi%hli%ht)html 4[EEEEEE4 Color for HT# code PHPC,B,CA
!rowscap B5 Bame and location of
!rowser(capa!ilities file
0e)%) !rowscap)ini3
PHPC,B,CSTSTE#
PHP Misc. -unctions
PHP: indicates the earliest 'ersion of PHP that supports the function)
-unction 1escription PHP
connectionCa!orted03 Chec+s whether the client has disconnected 3
connectionCstatus03 6eturns the current connection status 3
connectionCtimeout03 Deprecated in PHP N)E)9 3
constant03 6eturns the 'alue of a constant N
define03 Defines a constant 3
defined03 Chec+s whether a constant e/ists 3
die03 Prints a messa%e and e/its the current script 3
e'al03 E'aluates a strin% as PHP code 3
e/it03 Prints a messa%e and e/its the current script 3
%etC!rowser03 6eturns the capa!ilities of the user7s !rowser 3
hi%hli%htCfile03 1utputs a file with the PHP synta/ hi%hli%hted N
hi%hli%htCstrin%03 1utputs a strin% with the PHP synta/ N
Page 168 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
hi%hli%hted
i%noreCuserCa!ort03 Sets whether a remote client can a!ort the
runnin% of a script
3
pac+03 Pac+s data into a !inary strin% 3
phpCchec+Csynta/03 Deprecated in PHP 9)E)9 9
phpCstripCwhitespace03 6eturns the source code of a file with PHP
comments and whitespace remo'ed
9
showCsource03 Alias of hi%hli%htCfile03 N
sleep03 Delays code e/ecution for a num!er of seconds 3
timeCnanosleep03 Delays code e/ecution for a num!er of seconds
and nanoseconds
9
timeCsleepCuntil03 Delays code e/ecution until a specified time 9
uni;id03 2enerates a uni;ue ,D 3
unpac+03 5npac+s data from a !inary strin% 3
usleep03 Delays code e/ecution for a num!er of
microseconds
3
PHP Misc. $onstants
PHP: indicates the earliest 'ersion of PHP that supports the constant)
$onstant 1escription PHP
C1BBECT,1BCA*16TED
C1BBECT,1BCB16#A
C1BBECT,1BCT,#E15T
CCC1#P,E6CHATC1FFSETCC
Page 169 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
PHP My." -unctions
PHP My." 'ntroduction
The #yS$ functions allows you to access #yS$ data!ase ser'ers)
'nstallation
For the #yS$ functions to !e a'aila!le. you must compile PHP with
#yS$ support)
For compilin%. use --with-mysql=DI 0the optional D,6 points to the
#yS$ directory3)
0ote5 For full functionality of #yS$ 'ersions %reater than N)J). use the
#yS$i e/tension instead) ,f you would li+e to install !oth the mys;l
e/tension and the mys;li e/tension you should use the same client li!rary to
a'oid any conflicts)
'nstallation on "inu# ystems
PHP H/5 #yS$ and the #yS$ li!rary is not ena!led !y default) 5se the
--with-mysql=DI confi%ure option to include #yS$ support and
download headers and li!raries from www)mys;l)com)
'nstallation on !indows ystems
PHP H/5 #yS$ is not ena!led !y default. so the phpCmys;l)dll must !e
ena!led inside of php)ini) Also. PHP needs access to the #yS$ client
li!rary) A file named li!mys;l)dll is included in the Windows PHP
distri!ution. and in order for PHP to tal+ to #yS$ this file needs to !e
a'aila!le to the Windows systems PATH)
To ena!le any PHP e/tension. the PHP e/tensionCdir settin% 0in the php)ini
file3 should !e set to the directory where the PHP e/tensions are located) An
e/ample e/tensionCdir 'alue is c:XphpXe/t)
0ote5 ,f you %et the followin% error when startin% the we! ser'er: 45na!le to
load dynamic li!rary 7):phpCmys;l)dll74. this is !ecause phpCmys;l)dll or
li!mys;l)dll cannot !e found !y the system)
)untime $onfiguration
Page 170 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
The !eha'ior of the #yS$ functions is affected !y settin%s in the php)ini
file)
#yS$ confi%uration options:
0ame 1efault 1escription $hangeable
mys;l)allowCpersistent 4J4 Whether or not to
allow persistent
connections
PHPC,B,CSTSTE#
mys;l)ma/Cpersistent 4(J4 The ma/imum num!er
of persistent
connections per
process
PHPC,B,CSTSTE#
mys;l)ma/Clin+s 4(J4 The ma/imum num!er
of connections per
process 0persistent
connections included3
PHPC,B,CSTSTE#
mys;l)traceCmode 4E4 Trace mode) When set
to 4J4. warnin%s and
S$(errors will !e
displayed) A'aila!le
since PHP N)3
PHPC,B,CA
mys;l)defaultCport B5 The default TCP port
num!er to use
PHPC,B,CA
mys;l)defaultCsoc+et B5 The default soc+et
name to use) A'aila!le
since PHP N)E)J
PHPC,B,CA
mys;l)defaultChost B5 The default ser'er host
to use 0doesn7t apply in
S$ safe mode3
PHPC,B,CA
mys;l)defaultCuser B5 The default user name
to use 0doesn7t apply in
S$ safe mode3
PHPC,B,CA
mys;l)defaultCpassword B5 The default password
to use 0doesn7t apply in
S$ safe mode3
PHPC,B,CA
mys;l)connectCtimeout 4HE4 Connection timeout in
seconds
PHPC,B,CA
Page 171 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
)esource Types
There are two resource types used in the #yS$ e/tension) The first one is
the lin+Cidentifier for a data!ase connection. the second is a resource which
holds the result of a ;uery)
0ote5 #ost #yS$ functions accept lin+Cidentifier as the last optional
parameter) ,f it is not pro'ided. the last opened connection is used)
PHP My." -unctions
PHP: indicates the earliest 'ersion of PHP that supports the function)
-unction 1escription PHP
mys;lCaffectedCrows03 6eturns the num!er of affected rows in the
pre'ious #yS$ operation
3
mys;lCchan%eCuser03 Deprecated) Chan%es the user of the current
#yS$ connection
3
mys;lCclientCencodin%03 6eturns the name of the character set for
the current connection
N
mys;lCclose03 Closes a non(persistent #yS$ connection 3
mys;lCconnect03 1pens a non(persistent #yS$ connection 3
mys;lCcreateCd!03 Deprecated) Creates a new #yS$
data!ase) 5se mys;lC;uery03 instead
3
mys;lCdataCsee+03 #o'es the record pointer 3
mys;lCd!Cname03 6eturns a data!ase name from a call to
mys;lClistCd!s03
3
mys;lCd!C;uery03 Deprecated) Sends a #yS$ ;uery) 5se
mys;lCselectCd!03 and mys;lC;uery03
instead
3
mys;lCdropCd!03 Deprecated) Deletes a #yS$ data!ase)
5se mys;lC;uery03 instead
3
mys;lCerrno03 6eturns the error num!er of the last
#yS$ operation
3
mys;lCerror03 6eturns the error description of the last
#yS$ operation
3
mys;lCescapeCstrin%03 Deprecated) Escapes a strin% for use in a
mys;lC;uery) 5se
N
Page 172 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
mys;lCrealCescapeCstrin%03 instead
mys;lCfetchCarray03 6eturns a row from a recordset as an
associati'e array and:or a numeric array
3
mys;lCfetchCassoc03 6eturns a row from a recordset as an
associati'e array
N
mys;lCfetchCfield03 6eturns column info from a recordset as an
o!-ect
3
mys;lCfetchClen%ths03 6eturns the len%th of the contents of each
field in a result row
3
mys;lCfetchCo!-ect03 6eturns a row from a recordset as an o!-ect 3
mys;lCfetchCrow03 6eturns a row from a recordset as a
numeric array
3
mys;lCfieldCfla%s03 6eturns the fla%s associated with a field in
a recordset
3
mys;lCfieldClen03 6eturns the ma/imum len%th of a field in a
recordset
3
mys;lCfieldCname03 6eturns the name of a field in a recordset 3
mys;lCfieldCsee+03 #o'es the result pointer to a specified field 3
mys;lCfieldCta!le03 6eturns the name of the ta!le the specified
field is in
3
mys;lCfieldCtype03 6eturns the type of a field in a recordset 3
mys;lCfreeCresult03 Free result memory 3
mys;lC%etCclientCinfo03 6eturns #yS$ client info N
mys;lC%etChostCinfo03 6eturns #yS$ host info N
mys;lC%etCprotoCinfo03 6eturns #yS$ protocol info N
mys;lC%etCser'erCinfo03 6eturns #yS$ ser'er info N
mys;lCinfo03 6eturns information a!out the last ;uery N
mys;lCinsertCid03 6eturns the A5T1C,BC6E#EBT ,D
%enerated from the pre'ious ,BSE6T
operation
3
mys;lClistCd!s03 ists a'aila!le data!ases on a #yS$
ser'er
3
mys;lClistCfields03 Deprecated) ists #yS$ ta!le fields) 5se
mys;lC;uery03 instead
3
mys;lClistCprocesses03 ists #yS$ processes N
Page 173 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
mys;lClistCta!les03 Deprecated) ists ta!les in a #yS$
data!ase) 5se mys;lC;uery03 instead
3
mys;lCnumCfields03 6eturns the num!er of fields in a recordset 3
mys;lCnumCrows03 6eturns the num!er of rows in a recordset 3
mys;lCpconnect03 1pens a persistent #yS$ connection 3
mys;lCpin%03 Pin%s a ser'er connection or reconnects if
there is no connection
N
mys;lC;uery03 E/ecutes a ;uery on a #yS$ data!ase 3
mys;lCrealCescapeCstrin%03 Escapes a strin% for use in S$ statements N
mys;lCresult03 6eturns the 'alue of a field in a recordset 3
mys;lCselectCd!03 Sets the acti'e #yS$ data!ase 3
mys;lCstat03 6eturns the current system status of the
#yS$ ser'er
N
mys;lCta!lename03 Deprecated) 6eturns the ta!le name of
field) 5se mys;lC;uery03 instead
3
mys;lCthreadCid03 6eturns the current thread ,D N
mys;lCun!ufferedC;uery03 E/ecutes a ;uery on a #yS$ data!ase
0without fetchin% : !ufferin% the result3
N
PHP My." $onstants
Since PHP N)3 it has !een possi!le to specify additional fla%s for the
mys;lCconnect03 and mys;lCpconnect03 functions:
PHP: indicates the earliest 'ersion of PHP that supports the constant)
$onstant 1escription PHP
#TS$CC,EBTCC1#P6ESS 5se compression protocol N)3
#TS$CC,EBTC,2B16ECSPACE Allow space after function
names
N)3
#TS$CC,EBTC,BTE6ACT,@E Allow interacti'e timeout
seconds of inacti'ity !efore
closin% the connection
N)3
#TS$CC,EBTCSS 5se SS encryption 0only
a'aila!le with 'ersion NK of the
#yS$ client li!rary3
N)3
Page 174 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
The mys;lCfetchCarray03 function uses a constant for the different types of
result arrays) The followin% constants are defined:
$onstant 1escription PHP
#TS$CASS1C Columns are returned into the array with the
fieldname as the array inde/

#TS$C*1TH Columns are returned into the array ha'in% !oth a
numerical inde/ and the fieldname as the array inde/

#TS$CB5# Columns are returned into the array ha'in% a
numerical inde/ 0inde/ starts at E3

PHP impleAM" -unctions
PHP impleAM" 'ntroduction
The Simple"# functions lets you con'ert "# to an o!-ect)
This o!-ect can !e processed. li+e any other o!-ect. with normal property
selectors and array iterators)
Some of these functions re;uires the newest PHP !uild)
'nstallation
The Simple"# functions are part of the PHP core) There is no installation
needed to use these functions)
PHP impleAM" -unctions
PHP: indicates the earliest 'ersion of PHP that supports the function)
-unction 1escription PHP
CCconstruct03 Creates a new Simple"#Element o!-ect 9
addAttri!ute03 Adds an attri!ute to the Simple"#
element
9
Page 175 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
addChild03 Adds a child element the Simple"#
element
9
as"#03 2ets an "# strin% from a Simple"#
element
9
attri!utes03 2ets a Simple"# element7s attri!utes 9
children03 2ets the children of a specified node 9
%etDocBamespaces03 2ets the namespaces of an "# document 9
%etBame03 2ets the name of a Simple"# element 9
%etBamespaces03 2ets the namespaces from "# data 9
re%ister"PathBamespace03 Creates a namespace conte/t for the ne/t
"Path ;uery
9
simple/mlCimportCdom03 2ets a Simple"#Element o!-ect from a
D1# node
9
simple/mlCloadCfile03 2ets a Simple"#Element o!-ect from an
"# document
9
simple/mlCloadCstrin%03 2ets a Simple"#Element o!-ect from an
"# strin%
9
/path03 6uns an "Path ;uery on "# data 9
PHP impleAM" $onstants
Bone
PHP tring -unctions
PHP tring 'ntroduction
The strin% functions allow you to manipulate strin%s)
'nstallation
The strin% functions are part of the PHP core) There is no installation needed
to use these functions)
PHP tring -unctions
Page 176 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
PHP: indicates the earliest 'ersion of PHP that supports the function)
-unction 1escription PHP
addcslashes03 6eturns a strin% with !ac+slashes in front
of the specified characters
N
addslashes03 6eturns a strin% with !ac+slashes in front
of predefined characters
3
!inMhe/03 Con'erts a strin% of ASC,, characters to
he/adecimal 'alues
3
chop03 Alias of rtrim03 3
chr03 6eturns a character from a specified
ASC,, 'alue
3
chun+Csplit03 Splits a strin% into a series of smaller parts 3
con'ertCcyrCstrin%03 Con'erts a strin% from one Cyrillic
character(set to another
3
con'ertCuudecode03 Decodes a uuencoded strin% 9
con'ertCuuencode03 Encodes a strin% usin% the uuencode
al%orithm
9
countCchars03 6eturns how many times an ASC,,
character occurs within a strin% and
returns the information
N
crc3M03 Calculates a 3M(!it C6C for a strin% N
crypt03 1ne(way strin% encryption 0hashin%3 3
echo03 1utputs strin%s 3
e/plode03 *rea+s a strin% into an array 3
fprintf03 Writes a formatted strin% to a specified
output stream
9
%etChtmlCtranslationCta!le03 6eturns the translation ta!le used !y
htmlspecialchars03 and htmlentities03
N
he!re'03 Con'erts He!rew te/t to 'isual te/t 3
he!re'c03 Con'erts He!rew te/t to 'isual te/t and
new lines 0Xn3 into <!r :>
3
htmlCentityCdecode03 Con'erts HT# entities to characters N
htmlentities03 Con'erts characters to HT# entities 3
htmlspecialcharsCdecode03 Con'erts some predefined HT# entities 9
Page 177 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
to characters
htmlspecialchars03 Con'erts some predefined characters to
HT# entities
3
implode03 6eturns a strin% from the elements of an
array
3
-oin03 Alias of implode03 3
le'enshtein03 6eturns the e'enshtein distance !etween
two strin%s
3
localecon'03 6eturns locale numeric and monetary
formattin% information
N
ltrim03 Strips whitespace from the left side of a
strin%
3
md903 Calculates the #D9 hash of a strin% 3
md9Cfile03 Calculates the #D9 hash of a file N
metaphone03 Calculates the metaphone +ey of a strin% N
moneyCformat03 6eturns a strin% formatted as a currency
strin%
N
nlClan%info03 6eturns specific local information N
nlM!r03 ,nserts HT# line !rea+s in front of each
newline in a strin%
3
num!erCformat03 Formats a num!er with %rouped thousands 3
ord03 6eturns the ASC,, 'alue of the first
character of a strin%
3
parseCstr03 Parses a ;uery strin% into 'aria!les 3
print03 1utputs a strin% 3
printf03 1utputs a formatted strin% 3
;uotedCprinta!leCdecode03 Decodes a ;uoted(printa!le strin% 3
;uotemeta03 $uotes meta characters 3
rtrim03 Strips whitespace from the ri%ht side of a
strin%
3
setlocale03 Sets locale information 3
shaJ03 Calculates the SHA(J hash of a strin% N
shaJCfile03 Calculates the SHA(J hash of a file N
similarCte/t03 Calculates the similarity !etween two 3
Page 178 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
strin%s
sounde/03 Calculates the sounde/ +ey of a strin% 3
sprintf03 Writes a formatted strin% to a 'aria!le 3
sscanf03 Parses input from a strin% accordin% to a
format
N
strCireplace03 6eplaces some characters in a strin% 0case(
insensiti'e3
9
strCpad03 Pads a strin% to a new len%th N
strCrepeat03 6epeats a strin% a specified num!er of
times
N
strCreplace03 6eplaces some characters in a strin% 0case(
sensiti'e3
3
strCrotJ303 Performs the 61TJ3 encodin% on a strin% N
strCshuffle03 6andomly shuffles all characters in a
strin%
N
strCsplit03 Splits a strin% into an array 9
strCwordCcount03 Count the num!er of words in a strin% N
strcasecmp03 Compares two strin%s 0case(insensiti'e3 3
strchr03 Finds the first occurrence of a strin% inside
another strin% 0alias of strstr033
3
strcmp03 Compares two strin%s 0case(sensiti'e3 3
strcoll03 ocale !ased strin% comparison N
strcspn03 6eturns the num!er of characters found in
a strin% !efore any part of some specified
characters are found
3
stripCta%s03 Strips HT# and PHP ta%s from a strin% 3
stripcslashes03 5n;uotes a strin% ;uoted with
addcslashes03
N
stripslashes03 5n;uotes a strin% ;uoted with
addslashes03
3
stripos03 6eturns the position of the first occurrence
of a strin% inside another strin% 0case(
insensiti'e3
9
stristr03 Finds the first occurrence of a strin% inside
another strin% 0case(insensiti'e3
3
Page 179 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
strlen03 6eturns the len%th of a strin% 3
strnatcasecmp03 Compares two strin%s usin% a 4natural
order4 al%orithm 0case(insensiti'e3
N
strnatcmp03 Compares two strin%s usin% a 4natural
order4 al%orithm 0case(sensiti'e3
N
strncasecmp03 Strin% comparison of the first n characters
0case(insensiti'e3
N
strncmp03 Strin% comparison of the first n characters
0case(sensiti'e3
N
strp!r+03 Searches a strin% for any of a set of
characters
9
strpos03 6eturns the position of the first occurrence
of a strin% inside another strin% 0case(
sensiti'e3
3
strrchr03 Finds the last occurrence of a strin% inside
another strin%
3
strre'03 6e'erses a strin% 3
strripos03 Finds the position of the last occurrence of
a strin% inside another strin% 0case(
insensiti'e3
9
strrpos03 Finds the position of the last occurrence of
a strin% inside another strin% 0case(
sensiti'e3
3
strspn03 6eturns the num!er of characters found in
a strin% that contains only characters from
a specified charlist
3
strstr03 Finds the first occurrence of a strin% inside
another strin% 0case(sensiti'e3
3
strto+03 Splits a strin% into smaller strin%s 3
strtolower03 Con'erts a strin% to lowercase letters 3
strtoupper03 Con'erts a strin% to uppercase letters 3
strtr03 Translates certain characters in a strin% 3
su!str03 6eturns a part of a strin% 3
su!strCcompare03 Compares two strin%s from a specified
start position 0!inary safe and optionally
case(sensiti'e3
9
Page 180 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
su!strCcount03 Counts the num!er of times a su!strin%
occurs in a strin%
N
su!strCreplace03 6eplaces a part of a strin% with another
strin%
N
trim03 Strips whitespace from !oth sides of a
strin%
3
ucfirst03 Con'erts the first character of a strin% to
uppercase
3
ucwords03 Con'erts the first character of each word
in a strin% to uppercase
3
'fprintf03 Writes a formatted strin% to a specified
output stream
9
'printf03 1utputs a formatted strin% N
'sprintf03 Writes a formatted strin% to a 'aria!le N
wordwrap03 Wraps a strin% to a %i'en num!er of
characters
N
PHP tring $onstants
PHP: indicates the earliest 'ersion of PHP that supports the constant)
$onstant 1escription PHP
C6TPTCSATCEB2TH Contains the len%th of the default
encryption method for the
system) For standard DES encryption. the
len%th is M

C6TPTCSTDCDES Set to J if the standard DES(!ased
encryption with a M character salt is
supported. E otherwise

C6TPTCE"TCDES Set to J if the e/tended DES(!ased
encryption with a F character salt is
supported. E otherwise

C6TPTC#D9 Set to J if the #D9 encryption with a JM
character salt startin% with AJA is
supported. E otherwise

C6TPTC*1WF,SH Set to J if the *lowfish encryption with a
JH character salt startin% with AMA or AMaA
is supported. E otherwiseE

Page 181 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
HT#CSPEC,ACHA6S
HT#CEBT,T,ES
EBTCC1#PAT
EBTC$51TES
EBTCB1$51TES
CHA6C#A"
CCCTTPE
CCB5#E6,C
CCT,#E
CCC1ATE
CC#1BETA6T
CCA
CC#ESSA2ES
ST6CPADCEFT
ST6CPADC6,2HT
ST6CPADC*1TH
PHP AM" Parser -unctions
PHP AM" Parser 'ntroduction
The "# functions lets you parse. !ut not 'alidate. "# documents)
"# is a data format for standardiDed structured document e/chan%e) #ore
information on "# can !e found in our "# Tutorial)
This e/tension uses the E/pat "# parser)
E/pat is an e'ent(!ased parser. it 'iews an "# document as a series of
e'ents) When an e'ent occurs. it calls a specified function to handle it)
Page 182 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
E/pat is a non('alidatin% parser. and i%nores any DTDs lin+ed to a
document) Howe'er. if the document is not well formed it will end with an
error messa%e)
*ecause it is an e'ent(!ased. non 'alidatin% parser. E/pat is fast and well
suited for we! applications)
The "# parser functions lets you create "# parsers and define handlers
for "# e'ents)
'nstallation
The "# functions are part of the PHP core) There is no installation needed
to use these functions)
PHP AM" Parser -unctions
PHP: indicates the earliest 'ersion of PHP that supports the function)
-unction 1escription PHP
utfPCdecode03 Decodes an 5TF(P strin% to
,S1(PP9F(J
3
utfPCencode03 Encodes an ,S1(PP9F(J
strin% to 5TF(P
3
/mlCerrorCstrin%03 2ets an error strin% from the
"# parser
3
/mlC%etCcurrentC!yteCinde/03 2ets the current !yte inde/
from the "# parser
3
/mlC%etCcurrentCcolumnCnum!er03 2ets the current column
num!er from the "#
parser
3
/mlC%etCcurrentClineCnum!er03 2ets the current line num!er
from the "# parser
3
/mlC%etCerrorCcode03 2ets an error code from the
"# parser
3
/mlCparse03 Parses an "# document 3
/mlCparseCintoCstruct03 Parse "# data into an
array
3
/mlCparserCcreateCns03 Create an "# parser with
namespace support
N
Page 183 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
/mlCparserCcreate03 Create an "# parser 3
/mlCparserCfree03 Free an "# parser 3
/mlCparserC%etCoption03 2et options from an "#
parser
3
/mlCparserCsetCoption03 Set options in an "#
parser
3
/mlCsetCcharacterCdataChandler03 Set handler function for
character data
3
/mlCsetCdefaultChandler03 Set default handler function 3
/mlCsetCelementChandler03 Set handler function for start
and end element of elements
3
/mlCsetCendCnamespaceCdeclChandler03 Set handler function for the
end of namespace
declarations
N
/mlCsetCe/ternalCentityCrefChandler03 Set handler function for
e/ternal entities
3
/mlCsetCnotationCdeclChandler03 Set handler function for
notation declarations
3
/mlCsetCo!-ect03 5se "# Parser within an
o!-ect
N
/mlCsetCprocessin%CinstructionChandler03 Set handler function for
processin% instruction
3
/mlCsetCstartCnamespaceCdeclChandler03 Set handler function for the
start of namespace
declarations
N
/mlCsetCunparsedCentityCdeclChandler03 Set handler function for
unparsed entity declarations
3
PHP AM" Parser $onstants
$onstant
"#CE6616CB1BE 0inte%er3
"#CE6616CB1C#E#16T 0inte%er3
"#CE6616CSTBTA" 0inte%er3
Page 184 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
"#CE6616CB1CEE#EBTS 0inte%er3
"#CE6616C,B@A,DCT1UEB 0inte%er3
"#CE6616C5BC1SEDCT1UEB 0inte%er3
"#CE6616CPA6T,ACCHA6 0inte%er3
"#CE6616CTA2C#,S#ATCH 0inte%er3
"#CE6616CD5P,CATECATT6,*5TE 0inte%er3
"#CE6616C85BUCAFTE6CD1CCEE#EBT 0inte%er3
"#CE6616CPA6A#CEBT,TTC6EF 0inte%er3
"#CE6616C5BDEF,BEDCEBT,TT 0inte%er3
"#CE6616C6EC56S,@ECEBT,TTC6EF 0inte%er3
"#CE6616CASTBCCEBT,TT 0inte%er3
"#CE6616C*ADCCHA6C6EF 0inte%er3
"#CE6616C*,BA6TCEBT,TTC6EF 0inte%er3
"#CE6616CATT6,*5TECE"TE6BACEBT,TTC6EF 0inte%er3
"#CE6616C#,SPACEDC"#CP, 0inte%er3
"#CE6616C5BUB1WBCEBC1D,B2 0inte%er3
"#CE6616C,BC166ECTCEBC1D,B2 0inte%er3
"#CE6616C5BC1SEDCCDATACSECT,1B 0inte%er3
"#CE6616CE"TE6BACEBT,TTCHABD,B2 0inte%er3
"#C1PT,1BCCASECF1D,B2 0inte%er3
"#C1PT,1BCTA62ETCEBC1D,B2 0inte%er3
"#C1PT,1BCSU,PCTA2STA6T 0inte%er3
"#C1PT,1BCSU,PCWH,TE 0inte%er3
PHP Iip -ile -unctions
PHP Iip -ile 'ntroduction
The &ip files functions allows you to read &,P files)
Page 185 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
'nstallation
For the &ip file functions to wor+ on your ser'er. these li!raries must !e
installed:
The &&,Pli! li!rary !y 2uido Draheim: Download the &&,Pli!
li!rary
The &ip PEC e/tension: Download the &ip PEC e/tension
'nstallation on "inu# ystems
PHP H/5 &ip functions and the &ip li!rary is not ena!led !y default and must
!e downloaded from the lin+s a!o'e) 5se the --with-!ip=DI confi%ure
option to include &ip support)
'nstallation on !indows ystems
PHP H/5 &ip functions is not ena!led !y default. so the phpCDip)dll and the
&&,Pli! li!rary must !e downloaded from the lin+ a!o'e) phpCDip)dll must
!e ena!led inside of php)ini)
To ena!le any PHP e/tension. the PHP e/tensionCdir settin% 0in the php)ini
file3 should !e set to the directory where the PHP e/tensions are located) An
e/ample e/tensionCdir 'alue is c:XphpXe/t)
PHP Iip -ile -unctions
PHP: indicates the earliest 'ersion of PHP that supports the function)
-unction 1escription PHP
DipCclose03 Closes a &,P file N
DipCentryCclose03 Closes an entry in the &,P file N
DipCentryCcompressedsiDe03 6eturns the compressed siDe of an
entry in the &,P file
N
DipCentryCcompressionmethod03 6eturns the compression method of an
entry in the &,P file
N
DipCentryCfilesiDe03 6eturns the actual file siDe of an entry
in the &,P file
N
DipCentryCname03 6eturns the name of an entry in the
&,P file
N
DipCentryCopen03 1pens an entry in the &,P file for N
Page 186 of 187
Tutorial PHP by www.w3schools.com
Organized by Nur Dwi Muryanto, 2!
readin%
DipCentryCread03 6eads from an open entry in the &,P
file
N
DipCopen03 1pens a &,P file N
DipCread03 6eads the ne/t entry in a &,P file N
PHP Iip -ile $onstants
B1BE
Page 187 of 187

You might also like