Professional Documents
Culture Documents
Youth Dreams
Part (I)
Part
(II)
First edition
Second edition
First Edition
Chapter
PHP
Web Developer
PHP
Programming
..code
run
code
w3schools.com reference
moemyintsheinster@gmail.com
www.moemyintshein.com
Youth Dreams
Contents at a Glance
Chapter 1
Introducing PHP
Chpater 2
Chapter 3
14
Chapter 4
25
Chapter 5
32
Chapter 6
54
Chapter 7
74
Chapter 8
83
Chapter 9
97
124
Conclusion
136
Youth Dreams
scripting language
PHP
web
scripts
stand
alone
application
application
PHP
) PHP
Rasmus
Lerdorf
1994
PHP
PHP
programming language
PHP
THE
PHP GROUP maintain
free
software
PHP general-purpose scripting language
web
development
HTML
coding
web server
run
web servers
Operating
System
Platform
PHP
websites
web
server
install
syntax
operating
system
Apache
(web
server)
Perl
Windows
Microsoft
IIS
official current release
15, 2010)
PHP 4 PHP 5
PHP
language
database
open source
PHP
JSP, ROR
ASP.net
..
PHP
PHP
server-side language
code
server
run
server-side language
web page
host
server
information
server
run
browser
web
page
click
click
result
server
Input
server
server-side
client-side language
user
client
run
JavaScript
client web browser
web server
information
Youth Dreams
browser code
interprets
client-side server-side
form
sign up
text box
data
valid
submit
server
server
information
web server
save
server side
server
request
PHP
My SQL Database
PHP
software
localhost
software
package software
software
web server
database
software
windows
WAMP
XAMPP
XAMPP
http://www.apachefriends.org/en/xampp.html
windows version
xampp installer
software
xampp
htdocs
php
folder
save
PHP
PHP,
Apache
MySQL
Install
Part (II)
XAMPP
text
editor
PHP editor
Dream weaver CS 4
Notepad
Youth Dreams
<?php
?>
PHP block
document
<?
?>
<?php
?>
PHP file
HTML
HTML tag
PHP code
PHP script
browser
Hello World
code
<html>
<body>
<?php
echo "Hello World";
?>
</body>
</html>
code
run
Dreamweaver
PHP
code
Notepad
code
copy paste
save
.. save
C
xampp
htdocs
php
1.php, 2.php
browser
http://localhost/php/1.php, http://localhost/php/2.php
PHP
code
semicolon
semicolon
separator
PHP
text
output
statements
echo
print
echo
Hello World
output
save
.php
.html
PHP code
Comments in PHP
PHP
single line comment
//
/*
*/
Youth Dreams
<html>
<body>
<?php
//This is a comment
/*
This is
a comment
block
*/
?>
</body>
</html>
PHP Variables
variable
number
strings
arrays
function
result
variable
php script
PHP
variable
$var_name = value;
string variable
number variable
<?php
$txt = "Hello World!";
$number = 10;
?>
PHP
variable
data type
variable
data
type
data type
PHP
Java
Strong
type language
data type
variable
variable name
letter
underscore _
variable name
alpha-numeric characters
underscores (
_ )
Youth Dreams
variable name
space
variable name
( word )
underscore (_)
($my_string)
capital letter
($myString)
Strings in PHP
String variable
string
function
operators
String
string
function
variable
Hello
World
String
$txt
string
variable
assign
<?php
$txt = "Hello World";
echo $txt;
?>
output
Hello World
string
function
operators
manipulate
operator
concatenation operator
(.)
string value
string
<?php
$txt1="Hello World";
$txt2="12345";
echo $txt1 . " " . $txt2;
?>
output
Hello World 12345
code
concatenation operator
(.)
string
(empty
space)
length
Hello World!
string
length
Youth Dreams
<?php
echo strlen("Hello World!");
?>
output
12
string
length
looping
function
character
string
<?php
echo strpos("Hello World!", "World");
?>
output
6
World
string
position 1
PHP
string
function
PHP Operators
PHP
operator
Arithmetic Operators
Arithmetic Operators
run
<?php
$no1=2;
10
Youth Dreams
10
$no2=3;
$no3= $no1+$no2;
echo $no3;
?>
code
run
output 5
Division
15
2.5
<?php
$no1=5;
$no2=2;
$no3= $no1/$no2;
echo $no3;
?>
Modulus
5%2
1
.. 10%2
<?php
$no1=5;
$no2=2;
$no3= $no1%$no2;
echo $no3;
?>
Assignment Operators
Assignment Operators
..PHP
x=x+y
x
PHP
assignment operator
x+=y
run
11
Youth Dreams
11
<?php
$x=5;
$y=2;
$z= $x+=$y;
echo $z;
?>
Output 7
Comparison Operators
Comoparison Operators
==
5 8
5==8
result
false
$x=5;
$y=2;
if ($x==$y)
echo true;
else echo false;
?>
code
run
false
variable x y 3
run
output true
$x=3;
$y=3;
if ($x==$y)
echo "true";
else echo "false";
?>
12
Youth Dreams
12
Logical Operators
Logical Operators
.. Operator
13
Youth Dreams
13
condition
Conditional Statements
coding
conditional statements
code
run
..
code
run
ifelse statement
syntax
if (condition)
else
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
else
echo "Have a nice day!";
?>
</body>
</html>
code
run
..
Computer
System Date
Tuesday
run
Have a nice day
:)
14
Youth Dreams
14
condition
code
run
curly braces
{ }
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
{
echo "Hello! <br/>";
echo "Have a nice weekend!";
echo " See you on Monday!";
}
?>
</body>
</html>
code
output
Hello!
Have a nice weekend! See you on Monday!
..
The elseif statement
condition
code
run
elseif statement
syntax
if (condition)
elseif (condition)
else
<html>
<body>
15
Youth Dreams
15
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
elseif ($d=="Sun")
echo "Have a nice Sunday!";
else
echo "Have a nice day!";
?>
</body>
</html>
output
Have a nice day!
code
run
case
switch case statement
ifelseifelse statement
Syntax
switch (expression )
{
case label1:
case label2:
default:
code to be executed
if expression is different
run
<html>
<body>
<?php
16
Youth Dreams
16
$x=4;
switch ($x)
{
case 1:
echo "Number 1";
break;
case 2:
echo "Number 2";
break;
case 3:
code
run
No
number
between
and
..
$x=2
assign
$x=4
Number 2
output
single expression
variable
evaluate
.. code
case
expression
case
code
execute (run)
execute
case
run
break
case
default statement
execute
PHP Arrays
array
variable
name
variable
variable
array
elements
array
element
(ID)
array
array
array
17
Youth Dreams
17
-Multidimensional array-
array
array
Numeric array
numeric array
$names = array("MgMg","MaMa","KoKo");
ID key
code
manual
$names[0] = "MgMg";
$names[1] = "MaMa";
$names[2] = "KoKo";
PHP coding
<?php>
$names[0] = "MgMg";
$names[1] = "MaMa";
$names[2] = "KoKo";
echo $names[1] . " and " . $names[2] . " are " . $names[0] . "'s neighbours";
?>
output
Associative Arrays
associative array
ID key
numerical array
associative
arrays
key
array
assign
array
assign (
..
array
$ages['MgMg'] = "18";
18
Youth Dreams
18
$ages['MaMa'] = "20";
$ages['KoKo'] = "19";
code
PHP
<?php>
$ages['MgMg'] = "18";
$ages['MaMa'] = "20";
$ages['KoKo'] = "19";
echo "KoKo is" . $ages['KoKo'] . " years old.";
?>
output
KoKo is19 years old.
Multidimensional Arrays
multidimensional array
array
..
array
element
array
sub array
elelment
array
..
<?php
$families = array
(
"Griffin"=>array
(
"Peter",
"Lois",
"Megan"
),
"Quagmire"=>array
(
"Glenn"
),
"Brown"=>array
(
"Cleveland",
"Loretta",
"Junior"
)
);
echo "Is " . $families['Griffin'][2] .
" a part of the Griffin family?";
19
Youth Dreams
19
?>
php code
$families
variable
array
Griffin, Quagmire,
Brown
Griffin
array
Quagmire
Glenn Brown
run
Output
Is Megan a part of the Griffin family?
Griffin array
Megan
Peter
Lois
PHP Looping
code
run
looping
PHP
looping
statements
while -
code
run
run
dowhile -
code
run
..
run
for -
code
run
foreach array
element
code
run
code
run
run
Syntax
while (condition)
code to be executed;
Example
code
variable i
looping
loop
<html>
<body>
<?php
$i=1;
while ($i<=5)
{
echo "The number is " . $i . "<br/>";
$i++;
}
?>
20
Youth Dreams
20
</body>
</html>
output
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
variable i
1 assign
..
.. i
{ }
code
The number is 1
output
<br/>
.. i
.. }
while
.. i
.. The number is 2
..
while
.. { }
code
..
code
run
..
run
..
run
Syntax
do
{
code to be executed;
}
while (condition);
Example
<html>
21
Youth Dreams
21
<body>
<?php
$a=0;
do
{
$a++;
echo "The number is " . $a . "<br/>";
}
while ($a<5);
?>
</body>
</html>
variable a
do {}
code
.. a
echo
The number is 1
..<br/>
..a
do
do { }
..a
looping
..
output
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
code
run
for
statement
syntax
for (init; cond; incr)
{
code to be executed;
}
init
initial value
..
cond
condition
condition
loop
incr
init
increment
Hellow World!
<html>
<body>
22
Youth Dreams
22
<?php
for ( $i=1; $i<=10; $i++)
{
echo "Hello World!<br />";
}
?>
</body>
</html>
variable i
i 10
..
Hello
World!
.. i
..i 2
.. 10
..
Hello World!
..
program
output
..
10
11
.. Looping
..output
Hello World!
array
looping
Syntax (
)
foreach (array as value)
{
code to be executed;
}
<html>
<body>
<?php
$arr=array("one", "two", "three");
foreach ($arr as $value)
{
echo "Value: " . $value. "<br />";
}
?>
</body>
</html>
output
23
Youth Dreams
23
Value: one
Value: two
Value: three
looping
array element
$value
assign
array
pointer
element
24
Youth Dreams
24
PHP
function
..PHP
built-in
functions
700
function
..
function
function
function ()
function
function
letter
underscore
function
function
code
..
function
function
Example
<html>
<body>
<?php
function writeMyName()
{
echo "Moe Myint Shein";
}
writeMyName();
?>
</body>
</html>
writeMyName()
function
..
code
screen
.. function
writeMyName();
<html>
<body>
25
Youth Dreams
25
<?php
function writeMyName()
{
echo "Moe Myint Shein";
}
echo "Hello World! <br />";
echo "My name is ";
writeMyName();
echo ". <br /> That's right, ";
writeMyName();
output
Hello World!
My name is Moe Myint Shein.
That's right, Moe Myint Shein is my name.
function
writeMyName()
function
string
echo
function
parameters
parameter
variable
writeMyName()
function name
parentheses
()
paramenter
parentheses
Example 1
first name
<html>
<body>
<?php
function writeMyName($fname)
{
echo $fname. "Moe. <br />";
}
echo "My name is ";
26
Youth Dreams
26
writeMyName("Shwe");
echo "My name is ";
writeMyName("Ngwe");
echo "My name is ";
writeMyName("Sein");
?>
</body>
</html>
output
My name is ShweMoe.
My name is NgweMoe.
My name is SeinMoe
writeMyName ()
function
$fname
parameter
function
code
.. $fname
parameter
Moe
echo
writeMyName()
function
Shwe
parameter
writeMyName(Shwe);
$fname
Shwe
ShweMoe
parameter
<html>
<body>
<?php
function writeMyName($fname, $punctuation)
{
echo $fname. "Moe". $punctuation . "<br />";
}
echo "My name is ";
writeMyName("Shwe", ".");
echo "My name is ";
writeMyName("Ngwe","!");
echo "My name is ";
writeMyName("Sein","...");
?>
</body>
</html>
run
27
Youth Dreams
27
My name is ShweMoe.
My name is NgweMoe!
My name is SeinMoe...
$punctuation
parameter
. , !,
function
return
<html>
<body>
<?php
function add($x,$y)
{
$total= $x + $y;
return $total;
}
echo "1+16=" . add(1,16);
?>
</body>
</html>
output - 1+16=17
add () function
$x
$y parameter
parameter
$total
..
$total
return
.. add() function
$total
add(1,16);
function
function
.. 1
16
$total
17
..
return
output
1+16=17
Form
PHP
$_GET
$_POST
variable
HTML form PHP form
HTML Page
form element
PHP code
<html>
<body>
<form action = "welcome.php" method="post">
Name: <input type="text" name="name"/>
Age:<input type="text" name ="age"/>
<input type="submit"/>
</form>
28
Youth Dreams
28
</body>
</html>
code
form1.html
save
input field
button
user
form
submit button
form
welcome.php
file
welcome.php
button
object not
found
welcome.php
<html>
<body>
welcome.php
form1.html
folder
save
..
form1.html
http://localhost/php/form1.html
run
submit
button
output
PHP $_GET
PHP $_GET variable
get method
form
variable names
array
GET
method
(browser
address
bar
100 characters
Example
<form action ="welcome1.php" method ="get">
Name:<input type="text" name = "name1"/>
Age: <input type= "text" name = "age1"/>
<input type="submit"/>
</form>
code
form2.php
save
php
html file
C:
xampp
htdocs
php
save
http://localhost/php/form2.php
run
) welcome1.php
file
save
Welcome <?php echo $_GET["name1"]; ?>.<br />
29
Youth Dreams
29
form2.php
run
text box
submit button
address
bar
http://localhost/php/welcome1.php?name1=Moe+Myint+Shein&age1=20
.. welcome1.php
name1
age1
$GET variable
catch
browser
Welcome moemyintshein.
You are 20 years old!
$_GET variable
variable name
address bar
password
variable
URL
variable values
character
100
$_COOKIE
Get method
POST method
data
result
welcome1.php
$_GET
$_REQUEST
variable name
values
array
method= post
form
POST method
form3.php
save
Example
<form action="welcome2.php" method="post">
Enter your name: <input type="text" name="name" />
Enter your age: <input type="text" name="age" />
<input type="submit" />
</form>
welcome2.php
code
POST
30
Youth Dreams
30
form3.php
run
submit
GET method
address bar
http://localhost/php/welcome2.php
output
GET
method
$_REQUEST Variable
$POST
..
GET method
POST method
31
Youth Dreams
31
function
Syntax
date(format, timestamp)
format
parameter
format
timestamp
optional
default
timestamp
timestamp
1970
GMT 00:00:00
Unix Timestamp
date() function
parameter
format date/time
format
letter
d -
(01-31)
m -
(01-12)
Y digit
/, ., -
character
letter
<?php
echo date("Y/m/d");
echo "<br />";
echo date("Y.m.d");
echo "<br />";
echo date ("Y-m-d");
?>
code
run
output
2009/09/13
2009.09.13
2009-09-13
date()
function
format
parameter
timestamp
parameter
timestamp
mktime ()
function
timestamp
mktime() function
specified date
Unix timestamp
return
Syntax
mktime() function
day
argument
32
Youth Dreams
32
<?php
$tomorrow = mktime(0,0,0,date("m"),date("d")+1, date("Y"));
echo "Tomorrow is ". date("Y/m/d", $tomorrow);
?>
13
SSI
functions
header
footer
elements
require()
function
PHP file
run
file
content
function
include () function
warning
..
script
execute
script
execute
function
developer
web
page
header
menu file
header
update
include
file
update
site
web page
link
update
menu
file
Example
header.php
header file
header file
page
include() function
<html>
<body>
<?php include("header.php"); ?>
<h1> Welcome to my home page</h1>
<p> Some text</p>
</body>
</html>
Example 2
33
Youth Dreams
33
include
file
.php
web
page
menu file
menu.php
<html>
<body>
<a href ="http://www.moemyintshein.com/default.php"> Home </a> |
<a href= "http://www.moemyintshein.com/about.php"> About Me</a> |
<a href="http://www.moemyintshein.com/contact.php"> Contact Me</a>
</body>
</html>
default.php , about.php
contact.php
file
menu.php
file
default.php
code
<html>
<body>
<?php include("menu.php");?>
<h1> Welcome to my home page</h1>
<p> Some text</p>
</body>
</html>
menu.php
run
output
default.php
run
default.php
menu.php
directory(folder)
about.php
<html>
<body>
<?php include("menu.php");?>
<h1> Welcome to my about me page.</h1>
<p> Some text</p>
</body>
</html>
34
Youth Dreams
34
Output
source
<html>
<body>
<html>
<body>
<a href="http://www.w3schools.com/default.php">Home</a> |
<a href="http://www.w3schools.com/about.php">About Us</a> |
<a href="http://www.w3schools.com/contact.php">Contact Us</a><h1> Welcome to my about me
page.</h1>
<p> Some text</p>
</body>
</html>
contact.php
include
include.php
file
menu
link
site
web page
page
file
menu.php
code
()
function
include()
function
error
include() function
warning
script
run
require() function
error message
execute
include() function
error
error message
PHP CODE
<html>
<body>
<?php
include("wrongFile.php");
35
Youth Dreams
35
include()
on
[function.include]:
(include_path='.;C:\xampp\php\pear\')
line
Failed
in
opening
'wrongFile.php'
C:\xampp\htdocs\php\10.php
for
on
inclusion
line
Hello World!
error message
echo
Hello World
execute
include
warning
execute
require() function
PHP CODE
<html>
<body>
<?php
require("wrongFile.php");
echo "Hello World!";
?>
</body>
</html>
Error Message
error:
require()
on
[function.require]:
line
Failed
opening
required
'wrongFile.php'
36
Youth Dreams
36
echo statement
execute
require
error
execute
include()
require()
recommend
file
missing
script
execute
function
parameter
..
parameter
<html>
<body>
<?php
$file=fopen("welcome.txt","r");
?>
</body>
</html>
file
parameter
mode
r
read only
welcome.txt
file
directory
fopen() function
error message
<html>
<body>
<?php
Closing a File
fcolse() function
..
<?php
37
Youth Dreams
37
$file = fopen("welcome2.txt","r");
//some code to be executed
fclose($file);
?>
Checking End-of-File
feof() function
(End of File)
function
data length
looping
read
read
fopen() function file
false(0)
return
<?php
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
{
echo fgets($file). "<br />";
}
fclose($file);
?>
run
welcome.txt
read
echo
browser
welcome.txt
character
read
character
read
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
while (!feof($file))
{
echo fgetc($file);
}
fclose($file);
?>
38
Youth Dreams
38
PHP
server
file
upload
user
upload
form
HTML code
upload
<html>
<body>
<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"/>
<br/>
run
browser
browse
submit
upload
..
form
submit button
upload_file.php
run
upload_file.php
<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
39
Youth Dreams
39
remote server
client computer
parameter
input name
..
index
name, type, size, tmp_name,
error
$_FILES[file][name]- upload
$_FILES[file][type]- upload
$_FILES[file][size]- upload
size (bytes
$_FILES[file][error]-
upload
error code
$_FILES[file][tmp_name]- server
php
upload
security
user
upload
Restrictions on Upload
script
upload
user
gif
jpeg
upload
20
kb
<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
40
Youth Dreams
40
server
upload
php script
upload
store
location
<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
else
{
41
Youth Dreams
41
code
upload.php
run
php
directory (C:\xampp\htdocs\php)
upload
folder
..
upload
upload
folder
file
local
web hosting
PHP Cookies
cookie
user
identity
cookie
user
browser
web page
request
cookie
PHP
cookie
setcookie() function
setcookie() function
<html> tag
setcookie (name,value,expire,path,domain);
cookie
set
syntax
Example
user
cookie
Alex
Porter
expire
<?php
setcookie("user", "Alex Porter", time()+3600);
?>
<html>
....
cookie
expire time
<?php
$expire=to,e()+60*60*24*30;
setcookie("user", "Alex Porter", $expire);
?>
<html>
.....
expire time
(60 sec * 60 min * 24 hours * 30
days).
42
Youth Dreams
42
Cookie
Retrieve
<?php
//Print a cookie
echo $_COOKIE["user"];
// A way to view all cookies
print_r($_COOKIE);
?>
user
cookie
isset()
function
cookie
<html>
<body>
<?php
if (isset($_COOKIE["user"]))
echo "Welcome" . $_COOKIE["user"] . "!<br/>";
else
echo "Welcome guest!<br />";
?>
</body>
</html>
Cookie
cookie
expiration date
<?php
//set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>
Browser
Cookie
support
form
Submit button
user
welcome.php
user input
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"/>
43
Youth Dreams
43
code
form1.php
save
welcome.php
retrieve
<html>
<body>
Welcome <?php echo $_POST["name"]; ?>. <br />
You are <?php echo $_POST["age"]; ?> years old.
</body>
</html>
forum1.php
Browser
run
text box
submit
moemyintshein
20
submit
Welcome moemyintshein.
You are 20 years old.
PHP Sessions
user session
user
application
application
..
.
session
computer
web server
..
HTTP
state
maintain
PHP session
remember
user
server
session
information
user
website
database
data
session
visitor
UID
variable
UID
cookie
URL
propagated
44
Youth Dreams
44
PHP session
user information
session
session_start() function
<html> tag
server
user session
register
user Information
user session
UID
assign
PHP $_SESSION variable
<?php
session_start();
//store session data
$_SESSION['views']=1;
?>
<html>
<body>
<?php
//retrieve session data
Pageviews=1
isset() function
views
variable
..
counter
views variable
<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
45
Youth Dreams
45
run
. relode
views
Destroying a Session
session
data
unset()
function
sessopm_destroy()
function
unset() function
session variable
free
<?php
unset($_SESSION['views']);
?>
session_destroy()function
session
<?php
session_destroy();
?>
PHP Mail Function
PHP script
PHP
mail() function
Syntax
mail(to,subject,message,headers,parameters)
parameter
headers
parameters
Optional
46
Youth Dreams
46
PHP
text
variable
mail() function
<?php
$to= "mail@moemyintshein.com";
$subject="Test mail";
$message="Hello! This is a simple email message.";
$from= "gtalk@moemyintshein";
$headers="From: $from";
mail($to,$subject,$message,$headers);
echo "Mail Sent.";
?>
PHP Mail Form
PHP
website
feedback-form
form
<html>
<body>
<?php
if (isset($_REQUEST['email']))
//if "email" is filled out, send email
{
//send email
$email = $_REQUEST['email'] ;
$subject = $_REQUEST['subject'] ;
$message = $_REQUEST['message'] ;
mail( "someone@example.com", "Subject: $subject",
$message, "From: $email" );
echo "Thank you for using our mail form";
}
else
47
Youth Dreams
47
code
save
mailform.php
save
email
input
field
HTML form
form
submit buttion
page
reload
input field
SMTP
smtp_post
php.ini file
..
..
..
security
48
Youth Dreams
48
code
unauthorized user
input form
mail
header
data
user form
input fileld
someone@example.com%0ACc:person2@example.com
%0ABcc:person3@example.com,person3@example.com,
anotherperson4@example.com,person5@example.com
%0ABTo:person6@example.com
code form
email field
input
validate
<html>
<body>
<?php
function spamcheck($field)
{
//filter_var() sanitizes the e-mail
//address using FILTER_SANITIZE_EMAIL
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
//filter_var() validates the e-mail
//address using FILTER_VALIDATE_EMAIL
if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return TRUE;
}
else
{
return FALSE;
}
}
if (isset($_REQUEST['email']))
{//if "email" is filled out, proceed
//check if the email address is invalid
$mailcheck = spamcheck($_REQUEST['email']);
if ($mailcheck==FALSE)
{
echo "Invalid input";
}
49
Youth Dreams
49
else
{//send email
$email = $_REQUEST['email'] ;
$subject = $_REQUEST['subject'] ;
$message = $_REQUEST['message'] ;
mail("someone@example.com", "Subject: $subject",
$message, "From: $email" );
echo "Thank you for using our mail form";
}
}
else
{//if "email" is not filled out, display the form
echo "<form method='post' action='mailform.php'>
Email: <input name='email' type='text' /><br />
Subject: <input name='subject' type='text' /><br />
Message:<br />
<textarea name='message' rows='15' cols='40'>
</textarea><br />
<input type='submit' />
</form>";
}
?>
</body>
</html>
code
PHP Filter
input
string
The
FILTER_VALIDATE_EMAIL
email
format
PHP Filter
filter
error message
error
browser
web application
error handling
code
error checking code
security risk
PHP
error
50
Youth Dreams
50
Error reporting
text file
code
..
error
error message
user
..
code
access
<?php
if(!file_exists("welcome.txt"))
{
die("File not found");
}
else
{
#file=fopen("welcome.txt"."r");
}
?>
welcome.txt
error message
code
..error
code
run
error handling
..
error handling
php function
error
function
function
parameters
( error level
error message)
parameter
(optional: file, line number, error context)
Syntax
error_function (error_level, error_message, error_file, error_line, error_context)
51
Youth Dreams
51
error handler
error
..
error
function
code
run
error level
error message
output
script
trigger
( run
)
function
default error
handler
script
error
error handler
52
Youth Dreams
52
error
error
error handler
set_error_handler(customError);
error
function
set_error_handler() function
parameter
parameter
error
level
variable
Output
error handler
<?php
//error handler function
function customError($errno, $errstr)
{
echo "<b>Error:</b> [$errno] $errstr";
}
//set error handler
set_error_handler("customError");
//trigger error
echo($test);
?>
run
output
Trigger an Error
user data
input
script
illegal input
errors
trigger
PHP
trigger_error() function
test
varuable 1
error
<?php
$test=2;
if ($test>1)
{
trigger_error("Value must be 1 or below");
}
?>
run
output
53
Youth Dreams
53
web server
data
JavaScript
AJAX
user
web
page
relode
web server
data exchange
web page
responsive
AJAX
standards
-JavaScript
-XML
-HTML
-CSS
PHP
AJAX
PHP
..
..
AJAX
major browser
support
AJAX application
browser
platform
web application
html form
input
web server
submit
process
user
web page
return
user input
web page
server
user friendly
AJAX
web application
web page
relode
data
server
HTTP request
server data
JavaScript
web page
modify
server
..
AJAX
browser
run
browser
web server
web page
server
web page
web
browser
technology
tutorial
PHP
server
run
54
Youth Dreams
54
AJAX XMLHttpReuest
XMLHttpRequest object
AJAX
July 2000 Internet Explorer
2005
AJAX
Web 2.0
browser
XMLHttpRequest object
Internet Explorer ActiveXObject
browser
build in
JavaScript object
XMLHttpRequest
code
var XMLHttp=null
if (window.XMLHttpRequest)
{
XMLHttp=new XMLHttpRequest()
}
else if (window.ActiveXObject)
{
XMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
}
XMLHttpRequest object
XMLHttp variable
null
window.XMLHttpRequest
object available
Firefox, Opera, Safari
version
available
available
XMLHttp=new
XMLHttpRequest()
object
available
window.ActiveXObject available
Internet Explorer 5.5
available
available
XMLHttp=new ActiveXObject()
object
XMLHttpRequest object
Microsoft.XMLHTTP Xsxml2.XMLHTTP
Microsoft
latest version
load
IE 6
available
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
55
Youth Dreams
55
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
XMLHttpRequest object
XMLHttp
variable
Microsoft
IE
XMLHttp=new
ActiveXObject(Msxml2.XMLHTTP object
error
AJAX Suggest
AJAX
user web form
data
web page
web server
communticate
box
character
suggestion
page
HTML page
JavaScript page
PHP page
HTML page
form
HTML code
JavaScript
link
html file
ajaxtesting.html
<html>
<head>
<script src="clienthint.js"></script>
</head>
<body>
56
Youth Dreams
56
<form>
First Name:
<input type="text" id="txt1"
onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>
txt1
Input filed
HTML form
1.
keyboard
key
release
event
2.
evernt
showHint()
function
execute
3.
form
txtHint
<span>
showHint()
return data
JavaScript code
clienthint.js
HTML document
var xmlHttp;
function showHint(str)
{
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="gethint.php";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
57
Youth Dreams
57
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}// JavaScript Document
character
input filed
input
str.length>0
execute
1.
server
url filename
gethint.php
2.
input
filed
content
(character)
parameter
(q)
3.
58
random number
Youth Dreams
58
4.
GetXmlHttpObject function
XMLHTTP object
object
StateChanged
function
execute
5.
url
XMLHTTP object
6.
server
HTTP request
input filed
function txtHint
placeholder (suggestion
content (
)
function
execute(
state 4
complete
txtHint
content
response
text
browser
run
GetXMLHttpObjet()
XMLHTTP object
PHP page
JavaScript code
server page
gethint.php
Php file
gethint.php
code
array
client
return
<?php
// Fill up array with names
$a[]="Anna";
$a[]="Brittany";
$a[]="Cinderella";
$a[]="Diana";
$a[]="Eva";
$a[]="Fiona";
$a[]="Gunda";
$a[]="Hege";
$a[]="Inga";
$a[]="Johanna";
$a[]="Kitty";
$a[]="Linda";
$a[]="Nina";
$a[]="Ophelia";
$a[]="Petunia";
$a[]="Amanda";
$a[]="Raquel";
$a[]="Cindy";
$a[]="Doris";
$a[]="Eve";
59
Youth Dreams
59
$a[]="Evita";
$a[]="Sunniva";
$a[]="Tove";
$a[]="Unni";
$a[]="Violet";
$a[]="Liza";
$a[]="Elizabeth";
$a[]="Ellen";
$a[]="Wenche";
$a[]="Vicky";
$hint=$a[$i];
}
else
{
$hint=$hint." , ".$a[$i];
}
}
}
}
//Set output to "no suggestion" if no hint were found
//or to the correct values
if ($hint == "")
{
$response="no suggestion";
}
else
{
$response=$hint;
60
Youth Dreams
60
}
//output the response
echo $response;
?>
JavaScript
(strlen($q)>0)
text
1.
JavaScript
character
match
2.
response string
3.
match
no suggestion
response
5.
response
txtHint placeholder
4.
response
folder directory
save
..
ajaxtesting.html
browser
run
PHP
AJAX
web application
:D
AJAX
XML file
web page
AJAX
XML file
(fetch)
Select a CD:
..
CD info
HTML form
XML file
JavaScript
PHP page
HTML form
JavaScript
HTML code
ajaxxml.html
save
<html>
<head>
<script src="selectcd.js"></script>
</head>
<body>
<form>
Select a CD:
<select name="cds" onchange="showCD(this.value)">
<option value="Bob Dylan">Bob Dylan</option>
<option value="Bee Gees">Bee Gees</option>
61
Youth Dreams
61
<p>
<div id="txtHint"><b>CD info will be listed here.</b></div>
</p>
</body>
</html>
HTML form
cds
txtHint
div
div
web server
placeholder
user data
showCD
function
execute(run)
onchange event
function
run
showCD
function
XML file
code
cd_catalog.xml
save
ajaxxml.html
file
folder
<CATALOG>
<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
<CD>
<TITLE>Hide your heart</TITLE>
<ARTIST>Bonnie Tyler</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBS Records</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1988</YEAR>
</CD>
<CD>
<TITLE>Greatest Hits</TITLE>
<ARTIST>Dolly Parton</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>RCA</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1982</YEAR>
</CD>
<CD>
<TITLE>Still got the blues</TITLE>
<ARTIST>Gary Moore</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>Virgin records</COMPANY>
<PRICE>10.20</PRICE>
62
Youth Dreams
62
<YEAR>1990</YEAR>
</CD>
<CD>
<TITLE>Eros</TITLE>
<ARTIST>Eros Ramazzotti</ARTIST>
<COUNTRY>EU</COUNTRY>
<COMPANY>BMG</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1997</YEAR>
</CD>
<CD>
<TITLE>One night only</TITLE>
<ARTIST>Bee Gees</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>Polydor</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1998</YEAR>
</CD>
<CD>
<TITLE>Sylvias Mother</TITLE>
<ARTIST>Dr.Hook</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBS</COMPANY>
<PRICE>8.10</PRICE>
<YEAR>1973</YEAR>
</CD>
<CD>
<TITLE>Maggie May</TITLE>
<ARTIST>Rod Stewart</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>Pickwick</COMPANY>
<PRICE>8.50</PRICE>
<YEAR>1990</YEAR>
</CD>
<CD>
<TITLE>Romanza</TITLE>
<ARTIST>Andrea Bocelli</ARTIST>
<COUNTRY>EU</COUNTRY>
<COMPANY>Polydor</COMPANY>
<PRICE>10.80</PRICE>
<YEAR>1996</YEAR>
</CD>
<CD>
<TITLE>When a man loves a woman</TITLE>
<ARTIST>Percy Sledge</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Atlantic</COMPANY>
<PRICE>8.70</PRICE>
<YEAR>1987</YEAR>
</CD>
<CD>
<TITLE>Black angel</TITLE>
<ARTIST>Savage Rose</ARTIST>
63
Youth Dreams
63
<COUNTRY>EU</COUNTRY>
<COMPANY>Mega</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1995</YEAR>
</CD>
<CD>
<TITLE>1999 Grammy Nominees</TITLE>
<ARTIST>Many</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Grammy</COMPANY>
<PRICE>10.20</PRICE>
<YEAR>1999</YEAR>
</CD>
<CD>
<TITLE>For the good times</TITLE>
<ARTIST>Kenny Rogers</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>Mucik Master</COMPANY>
<PRICE>8.70</PRICE>
<YEAR>1995</YEAR>
</CD>
<CD>
<TITLE>Big Willie style</TITLE>
<ARTIST>Will Smith</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1997</YEAR>
</CD>
<CD>
<TITLE>Tupelo Honey</TITLE>
<ARTIST>Van Morrison</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>Polydor</COMPANY>
<PRICE>8.20</PRICE>
<YEAR>1971</YEAR>
</CD>
<CD>
<TITLE>Soulsville</TITLE>
<ARTIST>Jorn Hoel</ARTIST>
<COUNTRY>Norway</COUNTRY>
<COMPANY>WEA</COMPANY>
<PRICE>7.90</PRICE>
<YEAR>1996</YEAR>
</CD>
<CD>
<TITLE>The very best of</TITLE>
<ARTIST>Cat Stevens</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>Island</COMPANY>
<PRICE>8.90</PRICE>
<YEAR>1990</YEAR>
</CD>
64
Youth Dreams
64
<CD>
<TITLE>Stop</TITLE>
<ARTIST>Sam Brown</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>A and M</COMPANY>
<PRICE>8.90</PRICE>
<YEAR>1988</YEAR>
</CD>
<CD>
<TITLE>Bridge of Spies</TITLE>
<ARTIST>T'Pau</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>Siren</COMPANY>
<PRICE>7.90</PRICE>
<YEAR>1987</YEAR>
</CD>
<CD>
<TITLE>Private Dancer</TITLE>
<ARTIST>Tina Turner</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>Capitol</COMPANY>
<PRICE>8.90</PRICE>
<YEAR>1983</YEAR>
</CD>
<CD>
<TITLE>Midt om natten</TITLE>
<ARTIST>Kim Larsen</ARTIST>
<COUNTRY>EU</COUNTRY>
<COMPANY>Medley</COMPANY>
<PRICE>7.80</PRICE>
<YEAR>1983</YEAR>
</CD>
<CD>
<TITLE>Pavarotti Gala Concert</TITLE>
<ARTIST>Luciano Pavarotti</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>DECCA</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1991</YEAR>
</CD>
<CD>
<TITLE>The dock of the bay</TITLE>
<ARTIST>Otis Redding</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Atlantic</COMPANY>
<PRICE>7.90</PRICE>
<YEAR>1987</YEAR>
</CD>
<CD>
<TITLE>Picture book</TITLE>
<ARTIST>Simply Red</ARTIST>
<COUNTRY>EU</COUNTRY>
<COMPANY>Elektra</COMPANY>
<PRICE>7.20</PRICE>
65
Youth Dreams
65
<YEAR>1985</YEAR>
</CD>
<CD>
<TITLE>Red</TITLE>
<ARTIST>The Communards</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>London</COMPANY>
<PRICE>7.80</PRICE>
<YEAR>1987</YEAR>
</CD>
<CD>
<TITLE>Unchain my heart</TITLE>
<ARTIST>Joe Cocker</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>EMI</COMPANY>
<PRICE>8.20</PRICE>
<YEAR>1987</YEAR>
</CD>
</CATALOG>
code
selectcd.js
JavaScript code
var xmlHttp
function showCD(str)
{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")
return
}
var url="getcd.php"
url=url+"?q="+str
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("txtHint").innerHTML=xmlHttp.responseText
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
66
Youth Dreams
66
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
stateChanged()
GetXmlHttpObject
showCD()
function
drop
down
box
item
showHint()
JavaScript
XML
document
cd_catalog.xml
load
XML
DOM
PHP
XML file
query run
HTML
result
return
<?php
$q=$_GET["q"];
$xmlDoc = new DOMDocument();
$xmlDoc->load("cd_catalog.xml");
$x=$xmlDoc->getElementsByTagName('ARTIST');
for ($i=0; $i<=$x->length-1; $i++)
{
//Process only element nodes
if ($x->item($i)->nodeType==1)
{
if ($x->item($i)->childNodes->item(0)->nodeValue == $q)
{
$y=($x->item($i)->parentNode);
}
}
}
$cd=($y->childNodes);
for ($i=0;$i<$cd->length;$i++)
{
//Process only element nodes
if ($cd->item($i)->nodeType==1)
{
echo($cd->item($i)->nodeName);
echo(": ");
echo($cd->item($i)->childNodes->item(0)->nodeValue);
echo("<br />");
}
}
?>
67
Youth Dreams
67
query
1.
2.
JavaScript
match
loop
3.
artist
CD
4.
album
Output
txtHint placeholder
RSS Feeds
RSS
up to date
webpage
refresh
RSS
content
load
RSS
reader
HTML page
JavaScript
PHP
getrss.js
JavaScript
<html>
<head>
<script type="text/javascript" src="getrss.js"></script>
</head>
<body>
<form>
Select an RSS-Feed:
<select onchange="showRSS(this.value)">
<option value="Google">Google News</option>
<option value="MSNBC">MSNBC News</option>
</select>
</form>
<p><div id="rssOutput">
<b>RSS Feed will be listed here.</b></div></p>
</body>
</html>
HTML page
drop-down box
HTML form
68
Youth Dreams
68
event
showRSS()
function
rssOutput
<div>
showRSS() function return
data
placeholder
The JavaScript
code
getrss.js
JavaScript code
var xmlHttp
function showRSS(str)
{
xmlHttp=GetXmlHttp Object()
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")
return
}
var url="getrss.php"
url=url+"?q="+str
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("rssOutput")
.innerHTML=xmlHttp.responseText
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
JavaScript code
getrss.php
PHP file
..
server page
69
Youth Dreams
69
<?php
//get the q parameter from URL
$q=$_GET["q"];
//find out which feed was selected
if($q=="Google")
{
$xml=("http://news.google.com/news?ned=us&topic=h &output=rss");
}
elseif($q=="MSNBC")
{
$xml=("http://rss.msnbc.msn.com/id/3032091/device/rss/rss.xml");
}
$xmlDoc = new DOMDocument();
$xmlDoc->load($xml);
//get elements from "<channel>"
$channel=$xmlDoc->getElementsByTagName('channel')->item(0);
$channel_title = $channel->getElementsByTagName('title')
->item(0)->childNodes->item(0)->nodeValue;
$channel_link = $channel->getElementsByTagName('link')
->item(0)->childNodes->item(0)->nodeValue;
$channel_desc = $channel->getElementsByTagName('description')
->item(0)->childNodes->item(0)->nodeValue;
//output elements from "<channel>"
echo("<p><a href='" . $channel_link
. "'>" . $channel_title . "</a>");
echo("<br />");
echo($channel_desc . "</p>");
//get and output "<item>" elements
$x=$xmlDoc->getElementsByTagName('item');
for ($i=0; $i<=2; $i++)
{
$item_title=$x->item($i)->getElementsByTagName('title')
->item(0)->childNodes->item(0)->nodeValue;
$item_link=$x->item($i)->getElementsByTagName('link')
->item(0)->childNodes->item(0)->nodeValue;
$item_desc=$x->item($i)->getElementsByTagName('description')
->item(0)->childNodes->item(0)->nodeValue;
echo ("<p><a href='" . $item_link
. "'>" . $item_title . "</a>");
echo ("<br />");
echo ($item_desc . "</p>");
}
?>
JavaScript option
RSS feed
PHP
RSS feed
RSS channel
element
output
RSS items
loop
output
rssreader.html
run
70
Youth Dreams
70
result
Poll
HTML form
JavaScript
PHP page
Yes, No result
text file
HTML
HTML form
JavaScript
link
<html>
<head>
<script src="poll.js"></script>
</head>
<body>
<div id="poll">
<h2>Do you like PHP and AJAX so far?</h2>
<form>
Yes:
<input type="radio" name="vote"
value="0" onclick="getVote(this.value)">
<br />No:
<input type="radio" name="vote"
value="1" onclick="getVote(this.value)">
</form>
</div>
</body>
</html>
ajaxpoll.html
save
<div> tag
Yes
No
radio button
form
user yes
no
event
event
getVote()
function
execute
getVote() function
data
form
replace
poll_result.txt
save
poll
.. data
0||0
Yes votes
||
No votes
..
Yes
vote
01
The JavaScript
JavaScript code
poll.js
71
Youth Dreams
71
var xmlHttp
function getVote(int)
{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")
return
}
var url="poll_vote.php"
url=url+"?vote="+int
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("poll").
innerHTML=xmlHttp.responseText;
}
}
function GetXmlHttpObject()
{
var objXMLHttp=null
if (window.XMLHttpRequest)
{
objXMLHttp=new XMLHttpRequest()
}
else if (window.ActiveXObject)
{
objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
}
return objXMLHttp
}
Yes
No
HTML form
select
getVote() function
JavaScript
poll_vote.php
<?php
$vote = $_REQUEST['vote'];
//get content of textfile
$filename = "poll_result.txt";
$content = file($filename);
//put content in array
$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];
if ($vote == 0)
{
72
Youth Dreams
72
$yes = $yes + 1;
}
if ($vote == 1)
{
$no = $no + 1;
}
//insert votes to txt file
$insertvote = $yes."||".$no;
$fp = fopen($filename,"w");
fputs($fp,$insertvote);
fclose($fp);
?>
<h2>Result:</h2>
<table>
<tr>
<td>Yes:</td>
<td>
<img src="poll.gif"
width='<?php echo(100*round($yes/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($yes/($no+$yes),2)); ?>%
</td>
</tr>
<tr>
<td>No:</td>
<td>
<img src="poll.gif"
width='<?php echo(100*round($no/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($no/($no+$yes),2)); ?>%
</td>
</tr>
</table>
Yes (0) , No (1)
JavaScript
poll_result.txt file
content
contact
variable
variable
JavaScript
result
poll_result.txt
update
poll result
graphical representation
ajaxpoll.html
run
poll
Yes, No button
ajaxpoll.html
so
far
Yes
No
Yes
run
:P
73
Youth Dreams
73
PHP, MySQL
Apache
Package
XAMPP
root
username
password
..
Database
username
password
..MySQL
User
..
Creating a New User
Database
http://localhost/phpmyadmin/
. PHP My Admin
tool
Database
.. User
SQL Statement
PHP
Admin
Create
New
User
..
http://localhost/phpmyadmin/
Web Browser
Privileges
..
74
Youth Dreams
74
Privileges
..
user
75
Youth Dreams
75
Username
moemyintshein host
localhost
password
moemyintshein
Global privileges
Check All
..
Go
user
..
execute
SQL
Statement
Message
..
user
..
moemyintshein
localhost
SQL
statement
..
Server
user
SQL statement
username
moemyintshein1 password
moemyint12345
76
Youth Dreams
76
button
SQL
SQL query
execute
pop up page
..
Go
localhost
Server
moemyint12345
password
moemyintshein1
user
privileges
root
user
..
user
PHP MyAdmin
Table
Database
Home
Databases
menu
Database
mydomain
Collation
utf8_general_ci
mydomain
database
people
table
field
Go
77
Youth Dreams
77
Go
mydomain
database
people
table
table
save
PHP MyAdmin
78
Youth Dreams
78
save
Type
efficient
PHP MyAdmin
function
Drop
table
Primary Key
id fileld
auto_increment
record
Input
Default
save
screen
79
Youth Dreams
79
table
table
SQL command
PHP
Database
Table
Data
Insert
tab
80
Youth Dreams
80
Insert
field
setting
save
SQL code
window
Browse Tab
edit
Delete
back up
Database
database
mydomain
Tab
Export
81
Youth Dreams
81
people
export
backup
table
save
as
file
checked
zipped
GO
mydomain.sql
Zip
backup
Database
table
fileds
records
record
edit
back up
82
Youth Dreams
82
PHP
XAMPP
Install
..
PHP
XAMPP
PHP Myadmin
tool
PHP Database
PHP MySQL Introduction
What is MySQL?
MySQL
MySQL
database
MySQL
tables
database objects
table
column rows
Database
..
Database Tables
database
table
table
(Customers,
Orders). Table
rows
records
Persons
table
table
records (rows)
column(LastName, firstName,
Address
City)
Queries
query
query
column
83
Youth Dreams
83
database
data access
database
connection
PHP
mysql_connect() function
Syntax
mysql_connect(servername,username,password);
code
connection
($con)
variable
.. script
connection fail
die
<?php
$con=mysql_connect("localhost","user","password");
if (!$con)
{
die('Could not connect:' > mysql_error());
}
//some code
?>
PHP Script
connection
mysql_done()
fucntoin
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
mysql_close($con);
?>
PHP MySQL Create Database and Tables
Create a Database
MySQL
database
Syntax
PHP tutorial
database
..
SQL
SQL
84
Youth Dreams
84
execute
mysql_query() function
function
MySQL connection
query
command
my_db
database
<?php
$con = mysql_connect("localhost","user","moemyintshein");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
mysql_close($con);
?>
Table
MySQL
table
syntax
CREATE TABLE table_name
(
colomn_name1 data_type,
colomn_name2 data_type,
column_name3 data_type,
SQL
SQL Tutorial
PHP
mysql_query() function
execute
Persons
table
FirstName, LastName
Age
Colomn
<?php
$con = mysql_connect("localhost","root","moemyintshein");
if (!$con)
85
Youth Dreams
85
{
die('Could not connect: ' . mysql_error());
}
// Create database
if (mysql_query("CREATE DATABASE my_db1",$con))
{
echo "Database created";
}
else
{
- table
database
mysql_select_db()
function
database
varchar type
database field
filed
maximum length varchar(15)
data type
column
data
rows
primary key
primar y key
table
primary
key
null
database engine
record
personID
field
primary key
filed
ID number
AUTO_INCREMENT setting
AUTO_INCREMENT
record (column)
primary
86
Youth Dreams
86
key
field
primary key filed
null
field
NOT NULL
setting
table
column(record)
Syntax
INSERT INTO statement
data
column
column name
statement
execute
mysql_query()
function
function
MySQL connection
query
command
Persons
table
Firstname, Lastname
Age
Column
table
Persons
table
record
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
87
Youth Dreams
87
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Peter', 'Griffin', '35')");
mysql_query("INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Glenn', 'Quagmire', '33')");
mysql_close($con);
?>
Insert Data From a Form Into a Database
Persons table
record
HTML form
HTML form
<html>
<body>
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname" />
Lastname: <input type="text" name="lastname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
user
HTML form
Submit button
form
data
insert.php
insert.php
database
PHP $_POST variables
form
mysql_query() function
INSERT INTO
statement
Persons table
record
insert.php
code
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
88
Youth Dreams
88
database
data
select
Syntax
SELECT column_name(s)
FROM table_name
PHP
mysql_query() function
Persons table
data
character
table
data
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM Persons");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
mysql_close($con);
?>
mysql_query() return
data
$result
variable
array
recrodset
row
return
mysql_fetch_array () function
mysql_fetch_array()
recordset
row
return
while loop recordset
record
Looping
row
Screen
PHP
$row
variable
code
Output
89
Youth Dreams
89
Peter Griffin
Glenn Quagmire
Display the Result in an HTML Table
data
HTML tab;e
data
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM Persons");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
code
output
record
90
Youth Dreams
90
Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator value
Persons table
FirstName Peter
row
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM Persons
WHERE FirstName='Peter'");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
?>
output
Peter Griffin
recordset
data
ORDER BY keyword
default
ascending order
record
descending order
record
DESC keyword
Syntax
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC
91
Youth Dreams
91
Persons table
data
Age
column
result
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM Persons ORDER BY age");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
echo " " . $row['LastName'];
echo " " . $row['Age'];
echo "<br />";
}
mysql_close($con);
?>
code
output
Glenn Quagmire 33
Peter Griffin 35
order
by
column
Ordering
column
column
SELECT column_name(s)
FROM table_name
ORDER BY column1, column2
PHP MySQL Update
UPDATE statement
table
record
Update
Syntax
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
92
Youth Dreams
92
WHERE clause
UPDATE syntax
WHERE clause
record
WHERE
records
Update
Persons
Table
..
Persons table
data
update
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("UPDATE Persons SET Age = '36'
WHERE FirstName = 'Peter' AND LastName = 'Griffin'");
mysql_close($con);
?>
Update
Persons table
FROM
DELETE
Syntax
DELETE FROM table_name
WHERE some_column = some_value
WHERE clause
WHERE clause
record
WHERE
records
Delete
93
Youth Dreams
93
Persons table
code
LasteName Griffin
Persons table
record
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("DELETE FROM Persons WHERE LastName='Griffin'");
mysql_close($con);
?>
Delete
Data Source
Application
Programming Interface (API)
ODBC connection
database
MS Access Database
ODBC Connection
94
Youth Dreams
94
4.
5.
6.
7.
8.
configuration
website
Internet
Information Server
IIS
run
instruction
remote server
website
server
Physical access
web host
DNS
set up
Connecting to an ODBC
odbc_connect() function
function
parameter
data source
username
Password
SQL statement
execute
odbc_exec() function
northwind
DNS
connection
username
password
northwind
SQL
execute
$conn=odbc_connect('northwind','','');
$sql="SELECT * FROM customers";
$rs=odbc_exec($conn,$sql);
Retrieving Records
odbc_fetch_row()
result-set record
return
function rows
return
true
false
function
ODBC result identifier
parameter
odbc_fetch_row($rs)
Retrieving Fields from a Record
odbc_result() function record
fields
field number
name
parameter
.
code line
record
field
return
$compname=odbc_result($rs,1);
95
Youth Dreams
95
code line
CompanyName
field
return
$compname=odbc_result($rs,"CompanyName");
Closing an ODBC Connection
odbc_close() function
ODBC connection
odbc_close($conn);
ODBC
database connection
result set
HTML
table
data
<html>
<body>
<?php
$conn=odbc_connect('northwind','','');
if (!$conn)
{exit("Connection Failed: " . $conn);}
$sql="SELECT * FROM customers";
$rs=odbc_exec($conn,$sql);
if (!$rs)
{exit("Error in SQL");}
echo "<table><tr>";
echo "<th>Companyname</th>";
echo "<th>Contactname</th></tr>";
while (odbc_fetch_row($rs))
{
$compname=odbc_result($rs,"CompanyName");
$conname=odbc_result($rs,"ContactName");
echo "<tr><td>$compname</td>";
echo "<td>$conname</td></tr>";
}
odbc_close($conn);
echo "</table>";
?>
</body>
</html
96
Youth Dreams
96
Web Development
XML
XML
Extensible
Markup Language
XML
data
XML
HTML
XML
XML
Introduction to XML
XML
data
HTML
Data
XML HTML
markup language
XML tags
predefined
..
XML self-descriptive
XML
W3C
XML
HTML
XML HTML
XML data
..
HTML
data
HTML
XML
XML
XML
Jani Tove
note
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
self descriptive
XML
document
..
tags
Software
97
Youth Dreams
97
XML
plain text
Software
XML
XML
Application
XML tag
tags
application
XML
tag
<to>
<from>
XML standard
defined
tag
XML
document
XML language
predefined tags
HTML
HTML
tag
Predefined
HTML
documents
HTML
standard
tags
<p>
<h1>
XML
HTML
XML
software
hardware
XML
XML document
XML
self-describing
syntax
XML
XML version 1.0
encoding
(ISO-8859-1 = Latin-1/West European character set)
document
root element
document
note
<note>
to,from,heading
body
root
child elements
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
root element
98
Youth Dreams
98
</note>
XML document
Jani Tove
note
XML documents
root element
element
element
parent
XML
elements
document tree
root
branches
elements
<root>
<child>
<subchild>.....</subchild>
</child>
</root>
parent, child, sibling
elements
level
elements
HTML
text content
attributes
XML
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
99
Youth Dreams
99
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
<book> elements
<bookstore>
<book> element
<title> <author> <year>
<price>
elements
tag
HTML
elelement
<p>This is a paragraph
<p>This is another paragraph
XML
closing tag
tag
<p>This is a paragraph</p>
<p>This is another paragraph</p>
XML declaration
closing tag
..
declaration XML document
XML tags
Case Sensitive
XML
<letter> <Letter>
tag
case
<Message>This is incorrect</message>
<message>This is correct</message>
XML elements
nested
HTML
bold
italic
bold
italic
100
Youth Dreams
100
XML
XML
nested
<b>
XML elements
HTML
attributes
attribute value
XML
quote
<note date=12/11/2007>
<to>Tove</to>
<from>Jani</from>
</note>
<note date="12/11/2007">
<to>Tove</to>
<from>Jani</from>
</note>
Entity References
XML
less than < character
XML
element
error
XML parser
element
error
error
< character
entity reference
entity references
<
&
XML
illegal
entity reference
101
Youth Dreams
101
Comments in XML
XML
comment
syntax
HTML
XML elements
XML element
element
end
tag
element
elements
element
attributes
<bookstore>
<book category="CHILDREN">
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title>Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
<bookstore>
<book>
element contents
elements
<author>
text content
text
<book>
attribute
(category=CHILDREN)
XML Naming Rules
XML
letter, numbers
character
punctuation charcter
spaces
102
Youth Dreams
102
<note>
<to>Tove</to>
<from>Jani</from>
<body>Don't forget me this weekend!</body>
</note>
Output
XML document
<to>, <from>
<body> elements
application
..
MESSAGE
To:
Tove
From: Jani
Don't forget me this weekend!
<note>
<date>2008-01-10</date>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
application crash
break
No
application
element
output
XML
application
extend
XML Attributes
XML elements
HTML
start tag
attribute
Attribute
element
HTML
<img src=computer.gif>
src
attribute
<img> element
<img src="computer.gif">
<a href="demo.asp">
XML attribute
Quote
single quote double quote
sex
person
tag
103
Youth Dreams
103
<person sex="female">
<person sex='female'>
attribute
double quote
single quote
character entity
<person sex="female">
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>
<person>
<sex>female</sex>
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>
sex attribute
sex element
attribute
element
HTML
attribute
XML
element
attribute
My Favorite Way
XML documents
date attribute
<note date="10/01/2008">
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
date element
<note>
<date>10/01/2008</date>
104
Youth Dreams
104
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
date element
<note>
<date>
<day>10</day>
<month>01</month>
<year>2008</year>
</date>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
XML Attributes for Metadata
elements
ID references
messages>
<note id="501">
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<note id="502">
<to>Jani</to>
<from>Tove</from>
<heading>Re: Reminder</heading>
<body>I will not</body>
</note>
</messages>
identifier
notes
note
metadata
attributes
data
elements
XML Validation
syntax
xml document
well formed
syntax rule
-XML document
root element
-XML tags
case sensitive
105
Youth Dreams
105
-XML elements
nested
-XML attribute
quote
XML document
DOCTYPE
DTD file
DTD file
content
XML DTD
DTD
XML document
define
legal
elements
structure
<!DOCTYPE note [
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to
(#PCDATA)>
<!ELEMENT from
(#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body
(#PCDATA)>
]>
XML Schema
W3C DTD
XML Schema
support
<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to"
type="xs:string"/>
<xs:element name="from"
type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
106
Youth Dreams
106
<xs:element name="body"
</xs:sequence>
</xs:complexType>
type="xs:string"/>
</xs:element
XML Validator
XML document
error
XML application
error
XML document
processing
Program
XML
software
compatible
HTML
browsers
error
document
XML
error
XML
syntax
XML validator
browser
HTML page
XML files
CSS
107
Youth Dreams
107
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
<CD>
<TITLE>Hide your heart</TITLE>
<ARTIST>Bonnie Tyler</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBS Records</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1988</YEAR>
</CD>
.
.
.
.
</CATALOG>
CSS file
CATALOG
{
background-color: #ffffff;
width: 100%;
}
CD
{
display: block;
margin-bottom: 30pt;
margin-left: 0;
}
TITLE
{
color: #FF0000;
font-size: 20pt;
}
ARTIST
{
color: #0000FF;
font-size: 20pt;
}
COUNTRY,PRICE,YEAR,COMPANY
{
display: block;
color: #000000;
margin-left: 20pt;
}
CSS
format
CD catalog
108
Youth Dreams
108
XML
CSS
format
W3C
XSLT
recommend
XML document
HTML
XSLT XML
recommend
XSLT(eXtensible Stylessheet Language
Transformations) CSS
XSLT
browser
XML
HTML
XML file
109
Youth Dreams
109
<price>$7.95</price>
<description>
light Belgian waffles covered with strawberries and whipped cream
</description>
<calories>900</calories>
</food>
<food>
<name>Berry-Berry Belgian Waffles</name>
<price>$8.95</price>
<description>
light Belgian waffles covered with an assortment of fresh berries and whipped
cream
</description>
<calories>900</calories>
</food>
<food>
<name>French Toast</name>
<price>$4.50</price>
<description>
thick slices made from our homemade sourdough bread
</description>
<calories>600</calories>
</food>
<food>
<name>Homestyle Breakfast</name>
<price>$6.95</price>
<description>
two eggs, bacon or sausage, toast, and our ever-popular hash browns
110
Youth Dreams
110
</description>
<calories>950</calories>
</food>
</breakfast_menu>
XSLT Style Sheet
result
XML file
XML file
XSLT file
XML
PHP
XML
XML document
pricess
What is Expat?
XML document
XML parser
XML parsers
111
Youth Dreams
111
-Tree-based parser:
parser
XML document
tree structure
document
analyze
tree elements
access
Document
Object Model(DOM)
events
series
specific event
function
Expat parser
event-based parser
Structure
event-based parser
tree-based parses
data
access
<from>Jani</from>
event
series
XML
event-based parser
-Start Element:From
-Start CDATA section,
Jani
-Close element: from
XML well-formed XML
valid XML
DTD
Expat parser
Expat
DTDs
non-validating
parser
event based
Expat
PHP web applications
XML document
well-formed
Expat error
Installation
XML Expat parser function
PHP core
function
install
XML file
112
Youth Dreams
112
XML events
handlers
XML file
parse
<?php
//Initialize the XML parser
$parser=xml_parser_create();
//Function to use at the start of an element
function start($parser,$element_name,$element_attrs)
{
switch($element_name)
{
case "NOTE":
echo "-- Note --<br />";
break;
case "TO":
echo "To: ";
break;
case "FROM":
echo "From: ";
break;
case "HEADING":
echo "Heading: ";
break;
case "BODY":
echo "Message: ";
}
}
//Function to use at the end of an element
function stop($parser,$element_name)
{
echo "<br />";
}
//Function to use when finding character data
function char($parser,$data)
{
echo $data;
}
//Specify element handler
xml_set_element_handler($parser,"start","stop");
//Specify data handler
xml_set_character_data_handler($parser,"char");
//Open XML file
$fp=fopen("test.xml","r");
//Read data
while ($data=fread($fp,4096))
{
xml_parse($parser,$data,feof($fp)) or
die (sprintf("XML Error: %s at line %d",
xml_error_string(xml_get_error_code($parser)),
xml_get_current_line_number($parser)));
}
//Free the XML parser
xml_parser_free($parser);
113
Youth Dreams
113
?>
code
output
1.
XML parser
xml_parser_create() function
2.
event handlers
function
3.
parser opening
closing tag
function
4.
xml_set_handler() function
function
xml_set_character_data_handler()
5.
text.xml
parse
xml_parse () function
6.
error
xml_error_string()
function
XML
error
7.
xml_parser_create() function
memory allocate
xml_parser_free() function
DOM parser
PHP
XML documents
Process
What is DOM?
XML DOM(Document Object Model) XML documents
access
standard
DOM XML document
tree structure
element
attribute
nodes
114
Youth Dreams
114
XML
XML DOM
DOM
DOM
W3C (World Wide
DOM XML
HTML
document
access
DOM
-Core DOM-
document
model
-XML DOM- XML documents
model
-HTML DOM HTML documents
model
object
properties
access
methods (interface)
HTML DOM
XML DOM
XML DOM
-XML
-XML
-Platform
Language
-W3C
115
Youth Dreams
115
XML DOM
XML elements
XML document
node
DOM
-document
document node
-XML element
element node
-XML elements
text
text node
- attribute
attribute node
-Comments
comment nodes
DOM Example
<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
116
Youth Dreams
116
nodes
<bookstore>
<book> nodes
<book> node
<title>, <author>,
<year>
<price>
nodes
..
text node
DOM processing
error
element node
element node
text node
<year>2005</year>
<year>
text node
2005
<year>
element
node- tree
tree
nodes
nodes
tree
access
content
element
node tree nodes
tree root node
tree
text node
books.xml
117
Youth Dreams
117
118
Youth Dreams
118
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
Node Parents, Children, and Siblings
node tree
nodes
parent, child , subling
parent node
children
level
children
siblings
-node tree
node
root
-
root
node
parent node
- node
- leaf
node
-sibling
nodes
node tree
nodes
119
Youth Dreams
119
XML
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
</bookstore>
<title> element <book> element
<price> element
<book>
element
parent node
PHP
XML
document
XML parser
XML parser
tree-based
event-based
XML
XML
tree structure
function
install
XML file
120
Youth Dreams
120
XML parser
xml
load
output
PHP code
<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("note.xml");
print $xmlDoc->saveXML();
?>
code
Output
browser window
view source
HTML
note.xml XML
load
saveXML() function
XML document
string
XML parser
XML
load
<note> element
element
looping
<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("note.xml");
$x = $xmlDoc->documentElement;
foreach ($x->childNodes AS $item)
{
print $item->nodeName . " = " . $item->nodeValue . "<br />";
}
?>
code
output
#text =
to = Tove
#text =
from = Jani
#text =
heading = Reminder
#text =
body = Don't forget me this weekend!
121
Youth Dreams
121
#text =
element
text nodes
XML generate
nodes
white-space
XML DOM parser
element
PHP SimpleXML
SimpleXML PHP5
XML document
layout
element
attribute
text
DOM
Expat parser
SimpleXML element
text data
code
SimpleXML
XML document
object
Elements-
SimpleXMLElement object
attribute
level
element
array
Attributes
associative array
access
index
attribute name
strings
element
text
node
order
SimpleXML
-XML file
read
-XML string
data
extract
-text nodes
attribute
advanced XML
Expat parser
XML DOM
PHP 5.0
SimpleXML functions
PHP core
function
install
Using SimpleXML
XML file
122
Youth Dreams
122
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
file
element
data
Output
1.
XML file
Load
2.
element
3.
child node
children()function
loop
4.
child node
element
data
<?php
$xml = simplexml_load_file("test.xml");
echo $xml->getName() . "<br />";
foreach($xml->children() as $child)
{
echo $child->getName() . ": " . $child . "<br />";
}
?>
code
run
Output
note
to: Tove
from: Jani
heading: Reminder
body: Don't forget me this weekend!
123
Youth Dreams
123
PHP 5
error
Object Oriented
Exceptiong handling
error
code
execute
flow
exception
exception
code
(save)
handler save
code
run
resume
script execution
code
script
run
- Exception
error
code
code
execute
PHP catch
block
exception
caught
Uncaught Exception
error
catch
exception
<?php
//create function with an exception
function checkNum($number)
{
if($number>1 )
{
throw new Exception("Value must be 1 or below");
}
return true;
}
124
Youth Dreams
124
//trigger exception
checkNum(2);
?>
error
Fatal
error:
Uncaught
exception
'Exception'
with
message
'Value
must
be
or
below'
in
error
exception
code
code
1.Try- exception
function try block
exception
code
run
exception
exception
thrown
2.Throw-
exception
throw
catch
exception
exception information
object
valid code
exception
<?php
//create function with an exception
function checkNum($number)
{
if($number>1)
{
throw new Exception("Value must be 1 or below");
}
return true;
}
//trigger exception in a "try" block
try
{
checkNum(2);
//If the exception is thrown, this text will not be shown
echo 'If you see this, the number is 1 or below';
}
//catch exception
catch(Exception $e)
125
Youth Dreams
125
{
echo 'Message: ' .$e->getMessage();
}
?>
code
error
output
exception
throw
catch
1.
checkNum() function
exception
2.
try block
checkNum() function
4.
($e) object
object
exception
3.
5.
checkNum() function
exception
(thrown)
information
exception
error message
$e->getMessage()
exception object
echo
PHP
exception
function
class
class
exception
class
extension
custom function
exception class
<?php
class customException extends Exception
{
public function errorMessage()
{
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}
}
$email = "someone@example...com";
try
{
//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
{
//throw exception if email is not valid
throw new customException($email);
126
Youth Dreams
126
}
}
catch (customException $e)
{
//display custom message
echo $e->errorMessage();
}
?>
class
old exception class
errorMessage()
function
old class
copy
properties
method
old class
getLine(), getFile()
getMessage()
exception
1.
2.
customException() class
properties
errorMessage()
email address invalid
function error
message
3.
$email variable
valid
4.
try block
execute
email
valid
exception
thrown
5.
error message
Multiple Exceptions
exception
script
if else block switch
nested multiple exception
exception
exception class
error message
<?php
class customException extends Exception
{
public function errorMessage()
{
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}
}
$email = "someone@example.com";
try
{
127
Youth Dreams
127
//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
{
//throw exception if email is not valid
throw new customException($email);
}
//check for "example" in mail address
if(strpos($email, "example") !== FALSE)
{
throw new Exception("$email is an example e-mail");
}
}
catch (customException $e)
{
echo $e->errorMessage();
}
catch(Exception $e)
{
echo $e->getMessage();
}
?>
run
code
1.
2.
customException() class
properties
errorMessage()
email address invalid
3.
$email variable
valid
example
string
4.
try block
execute
exception
5.
example
exception
6.
catch
exception
error message
Re-throwing Exceptions
exception
thrown
catch block
exception
throw
script
user
system error
System error
coder
user
user
exception
re-throw
<?php
class customException extends Exception
{
128
Youth Dreams
128
1.
customException() class
properties
2.
3.
errorMessage()
email address invalid
$email variable
valid
example
string
4.
try block
exception
re-throw
try block
5.
email
example
string
exception
6.
customException
re-throws
7.
customException
error message
exception
user-defined
function
set
129
Youth Dreams
129
<?php
function myException($exception)
{
echo "<b>Exception:</b> " , $exception->getMessage();
}
set_exception_handler('myException');
throw new Exception('Uncaught Exception occurred');
?>
output
code
catch block
top level exception handler
function
uncaught
exception
Exception
1.
Code
try block
2.
try block
throw
catch block
3.
exception class
catch block
4.
try block
catch block
exception
5.
( throw)
(catch)
PHP Filter
PHP Filter
?
PHP filter
user
input
valid
filter
user imputer
validate
filter
web application
PHP filter
filter(
Filter
?
web application
Input
user
web service
application
filter
..
application
input
130
Youth Dreams
130
data
filter
input filtering application
security
external data
form
Input data
Cookies
Web services
data
server variable
filter
filter function
filter_var()-
filter
variable
filter
filter_var_array()-
filter
variable
filter
filter
filter_input_array-
input variable
filter
filter
filter_var() function
integer
valid
<?php
$int = 123;
if(!filter_var($int, FILTER_VALIDATE_INT))
{
echo("Integer is not valid");
}
else
{
echo("Integer is valid");
}
?>
code variable
filter
FILTER_VALIDATE_INT filter
Integer valid
output
Interger is valid.
integer
variable 123abc
131
Youth Dreams
131
filter
Validating filters
Sanitizing filters
Validating filters
user input
validate
format rule
( URL
EMAIL)
validate
FALSE
Sanitizing filters
string
character
String
return
flags
filters
filter options
filter
Options
flags
filter_var() function
min_range
max_range option
integer
validate
<?php
$var=300;
$int_options = array(
"options"=>array
(
"min_range"=>0,
"max_range"=>256
)
);
if(!filter_var($var, FILTER_VALIDATE_INT, $int_options))
{
echo("Integer is not valid");
}
else
{
echo("Integer is valid");
}
?>
code
options
option
associative array
flag
array
integer 300
range
code
run
Integer is not valid
Validate Input
form
input form
validate
132
Youth Dreams
132
input data
filter_input ()
function
input data
filter
PHP page
<?php
if(!filter_has_var(INPUT_GET, "email"))
{
echo("Input type does not exist");
}
else
{
if (!filter_input(INPUT_GET, "email", FILTER_VALIDATE_EMAIL))
{
echo "E-Mail is not valid";
}
else
{
echo "E-Mail is valid";
}
}
?>
input
(URL)
POST Method
1.
POST type
url input
2.
sanitize(valid
character)
$url variable
sanitizing
http://www.moemyintshein.com
input fileld
filter_var
filter_input function
filter_var_array
filter_input_array
function
GET variable
filter
filter_input_array() function
GET variable
<?php
$filters = array
(
"name" => array
(
133
Youth Dreams
133
"filter"=>FILTER_SANITIZE_STRING
),
"age" => array
(
"filter"=>FILTER_VALIDATE_INT,
"options"=>array
(
"min_range"=>1,
"max_range"=>120
)
),
"email"=> FILTER_VALIDATE_EMAIL,
);
$result = filter_input_array(INPUT_GET, $filters);
if (!$result["age"])
{
echo("Age must be a number between 1 and 120.<br />");
}
elseif(!$result["email"])
{
echo("E-Mail is not valid.<br />");
}
else
{
echo("User input is valid");
}
?>
(name,age,email)
Input
GET method
1.
input variable
array
input variables
filter
2.
filter_input_array() function
array
3.
valid input
$result variable
input
invalid
filter_input_array() function
filter_input_array() function
parameter array
single filter ID
input array
filter
filter
parameter array
134
) array key
input variable
associative array
array
filter ID
filter, flag
option
array
Youth Dreams
134
FILTER_CALLBACK filter
filter
data filtering
PHP function
whitespaces
<?php
function convertSpace($string)
{
return str_replace("_", " ", $string);
}
$string = "Peter_is_a_great_guy!";
echo filter_var($string, FILTER_CALLBACK,
array("options"=>"convertSpace"));
?>
output
1.
whitespaces
fuction
2.
FILTER_CALLBACK filter
function
array
filter_var() function
135
Youth Dreams
135
Conclusion
English
PHP
136
Youth Dreams
136