Programming The Web Notes
Programming The Web Notes
ObjecAve:
Course outline
Provide the necessary knowledge for developing and administraAng the applicaAons running on World Wide Web.
Background Servers and protocols Web hosAng Client/Server programming Data exchange The Document Model Style Elements, Hyperlinking, and InteracAvity HTML5 XML and XHTML Tags and Styles Style Sheets ProperAes CSS Objects
1/27/13
Web Databases
Textbook:
AJAX RSS Social Networking Programming the World Wide Web 6th ediAon by Robert W. Sebesta
Exams
First
Exam:
24/02/2013,
Time:
4:00-5:00
Second
Exam:
31/03/2013,
Time:
4:00-5:00
Project
Deadline:
21/04/2013
1/27/13
ObjecAves
Provide
a
comprehensive
introducAon
to
the
programming
tools
and
skills
required
to
build
and
maintain
server
sites
on
the
web.
Learn
how
to
program
using
XHTML,
HTML5,
CSS,
JavaScript,
PHP,
MySQL.
Introduce
some
Web
2.0
features
Explore
some
content
management
systems.
Note
The
area
of
web
programming
is
very
wide
Many
books
can
be
found
explaining
just
one
web
programming
language
or
a
tool
Textbook:
Programming
the
world
wide
web,
sixth
ediAon,
by
Robert
W.
Sebesta
Tools
Use
Open
Source
tools
e.g.
Eclipse
1/27/13
The
internet
Originated
in
the
1960s.
Developed
by
the
DoD
A
collecAon
of
computers
connected
together
in
a
big
network.
Using
routers,
switches,
hubs,
and
many
dierent
servers
and
protocols.
A
known
widely
used
protocol
is
the
TCP/IP
protocol.
Robust: provides a delivery mechanism in which a piece of informaAon can take mulAple routes from one point to another. InformaAon are:
Client/Server topology
Requests for informaAon or service Responses containing that informaAon or the result of a service InformaAonal responses (control messages), that is, reasons why the service or informaAon could not be delivered
Wrieen as four 8-bit numbers, separated by periods. A trend to use a new standard, IPv6, (128-bit) Not user friendly.
1/27/13
Domain
Names
To
access
some
informaAon
on
one
computer
(the
host
machine)
on
the
internet,
you
need
its
address.
People
are
not
good
remembering
numbers.
Map
numeric
addresses
to
names
Names
begins
with
the
host
machine
that
are
followed
by
the
enclosing
collecAon
of
machines
are
called
domains.
edu,
com,
gov,
ps,
jo,
de
Ex:
eng.najah.edu
World Wide Web (www) or Web: originally to allow scienAsts to exchange documents.
Allow
a
user
anywhere
to
search
for
and
retrieve
documents
from
databases
on
any
number
of
dierent
document-serving
computers
on
the
internet.
All
document
have
been
formed
using
hypertext.
A
text
containing
links
to
other
documents.
This
developed
to
include
hypermedia
(pictures,
sound,
and
video)
1/27/13
Web
browsers
Two
computers
communicaAng
as
Client/ Server.
(request/response)
Document
provided
by
web
servers
are
requested
by
clients
browsers.
Although
many
protocols
are
supported
by
the
web,
the
most
common
one
is
the
Hypertext
Transfer
Protocol
(HTTP).
Most
common
browsers
are:
IE,
Firefox,
Safari,
Web
Servers
Handel
client
requests
Each
document
on
the
server
has
a
URL.
All
the
communicaAon
between
a
Web
server
and
a
web
browser
is
done
based
on
a
standard
web
protocol.
When
a
web
server
runs,
it
informs
the
operaAng
system
that
it
is
ready
for
any
network
request.
All
network
requests
that
meets
the
server
communicaAon
protocol
are
send
the
the
server.
The
web
server
runs
in
the
background
A
web
browser
opens
a
network
connecAon
to
a
web
server.
All
HTTP
commands
include
a
URL.
Indicates
the
specicaAons
of
the
host
server
machine
1/27/13
If a web server provides a document that is residing on a dierent computer, it is called a proxy server. Many web servers are now supporAng other protocols than the HTTP such as gp, gopher, news, and mailto.
In addiAon nearly all web servers supports interacAng with database systems through Common Gateway Interface (CGI) programs and server-side scripts.
hep,
gp,
gopher,
telnet,
le,
mailto,
and
news
hep:
used
to
request
and
send
eXtensible
Hypertext
Markup
Language
(XHTML)
documents.
URL
object-address:
//fully-qualied-domain-name/path-to-document
A
domain
name
has
to
include
a
port
number
For
Hep
the
default
is
80,
no
need
to
be
included
unless
it
is
something
else.
le:
using
the
le
protocol
to
reference
documents
residing
on
the
same
computer
the
requester
browser
resides
on.
le://path-to-document
1/27/13
URL
cont.
No
spaces
allowed
Also
semicolons,
colons,
and
ampersands(&).
To
include
such
disallowed
characters,
they
must
be
encoded
as
a
percent
sign
(%)
followed
by
its
ASCII
hexadecimal
code.
1/27/13
General: for general informaAon such as date Request: Included in request headers
Response: for response headers EnAty: Used in both request and response headers
One common request eld is the accept eld which specify a preference of the browser for the MIME type of the requested document e.g. Accept: text/plain or Accept: text/* for any.
1/27/13
Message
body
Not
all
requests
has
message
body,
for
example
requests
that
use
the
GET,
HEAD,
and
DELETE
methods
do
not
have
bodies.
10
1/27/13
Security
Consider
sending
a
credit
card
number
to
a
company,
the
security
issues
for
this
transacAon
are
Privacy:
it
must
not
be
possible
for
the
credit
card
number
to
be
stolen
on
its
way
to
the
companys
server
Integrity:
it
must
not
be
possible
for
the
credit
card
number
to
be
modied
on
its
way
to
the
companys
server
AuthenAcaAon:
it
must
be
possible
for
both
the
purchaser
and
the
seller
to
be
certain
of
each
others
iden)ty.
NonrepudiaAon:
it
must
be
possible
to
prove
legally
that
the
message
was
actually
sent
and
received.
Public-key
encrypAon
e.g.
RSA
Using encrypAon
XHTML
HTML
is
dened
with
the
use
of
the
Standard
Generalized
Markup
Language
(SGML)
All
web
standards
are
managed
by
the
World
Wide
Web
ConsorAum
(W3C)
HTML
is
the
language
of
the
World
Wide
Web
XHTML
is
a
formal
redeniAon
of
HTML
under
XML.
W3.org
This
makes
the
HTML
code
easier
to
validate,
as
it
adheres
more
closely
to
the
XML
standard
for
data
exchange.
The
basic
unit
of
deniAon
used
in
XML
and
HTML
is
the
tag
<tag_name>Content
inside
tag</tag_name>
11
1/27/13
The strict doctype <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 strict//EN "hep://www.w3.org/TR/html4/strict.dtd">
The HEAD: informaAon to the browser The BODY: all the content that is designed to be rendered In HTML5, the deniAon secAon and the head secAon are mandatory.
12
1/27/13
The
TITLE
tag
species
what
is
displayed
in
the
Atle
bar
of
the
browser
<TITLE>My
Title</TITLE>
13
1/27/13
Hyperlinking
The
ability
of
linking
content
together
This
can
be
a
page,
an
image,
a
video,
a
sound,
or
a
zip
le
containing
a
sogware
release
14
1/27/13
Anything
in
the
document
that
is
between
chevrons
(<
and
>)
is
considered
to
be
an
HTML
tag
The
robust
parsing
of
most
browsers
will
just
ignore
tags
that
are
invalid
or
improperly
formed.
Comments
Between
<!--
and
-->
Minimized
Tags
A
minimized
tag
is
one
where
there
is
no
start
and
end
tag,
just
a
single
instance
of
the
tag
<tag>
or
<tag/>
the
second
variaAon
is
the
one
preferred
by
the
XHTML
standard
NesAng
means
including
tags
inside
other
tags
Overlapping
means
extending
the
inner
tag
past
the
outer
tag
Many
tags
can
be
nested,
provided
that
the
sense
of
the
document
is
retained
<tag_one>Content
<tag_two>Other
Content</ tag_one>
More
Content</tag_two>
<tag_one>Content
<tag_two>Other
Content</ tag_two>
More
Content</tag_one>
one can specify italic text inside bold text in order to have bold, italic text one can also nest containers such as tables inside other containers (inside cells of tables, in the case of tables)
15
1/27/13
The
rst
three
tags
are
the
easiest.
They
typically
have
no
aeributes,
and
are
used
on
their
own,
or
nested,
in
order
to
render
specic
eects
The
bold
text
tag
is
<B>
This
will
be
<B>in
bold</B>
Text Formapng
You
can
use
the
FONT
tag.
However
it
has
been
deprecated
by
the
addiAon
of
style
sheets.
aeributes
that
allow
you
to
specify
the
font
by
the
FACE
aeribute,
color,
and
size
of
the
text
that
you
want
to
be
displayed.
<HTML> <HEAD> <TITLE>Bold, Italics and Underlined</TITLE> </HEAD> <BODY> This is <B>bold text</B>.<BR /><BR /> This is <I>italicized text</I>.<BR /><BR /> This is <U>underlined text</U>.<BR /><BR /> This is <B>bold +<I>italicized +<U>underlined</ U></I></B>. </BODY> </HTML>
16
1/27/13
<HTML>
<HEAD>
<TITLE>Times,
Courier
and
Verdana
Text</TITLE>
</HEAD>
<BODY>
<FONT
FACE="Courier
SIZE=6>This
is
Courier
text</FONT><BR
/><BR
/>
<FONT
FACE="Times
Color=#808080>This
is
Times
text</FONT><BR
/><BR
/>
<FONT
FACE="Verdana
Color=Red>This
is
Verdana
text</FONT><BR
/><BR
/>
</BODY>
</HTML>
The
standard
HTML
colors
are:
Black,
Silver,
Gray,
White,
Maroon,
Purple,
Fuchsia,
Red,
Yellow,
Olive,
Green,
Lime,
Navy,
Teal,
Blue,
Aqua
One
can
specify
colors
using
RGB
hex
value
You
can
use
a
tool
called
the
Color
Schemer,
available
at
hep://www.colorschemer.com/online.html
Font Example
Pre formapng tag <PRE> <PRE> This text is preformaeed. </PRE> Emphasizing tags <EM> and <STRONG>
On most browsers this is same as italic On most browsers this is the same as bold
17
1/27/13
Flow
Formapng
Anything
that
changes
the
ow
of
the
content
around
the
page,
as
well
as
(opAonally)
specic
color
and
style
informaAon
The
heading
tag,
heading
1
as
the
most
important,
and
6
as
the
least
<h1>Heading
1</h1>
<h2>Heading
2</h2>
<h3>Heading
3</h3>
<h4>Heading
4</h4>
<h5>Heading
5</h5>
<h6>Heading
6</h6>
This
is
normal
text.
Heading
can
take
several
tags
such
as
ALINE
<h1
align="RIGHT">Right
Aligned
Heading</h1>
18
1/27/13
<body>
<h1
align="LEFT">Heading</h1>
<p>This
is
a
paragraph
of
text.</p>
This
is
not
inside
a
paragraph.
<p>This
is
another
paragraph.</p>
</body>
The
ALIGN
aeribute
with
the
paragraph
tag.
<div
align="CENTER">
<p>This
is
centered.</p>
</div>
<p>This
is
not.</p>
or
to
use
three
control
tags:
This
is
deprecated
You
can
use
the
DIV
align
aeribute
Paragraph <P>
<CENTER> <RIGHT> <LEFT> However, only the CENTER tag is supported in the HTML standard and is part of the TransiAonal deniAon. In other words, under strict HTML 4.01, it should not be used.
Ordered
list:
numbered
items
(nominally
1,
2,
3,
and
so
on,
but
can
be
changed)
Enclosing
it
in
<ol>
and
</ol>
tags
Each
item
must
begin
with
an
<li>
tag;
however,
a
closing
tag
is
not
required.
The
TYPE
aeribute
can
be
used
to
change
the
numbering
scheme
used,
however
it
is
deprecated.
i
for
roman
numerals
(i,
ii,
iii,
iv,
and
so
on)
a
for
lowercase
leeers
(a,
b,
c,
d,
and
so
on).
<OL
start=5>
lists of items
To start indexing other than the default use the aeribute start
<ol TYPE=i"> <li>This is the rst item</li> <ol TYPE="a"> <li>This is sub-item one</li> <li>This is sub-item two</li> <li>etc. </li> </ol> </ol>
19
1/27/13
There
is
simply
a
bullet
or
other
illustraAve
element
in
front
of
the
item
rather
than
a
number
<ul>
<li>This
is
the
rst
item</li>
<ul>
<li>This
is
sub-item
one</li>
<li>This
is
sub-item
two</li>
<li>etc.
</li>
</ul>
</ul>
The
TYPE
aeribute
is
used
to
change
the
ordering
style
for
the
ordered
list
Three
allowable
values
DISC,
SQUARE,
and
CIRCLE
<UL>
Types
<ul
type="DISC">
<li>This
is
the
rst
item
<ul
type="SQUARE">
<li>This
is
sub-item
one</li>
<li>This
is
sub-item
two</li>
<li
type="CIRCLE">This
is
a
dierent
sub-item
bullet!
</li>
</ul>
</ul>
20
1/27/13
DeniAon
list
A
deniAon
list
is
just
a
structured
list
that
contains
items
and
their
deniAons.
The
deniAon
block
is
usually
slightly
indented
from
the
item
to
which
it
refers,
and
when
the
line
wraps,
the
indent
is
kept.
You
cannot
change
the
aspect
of
it
using
the
TYPE
aeribute.
Instead,
styles
must
be
used
to
change
the
rendering.
<dl>
<dt>First
item</dt>
<dd>First
deni)on</dd>
<dt>Second
item</dt>
<dd>Second
deni)on,
rst
part</dd>
<dd>Second
deni)on,
second
part</dd>
</dl>
21
1/27/13
Tables cont.
Ex: A table that has three columns, two of 25% and one of 50%, you would use HTML such as: <table WIDTH="100%"> <tr> <td WIDTH="25%"> </td> </tr> <tr> <td WIDTH="50%"> </td> </tr> <tr> <td WIDTH="25%"> </td> </tr> </table> Note: if you want to center the table, you can enclose it in <CENTER> and </CENTER> tags.
value for the WIDTH aeribute can be presented as a percentage of the available block or as a discrete value, in pixels.
Homework
Use
the
<table>
tage
to
to
generate
the
webpage
shown
here.
Note
that
you
may
need
to
use
aeributes
like
COLSPAN,
WIDTH,
and
VALIGN,
also
other
tags
like
<H1>,
<BR/>,
22
1/27/13
More
on
Tables
BGCOLOR
aeribute
is
used
to
set
the
background
of
the
table
or
a
parAcular
cell
inside
the
table.
deprecated
The
CELLSPACING
and
CELLPADDING
aeributes
are
used
in
the
<TABLE>
tag
to
set
the
space
between
cells
(spacing)
and
the
inside
margins
(padding).
The
<TH>
tag
allows
you
to
specify
that
a
cell
contains
heading
informaAon
<table>
<tr>
<th>Col
1</th>
<th>Col
2</th>
<th>Col
3</th>
</tr>
<tr>
<td>Cell
1</td>
<td>Cell
2</td>
<td>Cell
3</td>
</tr>
</table>
The
generic
form
for
an
external
link
(which
will
be
in
the
index
page,
linking
to
other
pages)
is
as
follows:
<A>
is
the
anchor
tag
On
the
same
page
On
the
same
server
On
dierent
server
<A
HREF="#internal_ref_name>Link
Text</A>
<A
HREF="target_page.html">Link
Text</A>
<A
HREF="hZp://www.mycom.com/target_folder/ target_page.html">Link
Text</A>
<A
HREF="hZp://www.mycom.com/target_folder/target_page.html
#internal_ref_name">
Link
Text</A>
Document Linking
Links can be text, images, or mulAmedia. Text links typically appear as underlined, dierently colored words on a page. Any image on a web page can be turned into a link. You can place <a> tags around video and audio content to make them links.
23
1/27/13
24
1/27/13
You
must
assign
names
to
the
areas
to
which
you
want
to
link
You
can
do
this
with
the
id
aeribute.
25
1/27/13
26
1/27/13
27
1/27/13
28
1/27/13
Input elements such as text elds, menus, and check boxes collect data from a website user. Web page forms have three important parts: a <form> tag, form input elements, and a Submit bueon. All forms should include a Submit bueon for sending the data to a web server for processing. Aper the form data is processed, a script typically sends a conrma)on page back to the browser window noAng whether or not the form data was sent successfully.
Forms
The <INPUT> tag is used to specify the elements that are to be used to allow the users to enter data
29
1/27/13
Text Boxes
Control Types
New in HTML5, some text boxes can hold a specic type of text content such as an e-mail address or a URL.
File Upload Range Slider is new in HTML5 Date and Time Fields
New in HTML5, you can dene menus that hold )me and date informaAon such as months, weeks, and days.
HTML5 introduces several new eld types for presenAng chronological informaAon such as month, week, and Ame elds.
Textbox
30
1/27/13
Password
text
boxes
are
similar
to
regular
text
boxes
with
one
dierence.
Rather
than
displaying
the
characters
that
are
typed,
the
input
eld
displays
the
data
as
asterisks
(*)
or
bullets
().
This
prevents
others
from
seeing
the
password
text.
To
create
a
text
box
for
password
entry,
you
specify
the
password
type
in
the
<input>
tag.
For
example:
To
create
a
text
eld
that
accepts
only
numbers
<input
type=password
name=textboxName
size=45>
<input
type=number
name=age
value=21
min=1
max=120
step=0.5>
<input
type=hidden
name=specialcode
value=abc123>
You can dene a form input eld of type hidden. For example:
Text
area
size
is
measured
in
rows
and
columns,
with
the
measurement
based
on
the
number
of
characters
that
can
be
displayed.
Wrap
aZribute.
Use
sog
to
wrap
text
within
the
text
area
but
does
not
wrap
text
in
the
form
results
(text
come
ager
data
processing).
Use
hard
to
wraps
text
within
both
the
text
area
and
the
form
results.
Use
o
to
turn
o
text
wrapping,
forcing
users
to
create
new
lines
of
text
as
they
type.
If
the
user
types
more
text
than
is
visible
in
the
text
area,
scroll
bars
appear
at
the
side
of
the
text
box
You
can
use
the
readonly
aeribute
if
you
want
to
display
default
text
in
a
text
area
and
do
not
want
users
to
move
or
edit
the
text.
This
aeribute
does
not
require
a
value.
31
1/27/13
Note: The check box value does not appear on the form, it is used as the value to be assigned if the check box is checked. To automaAcally show the check box as selected use the checked aeribute <input type=checkbox Name=newsleeer Value=yes checked>
32
1/27/13
When radio bueons have dierent name aeributes, the browser treats them as parts of dierent radio bueon sets. You can use the checked aeribute to show one radio bueon in the group as selected by default.
33
1/27/13
If
the
value
of
the
size
aeribute
is
greater
than
1
the
view
will
be
a
list
(rectangular
box)
with
scroll
bars.
To
create
a
submenu,
use
the
<optgroup>
tag
and
the
label
aeribute
(note
that
not
all
browsers
support
the
<optgroup>
tag)
<p>What
is
your
favorite
sport?</p>
<select
name=favoritesport>
<optgroup
label=Summer>
<opAon
value=Diving>Diving
<opAon
value=Biking>Biking
</optgroup>
<optgroup
label=Winter>
<opAon
value=Skiing>Skiing
<opAon
value=Ice
Climbing>Ice
Climbing
</optgroup>
</select>
Combo/list
34
1/27/13
To prevent a text box autocompleAng from happening, you can set the autocomplete aeribute to o. For example: To add a URL text
<input type=text name=ssn autocomplete=o> <input type=url name=emailaddress size=25 maxlength=200> checks if the text includes :// with alphabeAcal text before and alphanumeric text or a period ager.
35
1/27/13
36
1/27/13
37
1/27/13
The submit bueon allows users to send the data they enter into the form. The reset bueon allows users to clear the data they have entered.
38
1/27/13
You can mark elds in your form as required using the required aeribute. If you set a eld to required, your users cannot submit the form unAl they have entered valid data in that eld. The required aeribute does not require a value associated with it.
Require a Field
You can add placeholder text to your form elds to add instrucAons. The text appears inside the form eld when the form rst appears. If a user clicks inside the eld, the placeholder text disappears and the user can type in the eld as usual.
Add a Placeholder
39
1/27/13
Form
Example
The
RADIO
type
is
usually
a
group
of
items,
of
which
only
one
can
be
selected.
Thus,
each
item
has
the
same
NAME
aeribute,
but
with
dierent
VALUE
aeributes
so
that
the
server
can
be
told
which
one
has
been
chosen
by
the
user.
<INPUT
TYPE="RADIO"
NAME="SET_1"
VALUE="OPTION_1">Op)on
1<BR/>
<INPUT
TYPE="RADIO"
NAME="SET_1"
VALUE="OPTION_2">Op)on
2<BR/>
<INPUT
TYPE="RADIO"
NAME="SET_1"
VALUE="OPTION_3">Op)on
3<BR/>
Form Example
<FORM ACTION=TheFunc)onForAc)on" METHOD="POST"> Name: <INPUT TYPE="TEXT" NAME="NAME"><BR /> Address:<BR /> <TEXTAREA NAME="ADDRESS" ROWS="5" COLS="25"></TEXTAREA><BR /> <INPUT TYPE="SUBMIT" VALUE="Add Address"> </FORM>
40
1/27/13
Some
symbols
are
used
for
coding
in
HTML
such
as
<,
>,
and
.
If
you
want
these
symbols
to
appear
in
the
web
page
for
the
user
to
see,
you
need
to
use
the
&code
instead.
<
<
"
®
>
>
©
space
The
complete
list
can
be
found
on
W3C
Other
symbols
can
be
inserted
using
the
&#code,
see
the
character
map
in
windows
StartProgramsAccessoriesSystem
ToolsCharacter
Map
41
1/27/13
Character map
HTML5
d,
the
n
<video>
tag
for
embedding
video
clips
into
your
pages
and
an
<audio>
tag
for
integraAng
sound.
In
the
past,
developers
used
the
nonstandard
<embed>
tag
and
the
generic
<object>
tag
for
adding
mulAmedia.
HTML5
adds
a
number
of
new
input
elements
for
web
forms.
For
example,
you
can
create
text
elds
that
accept
only
e-mail
addresses
or
web
URLs.
Previously,
developers
have
had
to
resort
to
using
complicated,
custom
scripts
to
provide
such
features.
42
1/27/13
Drawing
on
Canvases
A
new
<canvas>
tag
enables
you
to
dene
a
rectangular
area
on
your
page
on
which
you
can
draw.
You
can
use
scripAng
commands
to
create
shapes,
draw
straight
and
curved
lines,
apply
color
gradients,
and
even
add
images
or
parts
of
images
within
the
area
In
the
past,
designers
needed
to
create
such
visual
content
in
a
separate
image
editor
or
drawing
program
and
then
embed
the
result
as
an
image.
Allow
you
to
reect
the
design
you
want
on
the
content,
but
be
able
to
change
it
on
a
whim
without
recoding
everything
from
the
ground
up.
Aeach
specic
informaAon
pertaining
to
the
rendering
of
HTML
while
remaining
within
XML
and
HTML
guidelines.
Very
important
when
dealing
with
Content
Management
Systems
(CMS).
Done
by
creaAng
named
derivaAons
then
use
these
derivaAons
as
aeributes
in
tages
Styles
are
created
using
the
"text/css"
language
You
can
introduce
styles
in
three
places
Inline
(at
the
same
Ame
as
the
tag,
such
as
<h1
style="color:
purple;">.
.
.)
Internally,
as
part
of
the
<head>
of
the
document
Externally,
in
style
sheets
External style sheets are a good idea if you need to be able to swap between styles
CSS adds style to exisAng content XSL provides the possibility to transform the content into something dierent CSS and HTML, XHTML, or XML.
43
1/27/13
The W3C actually denes a style sheet for XHTML 1.0, which gives the default style informaAon for the tags that are dened in that standard.
44
1/27/13
Internal CSS
45
1/27/13
External CSS
46
1/27/13
You can separate a list of selectors by commas to apply the same set of styles to all of them:
You can use the universal selector (*) to apply styles to every HTML tag in your document:
Note that you can override such a rule by wriAng addiAonal rules for specic tags.
47
1/27/13
Assign
a
Class
You
can
create
a
CSS
class
to
apply
a
style
rule
to
specic
instances
of
HTML
tags
in
a
page.
For
example,
if
you
want
the
introductory
paragraphs
formaeed
dierently
from
all
the
other
paragraphs,
you
can
create
a
class
specically
for
the
introductory
paragraphs.
Ager
you
create
the
class
and
assign
it
using
the_class_aeribute,
the
browser
applies
the
formapng
to
all
the
aected
paragraphs.
You
can
set
up
a
class
in
an
internal
or
external
style
sheet.
Ex:
h1.my_heading
{
color:
"blue";
}
<h1
class="my_heading">H1
In
Blue</h1>
48
1/27/13
Generic
class
You
can
use
a
generic
class
to
format
more
than
one
type
of
tag.
For
example,
you
might
use
a
generic
class
to
format
both
paragraphs
and
level
3
headings
in
a
document.
When
dening
a
generic
class,
simply
type
a
period
followed
by
the
class
name
and
then
your
declaraAon.
For
example:
.myclass
{color:
blue}
Do
not
type
an
HTML
tag
before
the
period.
The
following
HTML
examples
apply
the
class
to
dierent
tags:
<p
class=myclass><h3
class=myclass>
The paragraph above would have the styles associated with both the huge class and the fancy class applied to it.
49
1/27/13
50
1/27/13
51
1/27/13
52
1/27/13
53
1/27/13
TIPs
What should I keep in mind when optimizing a page for mobile devices such as the iPhone? Key things to consider are that you are designing for a smaller screen, navigation by touch, and slower download speeds. You should consider increasing the font size to make text more legible and links easier to tap; turning off the display of larger images to reduce the page download time; and disabling CSS float styles to convert multicolumn layouts into single-column layouts, which can be easier to view on smaller screens Is there a way to make a CSS rule specific to a media type? Yes. The steps above describe loading an entire external style sheet based on the media type. To limit a specific CSS rule to a media type, you can use the @media directive and surround the rule with an additional set of brackets: @media only screen and (max-device-width: 480px) { p.bigger {font-size: 16px;} }
The CSS code above sets the font size for paragraphs displayed on iPhones.
54
1/27/13
TIPs
What is the terminology to describe the nested relationship of tags on a page? We can use family-tree terminology. The outer tags are known as ancestors and the inner tags are known as descendants. In the example above, the <h2> tag must be a descendant of the <section> tag for the style to be applied. Tags directly next to each other in the hierarchy can be given more specific classification. The outer tag is a parent and the next tag immediately on the inside is a child. How do I specify a parent-child relationship in my CSS rule? You can specify that a style rule be applied only to the immediate descendant, or child, of a tag using a greater-than symbol (>) in the selector. The following applies a rule to a <p> tag that is directly inside of an <article> tag: article > p {font-size: 16px; color: green} This rule would apply to the following: <article><p>Hello, HTML5!</p></article> The rule would not apply to the following: <article><section><p>Hello, HTML5!</p></ section></article>
55
1/27/13
Derived
Objects
With
CSS
you
can
change
the
ow,
layout,
posiAon,
size,
and
even
adjust
the
parameters
so
that
the
resulAng
rendering
of
a
tag
looks
like
you
want,
but
the
behavior
will
remain
the
same,
e.g.
a
<ul>
will
always
behave
as
a
list
56
1/27/13
Summary
The
selectorThe
object,
or
part
of
the
HTML
document
The
propertyThe
aeribute
(property)
of
the
object
The
valueA
valid
value
for
that
property
tag.class
{
mulAple
properAes;
}
or
tag.class
{
property:
value;
property:
value;
}
The
class
may
not
be
required,
so
this
is
correct
Can
be
hierarchical
like
applying
style
to
the
emphasis
elements
of
the
form
tag
Form
em{font-size:14pt}
tag
{
mulAple
properAes;
}
Style data {property:value} are always contained within braces. Ex: To set the boarder of a div tag, one can use
div.odd_borders
{
border-top-style:
solid;
border-boeom-style:
doeed;
}
The
boarder
has
four
sides
which
are
border-top
border-leg
border-boeom
border-right
They
can
be
set
all
together
with
the
order
of
top
right
boeom
leg
div.odd_borders
{
border-style:
solid
solid
doeed
solid;
}
57
1/27/13
Summary
cont.
Inline
<html>
<head>Example
Inline
Styles</head>
<body>
<h1
style="text-decora)on:
underline
overline;
font-weight:
bolder;">
Heading
1
</h1>
</body>
</html>
<head>
<)tle>Example
Style
Placement</)tle>
<style
type="text/css">
<!--
style
statements
here
-->
</style>
</head>
<body>
<!--
page
content
here
-->
</body>
Layout
Denes
the
posiAon
of
block-level
tag
contents.
Block-level
tags
place
new
lines
before
and
ager
the
content
they
enclose.
The
<p>,
<h1>,
and
<table>
tags
are
examples
of
block-level
tags.
So
are
the
new
semanAc
HTML5
tags
such
as
<sec)on>,
<ar)cle>,
<header>,
and
<footer>.
58
1/27/13
PosiAoning
Content
You
can
place
using
dierent
posi5oning
Rela9ve
posi)oning
places
content
on
the
page
rela)ve
to
the
normal
ow
of
the
other
content
on
the
page.
Absolute
posi)oning
places
content
on
absolute
points
on
the
page
rela)ve
to
the
containing
block.
Fixed
posi)oning
places
content
rela)ve
to
the
browser
window
and
keeps
it
xed
as
a
user
scrolls.
The
default
is
sta)c
Osepng
Content
You
can
oset
content
on
your
web
page
from
its
normal
posiAon
using
top,
lep,
right,
and
boZom
style
sheet
proper)es.
These
are
ignored
when
staAc
posiAoning
is
used
59
1/27/13
Space outside the edge of the box is known as margin, whereas space inside the edge of the box is called padding. Style sheets enable you to control space on the top, leg, right, and boeom of the boxes independently.
The oat CSS property takes a box out of the normal ow of your page and moves it to the right or lep side of the enclosing box. Content that follows then wraps around the oated element.
FloaAng Content
60
1/27/13
61
1/27/13
RelaAve Size
The web browser displays the element with a width rela)ve to the size of the enclosing box.
You can assign the overow property to the <p>, <div>, and other block-level tags.
62
1/27/13
Place content relaAve to other content on the page. If you oset a rela)vely posi)oned element using the top, leg, right, or boeom property, the element is oset relaAve to the point where it would normally begin.
63
1/27/13
64
1/27/13
65
1/27/13
66
1/27/13
Set Margins
67
1/27/13
Add Padding
68
1/27/13
Content that comes ager the oated element in your HTML wraps around the other side.
69
1/27/13
By oaAng several smaller, rectangular elements to the same side, you can create a grid arrangement, which is useful for creaAng photo galleries.
70
1/27/13
71
1/27/13
Transparency
Transparency
done
by
changing
object
opacity.
However,
dierent
browsers
recognize
dierent
style
sheet
commands
for
changing
opacity.
For Internet Explorer, you can type lter: alpha(opacity=?) in your style rule, replacing ? with a value from 0 to 100. For other popular browsers, you can type opacity: ? in your style rule, replacing ? with a fracAonal number from 0.0 to 1.0. You can put both properAes in a declaraAon to make the eect compaAble with as many web browsers as possible.
72
1/27/13
Borders
Borders
can
be
set
explicitly
or
as
a
group
There
are
three
basic
parameters
that
each
border
can
be
set
with
WidthThe
width,
in
pixels,
percentage,
or
relaAve
measurement
StyleFor
example,
solid,
doeed,
and
so
on
ColorThe
color
You
can
group
a
border
by
edge
border-top:
width
style
color;
border-width:
width;
border-style:
solid;
border-color:
red;
Background
can
be
used
with
pracAcally
any
element,
from
divisions
and
table
cells
to
the
document
body
itself.
Forms
background-color
:
red;
background-color
:
#f00;
background-color
:
#0000;
Ex:
background-image: url("hep://www.server.com/myimage.jpg") The image will scroll with the rest of the content, but it can be xed to the viewport by specifying xed as a value for the background- aeachment property. For example: body { background-image: url("hep://www.server.com/ myimage.jpg"); background-aZachment : xed;}
73
1/27/13
The background-repeat property is used If the image is smaller than the alloeed space (canvas), it is to make it repeat to cover the available space. To set this behavior, there are four possible sepngs, from which one may be chosen:
Background cont.
background-repeat : repeat repeat-x repeat-y no-repeat If repeat is specied, the image is Aled throughout the background, starAng from the center of the background. If repeat-x or repeat-y is specied, the image is repeated in either the horizontal or verAcal axis, working from the inside out.
Any text block or span can have its text and font properAes set; this includes the div, p, table, and span elements. Text color:
The
font,
color,
spacing,
decoraAon
(underlining,
for
example),
line
height,
weight
(bold,
for
example),
and
alignment
(center,
right,
and
so
on)
can
all
be
specied
using
styles.
p.red_text
{
color:
red;
}
p.red_text
{
color:
#F00;
}
<!--
#RGB
-->
p.red_text
{
color:
#0000;
}
<!--
#RRGGBB
-->
font-style:
normal,
italic,
or
oblique
font-weight:
normal,
bold,
bolder,
lighter
font-size:
pt
size
or
percentage
font-size:
14pt;
font-size:
200%:
Font style:
text-decoraAon: underline, overline, line-through, none This cannot combined with font compound property, see next slide text-align: leg, right, center, jusAfy text-indent: number or percentage text-transform: uppercase, capitalize, lowercase
Text transforma)on:
Capitalized opAon only transforms the rst leeer where uppercase transforms all the leeers of a word.
74
1/27/13
To
make
sure
that
all
the
lines
are
spaced
with
reference
to
the
largest
font
used
in
the
enAre
paragraph,
and
not
space
each
line
according
to
the
size
of
the
text
contained
within,
you
must
set
the
line-height
property:
line-height:
pt
size,
mulAplier
or
percentage
The
mulAplier
is
a
simple
number,
and,
like
the
percentage,
is
calculated
with
reference
to
the
font
size
of
the
element
to
which
the
style
property
is
being
set.
<div
style="line-height:
1.2;
font-size:
12pt;">
<div
style="line-height:
120%;
font-size:
12pt;">
<div
style="line-height:
14pt;
font-size:
12pt;">
Font Family:
Using this form, you can idenAfy an exact font, with a generic alternaAve: font-family: Times New Roman, serif; SerifTimes New Roman, Garamond, and so on Sans-serifArial, Verdana, and so on CursiveScript, Corsiva, and so on FantasyAnything goes. . . MonospaceCourier New and so on
SIZE
You
can
also
set
a
size
measurement
in
millimeters
(mm),
cenAmeters
(cm),
inches
(in),
points
(pt),
picas
(pc),
x-height
(ex),
or
em
space
(em).
You
can
also
set
an
indent
size
as
a
percentage
of
the
text
block
width,
such
as
20%.
75
1/27/13
76
1/27/13
Although numerous le types are used for computer images, JPEG, GIF, and PNG are the three most popular types used on the web. Another opAon for displaying graphical content on your pages in HTML5 is by using the new <canvas> tag. JPEG
GIF
stands for Joint Photographic Experts Group, supports 24-bit color. JPEG is not a good choice for solid-color artwork because it results in a larger overall le size, which translates to longer download Ames. stands for Graphics Interchange Format, supports up to 256 colors. If your image or graphic contains few colors and not a lot of detail, such as logos. A single GIF le can also store mul)ple images and display them as an animaAon. Stands for Portable Network Graphics, oers rich color support and advanced compression schemes, so it is a good choice for a variety of image types. supports 24-bit color but can also be saved with fewer colors.
PNG
77
1/27/13
Images
To
insert
an
image
into
a
web
page
<IMG
SRC="image_name"
WIDTH="width"
HEIGHT="height"
ALT="Image
Text
)tle=The
image
)tle>
One
can
use
Width
and
height
to
resize
the
image
as
needed
The
alternaAve
aeribute
ALT
used
to
display
text
descripAon
in
case
the
image
is
not
loaded.
This
also
used
by
SEO.
The
)tle
will
be
shown
as
pop
up
note
when
the
mouse
hovers
over
the
image.
Another
aeribute
is
the
BORDER
aeribute.
Value
0
indicate
no
border.
78
1/27/13
Image
map
Consider
the
problem
of
having
a
picture
where
each
part
of
it
reference
something
else.
E.g.
the
world
map,
the
user
click
on
a
country
to
get
the
informaAon
about
it.
79
1/27/13
Imagemap
Rectangle
13,16
83,90
(Top-Leg
and
Boeom-Right)
Circle
58,147
32
(Center
and
Radius)
Polygon
108,31
158,51
181,155
139,147
103,65
80
1/27/13
Imagemap
example
<IMG
SRC="imagemap.jpg"
WIDTH="200"
HEIGHT="200
USEMAP="#image_map">
<MAP
NAME="image_map">
<AREA
HREF="index.html"
SHAPE="RECT"
COORDS="13,16,83,90">
<AREA
HREF="page2.html"
SHAPE="CIRCLE"
COORDS="58,147,32">
<AREA
HREF="page3.html"
SHAPE="POLY"
COORDS="108,31,158,51,181,155,139,147,103,65,108,31">
</MAP>
The
#
sign
is
used
for
internal
reference,
e.g.
USEMAP=#image_map
.
The low aeribute indicates the lowest realized value in the range. The high aeribute indicates the highest realized value in the range. The optimum aeribute indicates the range opAmum.
81
1/27/13
Display progress
Pseudo-Elements
There
are
elements
that
have
no
corresponding
tag
in
HTML.
They
might
be
contained
within
a
tag
or
just
be
outside
the
document
model.
They
are,
however,
quite
browser-dependent,
and
so
I
will
cover
only
two
of
them
here.
The
rst
line
of
a
block
(div,
p,
and
so
on)
The rst line might not be as long or short on all browsers It is possible to make sure (using specic font sizes in points and bounding boxes in pixels) that the text takes the same space on every plauorm, but ogen this is not desirable. div.arAcle:rst-line { text-transform: capitalize; } If you assume that the very rst leeer should be given extra importance, you can add the following: div.arAcle:rst-leeer { font-size: 14pt; }
The rst leZer of an inline or block element (span, block, p, and so on)
div { width: 150px; margin:10px;} div:rst-line { text-transform: uppercase; } div:rst-leeer { font-size: 200%; oat:leg;}
82
1/27/13
Lists
They
can
have
various
bullet
types,
borders,
backgrounds,
and
layouts,
as
well
as
many
varia)ons
of
counted
lists,
including
special
character
sets
and
numbering
schemes.
list-style-posi)on
indicates
where
the
bullets
(or
numbers,
leeers,
and
so
on)
should
be
placed
in
relaAon
to
the
list
item
text
and
formapng
box.
It
is
specied
as
follows:
list-style-posiAon:
inside,
outside
<ul style="list-style-posi)on: inside;border: 1px solid black;"> <li>These bullets are</li> <li>inside the box</li> </ul> <ul style="list-style-posi)on: outside;border: 1px solid black;"> <li>These bullets are</li> <li>outside the box</li> </ul>
Lists
cont.
list-style-type
<ol>
list-style-type:
decimal,
alpha,
roman
The
alpha
and
roman
are
used
in
conjuncAon
with
the
word
lower-
or
upper-
prexes
<ul>
list-style-type:
disc,
circle,
square
Using
an
image
list-style-image:
url(hep://mydomain.com/image_le.png)
83
1/27/13
Generally
speaking,
when
you
include
a
client
side
script
within
the
Web
page
(or
as
an
external
script),
it
is
to
perform
one
of
the
following
funcAons:
Improve
navigaAon
drop-down
menus
inline calendars or image selecAon (from thumbnail examples), which layer CSS (styles, such as div elements) on top of regular HTML. includes oering topic expansion or inline help. as well as oaAng sign-up boxes or splash screens.
the ability to switch between content without loading another page (that is, like a tab control), as well as retrieving and displaying informaAon from the server based on data that the user is entering (AJAX) Shopping cart or quesAonnaire (survey) plauorm for mulA-page quesAonnaires.
Intro.
Client
side
scripts
are
executed
by
the
client
(the
browser)
as
if
they
are
extensions
to
the
HTML
page
that
is
being
displayed
browser
must
have
support
for
the
scripts
Build-in
scripts:
JavaScript,
HTML,
XML
Add-ins:
Adobe
Flash
player,
Microsog
Silverlight,
VRML,
and
so
on.
Scripts can be included inline or externally loaded as separate les. The Web server can serve scripts in the same way that it can serve image les and external style sheets they are just another reference to be loaded as part of the page. Before execu)ng scripts, the browser generally tries to make sure that it has all the informa)on it needs.
84
1/27/13
Inline
Scripts
Placed
in
the
head
secAon
of
the
HTML
document
and
will
be
accessible
for
all
the
HTML
document.
<script>
//
Code
lines
go
here...
</script>
Inside
the
script
tag
you
place
funcAons
and
variables.
Usually,
the
type
of
script
should
be
menAoned
in
the
script
tag:
<script
type=text/JavaScript>
scripts
can
be
used
as
acAons
in,
for
example,
form
controls.
This
makes
use
of
the
events
that
are
part
of
the
HTML
DOM
and
dened
by
the
W3C.
External
Scripts
Can
be
shared
across
mulAple
Web
pages.
In
addiAon,
there
is
a
certain
amount
of
hiding
of
the
script
that
takes
place
because
it
is
on
a
server
and
not
directly
in
the
page.
However,
scripts
are
never
going
to
be
safe
unless
you
take
addiAonal
steps
to
protect
them
by
using
a
tool
that
makes
them
unreadable.
The
use
of
an
interpreter
or
virtual
machine
such
as
in
java
applets.
Or
using
on-the-y
encrypAon
algorithm
would
be
beeer
o
encoded
85
1/27/13
JavaScript can access and change your elements on a page using DOM. DOM is hierarchal representaAon of HTML5 tags.
IntroducAon
to
JavaScript
Can
be
used:
inline,
external,
mixed
An
inline
script
must
be
contained
within
a
matching
pair
of
<script>
tags,
either
in
the
head
or
the
body
secAon
<script
language="JavaScript1.1">
</script>
//
Code
lines
go
here...
The
script
tag
may
someAmes
omieed
when
JS
is
used
directly
as
event
handler
<input
type="submit"
value="Submit"
onClick="document.myForm.name.style
=
background- color:red">
<a
href="javascript:history.go(-1)">Back</a>
86
1/27/13
<script src="my_func)ons.js" type=text/javascript"> The type aZribute is open omiZed, because it is assumed that the server will supply the correct MIME type to the browser. However, because this is not guaranteed, I prefer to give the browser all the informaAon that it might need in advance.
Example
87
1/27/13
It
is
necessary
to
do
two
things
when
using
JavaScript
A
browser
that
does
not
process
JavaScript
(or
the
<script>
tag)
will
not
be
able
to
do
anything
more
than
ignore
the
informaAon
that
it
does
not
understand.
So
you
just
put
those
commands
in
HTML
comments,
thus:
<script
language="JavaScript1.1">
<!-
-
Use
HTML
comments
to
hide
the
code
//
JavaScript
commands
go
here...
//
...
this
line
ends
the
hiding
here
-
->
</script>
The
second
approach
is
to
display
some
other
content
that
does
not
rely
on
scripts
to
be
displayed
by
the
browser.
<noscript>
Your
browser
does
not
seem
to
support
JavaScript!<br/>
(Perhaps
you
need
to
enable
it?)
</noscript>
It is becoming less and less necessary to do either of these opAons but it is sAll a good pracAce
Remarks
JavaScript
rarely
fails
noisily.
the
only
clue
that
you
have
that
it
is
not
correctly
wrieen
is
that
it
fails
to
do
anything.
You
need
to
use
the
repor)ng
func)on
of
your
browser.
In
Internet
Explorer,
this
is
indicated
by
a
liele
error
ag
in
the
boeom
leg
of
the
status
bar.
Double
click
to
access
it.
In
Firefox,
you
need
to
access
the
error
console
via
the
menu.
88
1/27/13
Remarks cont.
All
statements
must
end
with
a
semicolon
(;).
In
JavaScript,
comments
are
usually
contained
ager
//
and
inside
/*
*/.
Names
of
things
in
JavaScript
cannot
start
with
numbers
or
other
special
characters
(although
they
can
start
with
underscores,
_,
if
you
so
wish).
JavaScript
is
also
not
type-sensi)ve.
JavaScript
names
cannot
contain
spaces
JavaScript
converts
values
by
itself
based
on
the
target
type
or
chooses
the
most
appropriate
type
for
a
literal
provided
by
the
programmer.
89
1/27/13
Link to external JS le
90
1/27/13
91
1/27/13
Pop-up window
92
1/27/13
93
1/27/13
One Problem exist that is the change of images is not immediate (it takes a while in the rst )ll browser load the other images)
94
1/27/13
95
1/27/13
96
1/27/13
97
1/27/13
A variable is usually assigned the data type of the rst piece of data to be stored in it. Do not try to mix literals or variables, it is beeer to ensure that your code does not assume anything.
Arrays
An
array
can
contain
any
data
type
that
can
be
dened
in
JavaScript,
including
the
objects
that
make
up
an
HTML
page.
They
can
also
be
mixed,
meaning
that
dierent
types
of
data
can
be
stored
next
to
each
other
in
the
array.
But
you
have
to
remember
which
array
element
holds
which
data
type!!
98
1/27/13
Arrays
cont.
An
array
can
be
declared
by
Either
lling
it
with
values
or
Reserving
a
certain
number
of
items
in
advance.
Example
var
myArray=new
Array(10);
An
array
is
indexed
zero-based.
myArray[0]
=
"banana";
//
This
is
the
rst
element
Operators
Operators
can
be
categorized
depending
on
their
funcAon
AssignmentAssigns
a
value
to
a
variable
x
=
"42";
//
Put
a
string
literal
in
x
x
/=
2;
//
x
=
x
/
2
(division)
x
-=
7;
//
x
=
x
-
7
99
1/27/13
Operators
cont.
LogicalFor
use
with
Boolean
(true
and
false)
values
&&,
||,
and
!
!(x
=
=
y)
||
!(a
=
=
b);
Operators
cont.
The
condiAonal
operator,
?
condiAon
?
if_true
:
if_false
(y
==
3)
?
x
=
0
:
x
=
1;
The
this
operator
is
special
in
that
it
returns
the
object
that
is
currently
being
referenced.
This
will
usually
be
in
the
context
of
an
event
handler
coupled
with
an
HTML
object.
<form
ac)on="submit.php"
onClick="validate_form(this);"
method="post">
The operator void is used when something must be evaluated, but no value is returned or processed
100
1/27/13
FuncAons
The reason for this is to be sure that all the funcAons are available when the HTML document objects are instanAated (loaded and rendered) by the browser. There is a set of useful built-in funcAons, but the vast majority of work in JavaScript is done via the methods associated with built-in objects and not standalone funcAons. FuncAons can be called from anywhere in the HTML document by using the script tag or by assigning them to event handlers.
Calling FuncAons
Built-In Func)ons:
Conversion
funcAons
Number
and
String
(convert
string
to
number
and
number
to
string
respecAvely)
The
eval
funcAon
allows
you
to
evaluate
a
string
as
if
it
were
a
piece
of
JavaScript
code.
myDate
=
new
Date
();
//
make
a
new
date
object,
set
to
Today
myDateString
=
String
(myDate);
//
convert
to
a
string
The
escape
and
unescape
funcAons
allow
you
to
encode
a
URL
by
escaping
the
special
characters.
mySearchString
=
escape("rst
second
third");
//
mySearchString
contains
"rst%20second%20third
myNumber = (3>1)?(1 + 3):(3-1); // myNumber contains "(3>1)?(1 + 3):(3-1)" myNumber = eval ( myNumber ); // myNumber now contains 4
101
1/27/13
User-Dened
FuncAons
A
funcAon
(name
and
parameters)
should
not
be
iden)cal
to
another
func)on.
To
dene
a
funcAon
func)on
myFunc)on
(
myParameter1,
myParameter2
)
{
// My code statements } A funcAon can also return a value, which can be used for ongoing processing. An example of a funcAon that returns a value is as follows:
As
long
as
the
funcAon
has
been
dened
before
it
is
called,
it
can
be
called
from
inside
another
funcAon.
A
funcAon
can
also
be
dened
as
recursive;
in
other
words,
it
can
call
itself.
func)on
my_fact
(
n
)
{
if
(n
<=
1)
return
1;
//
is
n
less
than
or
equal
to
1?
else
return
(n
*
my_fact(n-1)
);
//
if
not
call
itself
}
funcAon myFuncAon ( myParameter1, myParameter2 ) { // My code statements return myReturnValue; } The type of myReturnValue can be anything that JavaScript supports, even objects.
It
is
perfectly
possible
to
dene
a
funcAon
that
does
not
have
exactly
one
named
parameter
for
each
piece
of
informaAon
that
it
needs
to
process.
Instead
it
has
only
one
named
parameter,
and
the
rest
are
implied
and
can
be
accessed
from
the
funcAon
code
implicitly.
Parameters
that
are
passed
and
not
named
can
be
accessed
through
the
arguments
property
of
the
funcAon.
func)on
myFunc)on
(
parameter_0
)
{
return
parameter_0
+
this.arguments[1];
}
This
example
assumes
that
the
funcAon
will
be
passed
more
than
one
argument,
otherwise
arguments[1]
will
be
undened.
for
(
var
arg
=
0;
arg
<
this.arguments.length;
arg++
)
{
//
process
this.arguments[arg]
here
}
You can obtain the number of arguments by using the length property of the arguments collecAon
102
1/27/13
Objects
you
use
typeof
to
determine
what
kind
of
type
these
are
In
reality,
because
JavaScript
converts
between
a
value
and
an
object,
there
is
no
dierence
between
the
two
when
it
comes
to
pracAcal
maeers
of
their
applicaAon.
typeof
myString_1;
//
returns
string
typeof
myString_2;
//
returns
object
Example
<script
type=text/javascript>
var
outText
=
new
String("Bold");
document.write(outText.bold());
var
evalString
=
"outText.italics()";
evalString
=
"document.write("
+
evalString
+
");";
eval
(evalString);
</script>
.
103
1/27/13
CondiAonal
Processing
if
..
else
}
else
{
if
(
a
=
=
"my
string
"
+
myNumberAsString
)
{
//
do
this
if
a
is
true
//
do
this
if
a
is
false
switch
switch ( colorNumber ) { // the condiAon can be any testable data type case 0 : colorString = "#0000"; break; case 1 : colorString = "#0000"; break; default: colorString = "#"; }
Loops
for ( var counter = 0; counter < total_iteraAons; counter++ ) { // statements to execute } var counter = 0; do { // statements to execute counter++; } while ( counter < total_iteraAons ); var counter = 0; while ( counter < total_iteraAons ){ // statements to execute counter++; }
104
1/27/13
105
1/27/13
Each
event
that
can
be
aeached
with
any
HTML
object
(usually
the
body,
img,
a,
and
form
tags)
has
the
general
form:
The
code
can
be
anything
from
a
call
to
a
funcAon
(recommended)
to
a
single
line
of
JavaScript.
<script>
func)on
event_handler()
{
//
func)on
code
here
Events
<tag onEvent="code">
} </script> <body onKeyPress="event_handler();"> In this example there are no access to event proper)es, to have such access: <body> <script> func)on event_handler(e) { // func)on has access to event proper)es } document.onKeyPress = event_handler(event); </script> </body>
onAbort
This
event
occurs
when
the
user
interrupts
the
loading
of
a
page.
The
OnAbort
event
should
only
be
trapped
once
for
the
HTML
document
as
a
whole.
For
example
it
is
used
with
img
tags.
<img
src=myimage.gif
onAbort="if
(!conrm(Stop
loading
document?))
{
history.go(0);
}">
This
snippet
will
ask
if
the
users
want
to
stop
loading
the
document.
If
they
click
No
on
the
conrm
dialog
box
that
appears,
the
document
will
be
reloaded.
Events cont.
onBlur This event occurs when an element in a page or when the window containing a page loses focusthat is, the user moves away from it by using the Tab bueon. It only applies to interacAve form elements and the window object.
106
1/27/13
onChange This event occurs when the content of an interacAve form element changes. This only applies to those elements that have selectable or user entered values.
Events cont.
onClick
This
event
occurs
when
an
object
on
a
document
is
clickedthat
is,
a
form
bueon
(including
checkboxes
and
radio
bueons)
or
a
link.
Because
a
click
is
a
combinaAon
of
a
mouseDown
and
mouseUp
event,
clicks
can
be
trapped
separately
with
their
own
handlers.
An
example
of
handling
the
onClick
event
might
be:
<a
onClick="this.myForm.submit();">
<img
src="submit.gif"
alt="Submit"></a>
For example, the Google Suggest service traps this event in order to populate the list of suggested search terms. This is used as follows: <input type="text" name="keywords" onChange="updateKeyList(this.value);">
Events
cont.
onDblClick
This
event
is
the
same
as
the
onClick
event,
except
that
it
is
triggered
when
the
user
double-clicks
a
control.
onFocus
This
event
is
the
opposite
of
onBlur,
that
is,
it
is
triggered
when
the
focus
moves
to
a
control
on
a
from.
onKeyDown,
onKeyPress,
and
onKeyUp
These
three
events
are
triggered
in
response
to
key
presses,
usually
trapped
by
a
document
object.
However,
they
are
also
listed
for
event
handlers
for
links,
images,
and
text
area
input
controls.
They
use
a
number
of
so-called
event
properAes.
107
1/27/13
Events cont.
The
onLoad
event
is
triggered
when
a
document
has
nished
loading.
It
is
usually
handled
in
the
body
tag,
thus:
<body
onLoad="my_funcAon();>
Ex:
When
page
is
loaded
into
frame.
<body
onLoad="my_funcAon();
onUnload="my_cleanup_funcAon();">
Events
cont.
onMouseMove
This
event
is
triggered
when
the
mouse
is
moved
over
a
browser
window.
108
1/27/13
<html> <head> <script type="text/javascript"> funcAon bigImg(x) { x.style.height="64"; x.style.width="64"; } funcAon normalImg(x) { x.style.height="32"; x.style.width="32"; } </script> </head> <body> <img onmousemove="bigImg(this)" onmouseout="normalImg(this)" border="0" src="smiley.gif" alt="Smiley" width="32" height="32" /> <p>The funcAon bigImg() is triggered when the user moves the mouse pointer over the image. This funcAon enlarges the image.</p> <p>The funcAon normalImg() is triggered when the mouse pointer is moved out of the image. That funcAon changes the height and width of the image back to normal.</p> </body> </html>
Example
Events
cont.
onReset
and
onSubmit
The
onReset
event
is
triggered
when
the
user
clicks
the
Reset
bueon
of
a
form,
and
the
onSubmit
event
is
triggered
when
the
user
clicks
the
Submit
bueon.
These
events
are
handled
in
the
form
tag:
onSelect
This
event
is
triggered
when
the
content
of
a
text
eld
is
selected.
This
is
useful
in
providing
dynamic
forms
and
support
to
users
when
they
ll
them
out.
For
example,
a
funcAon
could
be
wrieen
to
populate
a
container
of
city
names,
so
the
users
can
choose
their
city
from
the
list.
109
1/27/13
Example
<html>
<head>
<script
type="text/javascript">
funcAon
showMsg()
{
alert("You
have
selected
some
of
the
text!");
}
</script>
</head>
<body>
Select
text:
<input
type="text"
value="Hello
world!"
onselect="showMsg()"
/>
</body>
</html>
110
1/27/13
Event properAes
Returns whether or not an event can have its default acAon prevented
111
1/27/13
Example
Example
112
1/27/13
Example
The .open and .close methods are superuous for cross- plauorm browser development because not all browsers react in the same way. In most cases calls to these methods are addiAve. formsAn array of all the forms imagesAn array of all the images linksAn array of all the link locaAons in the document
113
1/27/13
The arrays are zero-based like all arrays. In addiAon it is possible to idenAfy forms by their name,
provided that forms have been dened with a name="myForm aeribute document.forms["MyForm"]
Can
be
used
for
making
controls
in
a
form
available
(or
not)
depending
on
the
opAons
already
chosen.
Ex:
make
an
enAre
<div>
appear
and
disappear,
like
a
message
or
pop-up
box.
The
frames
array
property
gives
access
to
any
frame
that
might
be
contained
within
the
window.
The
length
property
indicates
the
number
of
frames
for
and
the
parent
property
to
traverse
to
parent.
The loca)on property contains the address (URL) of the currently loaded document in the window (or frame). The status property contains a value that is displayed in the status bar (usually at the boeom of the screen) and this can be updated to change the message being displayed.
114
1/27/13
The print method opens the standard operaAng systems Print dialog box and prints the window contents. The stop method halts the current download, which is useful if something might take a long Ame to complete and you would like to allow the users to stop the process.
Using
the
String
object,
it
is
possible
to
convert
a
string
literal
to
a
piece
of
HTML
code.
Usually
used
with
the
document.write
method
to
generate
the
inline
HTML.
however,
the
actual
HTML
is
not
visible
when
the
user
selects
View
Source,
only
the
JavaScript
that
has
generated
the
HTML
will
be
var
myString
=
"anchor
text";
document.write(myString.anchor("anchor_name"));
<a
name="anchor_name">anchor
text</a>
var
myString
=
"url
text";
document.write(myString.link("url"));
<a
href="url">url
text</a>
Ex:
This example is the equivalent of the following HTML code: By the same token, the link method is used as follows: This is rendered by the browser as if the HTML had been:
115
1/27/13
Of course, string variables could have been used in these examples instead of literals. Also there are some methods used to create fonts of dierent properAes:
xedChooses a xed font (like Courier) fontcolor ( color )Species the color of the font, where color is either #rrggbb or color name, following the Web standards
The
alert
method
displays
a
box
alerAng
the
user,
with
a
custom
string
and
a
single
OK
bueon.
For
example:
alert("Alert!
You
pressed
the
alert
bueon...");
116
1/27/13
The
prompt
method
displays
a
box
in
which
the
users
can
type
some
text.
If
they
then
click
OK,
the
text
is
returned;
otherwise,
null
is
returned.
For
example:
theResult
=
prompt("Please
enter
some
text...");
If more complex interacAon is required, you can use the window.open method to open a new window containing a form from which informaAon can be obtained. Or, a custom div can be displayed containing the relevant HTML.
117
1/27/13
JavaScript
provides
the
possibility
to
execute
a
funcAon
ager
a
certain
length
of
Ame
has
elapsed
in
one
of
two
ways:
Once
every
x
milliseconds
(interval)
acAvated
by
using
the
setInterval
method
and
stopped
using
the
clearInterval
method.
AcAvated
by
using
the
setTimeout
method
and
Stopped
using
the
clearTimeout
method.
Interval Processing
The
setInterval
method
can
be
used
in
one
of
two
ways:
with
an
expression
or
with
a
funcAon
plus
an
argument
list.
For
example,
the
following
two
usages
are
idenAcal:
var
AmerID=setInterval("my_funcAon
(
1,
2,
3,
4
);",
25)
var
AmerID=setInterval(my_funcAon,
25,
1,
2,
3,
4)
clearInterval
(
AmerID
);
To cancel the interval Amer, use the clearInterval method with the Amer idenAer:
setTimeout and clearTimeout arguments are the same as the setInterval and clearInterval
Accessing
Cookies
Cookies
are
small
pieces
of
informaAon
that
are
stored
as
name,
value,
expiraAon
tuples.
The
expiraAon
date
is
opAonal
The
exact
format
of
the
cookie
data
is
up
to
the
programmer
to
dene.
JavaScript
provides
access
to
the
cookies
through
the
document.cookie
property.
cookies
need
to
be
encoded
(using
the
escape
and
unescape
funcAons)
to
render
unsupported
characters
(such
as
spaces)
as
data
using
their
hexadecimal
equivalents.
118
1/27/13
Cookies example
So,
to
set
a
cookie,
it
is
necessary
to
build
a
cookie
string
(document.cookie)
with
three
parts
the
name
(not
encoded),
the
value
(encoded),
and
the
expiry
date
(not
encoded
and
also
op)onal).
This is then replaced by a space value when given to the unescape funcAon.
The
cookie
string
can
then
be
set
in
the
document
properAes,
but
is
stored
by
the
browser.
The
complete
soluAon
is
as
follows:
document.cookie
=
name
+
=
+
escape(value)
+
;
expires="
+
expiry_date;
+
";"
To
get
the
expiry
date,
you
simply
convert
the
Date
object
value
to
a
GMT
string
using
the
.toGMTString()
of
the
Date
object.
For
example:
If expiry date not required, the cookie becomes a pair with just the name and encoded value.
Cookies
Example
funcAon
createCookie(name,value,days)
{
if
(days)
{
var
date
=
new
Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
//days
converted
to
milliseconds
var
expires
=
";
expires="+date.toGMTString();
}
else
var
expires
=
;;
document.cookie
=
name+"="+escape(value)+expires;
}
funcAon
readCookie(name)
{
var
nameEQ
=
name
+
"=";
var
ca
=
document.cookie.split(';');
for(var
i=0;i
<
ca.length;i++)
{
var
c
=
ca[i];
if
(c.indexOf(nameEQ)
==
0)
return
unescape(c.substring(nameEQ.length,c.length));
}
return
null;
}
funcAon
eraseCookie(name)
{
createCookie(name,"",-1);
}
119
1/27/13
Query
Strings
Some
URLs
that
are
the
result
of
a
form
submission
contain
data
that
has
been
submieed
and
that
might
be
useful
to
extract
from
the
URL
The
locaAon.search
property
accesses
the
porAon
of
the
URL
ager
the
?
(quesAon
mark),
which
is
known
as
the
query
string.
The
value
returned
includes
the
?,
so
the
rst
operaAon
is
to
discard
it.
Using
the
indexOf
method
of
the
string
object,
it
is
possible
to
extract
the
values
for
use
in
the
JavaScript
code.
This
could
also
be
true
of
a
form
that
is
passed
back
to
the
same
document
for
processing,
but
the
query
string
is
likely
to
be
more
complex.
For
example,
consider
the
following
HTML
code:
<form>
<input
type="text"
value=""
name="texield">
<input
type="Submit"
value="Submit!">
</form>
This
submits
the
form
back
to
the
source
page
with
the
URL.
If
you
had
entered
Banana
in
the
text
eld,
the
URL
would
look
something
like
this:
le:///test.html?texuield=Banana
120
1/27/13
String
121
1/27/13
String
example
string.charAt
(
n
)
string.slice
(
start,
end
)
string.substr
(
start,
length
)
string.split
(
separator,
limit
)
var
queryString
=
window.locaAon.search.substr
(
1
);
//
everything
except
the
?
//
split
by
the
&
character
var
queryArray
=
queryString.split
(
"&"
);
string.concat(
string_1,
string_2,
...
string_n
)
var
rstThat
=
myString1.indexOf
(
"g1"
);
//
returns
5
var
lastThat
=
myStringN.lastIndexOf
("2"
);
//
returns
7
var
myString2
=
myStringN.replace("123",
"1234");
string.toUpperCase()
string.toLowerCase()
var
myString1
=
"String1";
var
myStringN
=
myString1.concat("2",
"3");
122
1/27/13
123
1/27/13
Array
Examples
var
myNumbers
=
new
Array
(
42,
84,
12
);
var
myStrings
=
new
Array
(
"forty-two",
"eighty-four",
"twelve"
);
var
myNewArray
=
myNumbers.concat(myStrings);
//[
42,
84,
12,
"forty-two",
"eighty-four",
"twelve"
]
var
myString
=
myNewArray.join(",
");
//
default
separator
is
comma
turns
an
array
into
a
string,
separated
with
a
user-dened
or
default
separator.
//"42,
84,
12,
forty-two,
eighty-four,
twelve
//
newArray
contains
[
42,
84,
12,
"forty-two"
]
In
this
deniAon,
startAt
gives
the
index
at
which
to
begin
the
splice.
Similarly,
toRemove
gives
the
number
of
elements
that
should
be
removed
var
newArray
=
new
Array
(
);
newArray.splice
(
0,
0,
"1",
"two",
3
);
//[
"1",
"two",
3
]
newArray.splice
(
1,
2,
"twelve",
"four"
);
//[
"1",
"twelve",
"four"
]
funcAon compare ( a, b ) { if (a < b) { return -1; } if (a > b) { return 1; } return 0; } var myArray = new Array ( 1, 5, -3 ); myArray.sort ( compare );
124
1/27/13
125
1/27/13
Custom
MB
<div
id="msgBox
style="
width:250px;height:150px;visibility:hidden;leg:150;top:150;">
<table
style="background-color:#000080;
width=100%
height=100%
cellpadding=5>
<tr
height=15px>
<td
style="color:#;">
<b>Message
Box
Title</b>
</td>
</tr>
<tr>
<td
style="background-color:#;
align="center"
valign="center">
<b>Message
Box
Text</b><br/>
<table>
<tr>
<td>
<input
type="bueon"
value="
OK
onClick="close_dialog(OK);">
</td>
<td> </td>
<td>
<input
type="bueon"
value="Cancel
onClick="close_dialog(Cancel);">
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
126
1/27/13
Custom
MB
cont.
The
whole
dialog
box
is
contained
inside
a
div
tag,
which
is
set
to
visibility:hidden
so
that
it
cannot
be
seen
iniAally.
The
close_dialog
funcAon,
triggered
by
the
onClick
events
of
the
two
bueons,
is
just
there
to
set
the
visibility
back
to
hidden.
It
looks
like
this:
funcAon
close_dialog
(
)
{
document.getElementById("msgBox).style.visibility
=
"hidden";
}
funcAon
open_dialog
(
)
{
document.getElementById("msgBox).style.visibility
=
"visible";
}
The
open_dialog
funcAon
is
just
there
to
set
the
visibility
to
visible:
To
test
the
code,
you
need
to
place
a
bueon,
with
appropriate
JavaScript
code,
to
make
the
div
visible.
<input
type="bueon"
onClick="return
open_dialog();
value="Show
Dialog">
to
add
an
overlay
that
blanks
out
the
original
page
when
the
pop-up
message
box
is
shown.
The
overlay
is
dened
as
follows:
<div
id="overlay
style=z-index:100;
posiAon:
absolute;
width:100%;
height:100%;
leg:0;
top:0;
visibility:
hidden;
background-color:
silver;
lter:
alpha(opacity=50);
opacity: 0.5"></div>
127
1/27/13
Display
a
CalculaAon
You
can
use
the
new
HTML5
<output>
tag
to
display
the
result
of
a
calculaAon
on
your
page.
The
tag
works
with
one
or
more
form
<input>
tags
that
accept
numeric
values
from
the
user.
The
<output>
tag
enables
you
to
perform
mathemaAcal
calculaAons
for
your
users
and
easily
display
the
results
on
the
page.
128
1/27/13
DesAnaAon
129
1/27/13
The
<canvas>
tag
enables
you
to
dene
a
blank
drawing
area
on
your
web
page.
You
can
then
draw
shapes,
lines,
and
text,
insert
images,
create
gradients,
and
do
other
interesAng
things
using
JavaScript.
The
tag
accepts
width
and
height
aeributes
that
dene
the
size
of
the
canvas.
You
also
need
to
add
an
id
aeribute
so
your
scripts
can
draw
on
the
canvas.
Next
step
in
all
canvas
tasks
is
sepng
up
the
drawing
context.
This
prepares
your
JavaScript
code
to
access
all
the
instrucAons
it
needs
for
adding
shapes,
lines,
and
other
elements
to
your
canvas.
Then
you
need
to
choose
a
color
and
an
outline
width
for
drawing.
Done
using
getContext
method
Canvas
130
1/27/13
To successfully draw on your canvas using JavaScript, your HTML5 canvas has to be loaded prior to your script code running. You can do this by placing your script ager your canvas on your page, or place it in a JavaScript funcAon which you can then call using the onload aeribute in the <body> tag.
Draw Rectangles
131
1/27/13
Draw
Circles
For
creaAng
a
circle,
you
dene
a
center
coordinate
a
radius
you
also
dene
how
far
along
the
circumference
of
the
circle
to
draw.
You dene this value in radians, and to draw a complete circle this value is two Ames the value of pi.
The rst two numbers dene the coordinates of the circle center and The third number denes the radius of the circle in pixels. To draw a circle set the starAng angle to 0 and the ending angle to Math.PI*2. A true value draws the circle in a clockwise direcAon, and false draws it in a counterclockwise direcAon.
132
1/27/13
133
1/27/13
Draw
Lines
You
create
a
line
by
specifying
the
coordinate
at
which
to
start
the
line
using
the
moveTo
method.
Then
you
specify
an
ending
point
with
the
lineTo
method.
Calling
the
stroke
method
draws
the
line.
134
1/27/13
Add
Text
You
can
set
a
font
family
and
size
using
the
font
method
in
your
script.
You
can
create
lled
text
using
the
llText
method
or
outlined
text
using
the
strokeText
method.
To
add
extra
styling
to
your
text
you
can
rotate
it.
For
details,
see
?Rotate
Canvas
Content.?
135
1/27/13
136
1/27/13
The image must rst be loaded into the browser. Script execuAon is delayed unAl ager page loading using the onload property.
Add an Image
137
1/27/13
Scaling
The
drawImage
method
accepts
two
addiAonal
values:
The
rst
value
denes
the
width
of
the
resulAng
image,
and
the
second
denes
the
height.
ctx.drawImage(pict,
10,
10,
pict.width*0.5,
pict.height*0.5);
138
1/27/13
It
enables
you
to
place
the
part
of
the
image
that
interests
you,
or
place
several
parts
of
the
same
image
by
repeaAng
the
slicing.
The
rst
pair
denes
the
starAng
coordinates
of
the
rectangular
slice
in
the
original
image.
The
second
pair
denes
the
width
and
height
of
the
slice.
The
third
pair
denes
the
coordinates
where
the
slice
is
placed
on
the
canvas.
Slice an Image
The fourth pair denes the dimensions of the slice on the canvas. For no scaling, the second and fourth pairs of values are idenAcal.
139
1/27/13
PHP
Intro
to
PHP
These
PHP
scripts
are
wrieen
in
plain
text,
making
them
easy
to
edit
and
upload
to
the
server.
Although
they
can
be
compiled
this
is
not
common
for
user-created
scripts.
Like
JavaScript,
PHP
can
be
contained
inline
within
an
HTML
document,
or
it
can
be
referenced
from
an
HTML
document,
usually
through
embedded
PHP
code.
HTML
and
PHP
can
be
freely
mixed
so
long
as
the
convenAons
are
followed.
The
dierence
is
that
all
pages
that
contain
PHP
code
should
have
the
extension
.php,
so
that
the
system
can
send
them
to
the
php
interpreter.
In
addiAon,
someAmes
they
need
to
have
their
permissions
changed
so
that
they
are
classied
as
executable.
140
1/27/13
Inline
PHP
Can
be
wrieen
in
many
dierent
styles
The
correct
way
to
break
out
of
HTML
and
introduce
some
PHP
is
as
follows:
<body>
<b>This
is
HTML.</b>
<?php
//
PHP
code
here
?>
<b>This
is
also
HTML.</b>
</body>
Ex:
141
1/27/13
External
PHP
The
easiest
way
to
reference
an
external
PHP
le
is
through
the
include
funcAon,
and
is
usually
inserted
in
a
block
of
PHP
code.
For
example:
<?php
include
my_module.php;
?>
Other
styles
Short
style
<?
echo
<p>Order
processed.</p>;
?>
This
tag
style
is
the
simplest
and
follows
the
style
of
a
Standard
Generalized
Markup
Language
(SGML)
processing
instrucAon.
To
use
this
type
of
tagwhich
is
the
shortest
to
typeyou
either
need
to
enable
the
short_open_tag
sepng
in
your
cong
le
or
compile
PHP
with
short
tags
enabled.
The
use
of
this
style
is
not
recommended
because
it
will
not
work
in
many
environments
as
it
is
no
longer
enabled
by
default.
<script
language=php>
echo
<p>Order
processed.</p>;
</script>
This
tag
style
is
the
longest
and
will
be
familiar
if
youve
used
JavaScript
or
VBScript.
You
might
use
it
if
youre
using
an
HTML
editor
that
gives
you
problems
with
the
other
tag
styles.
<%
echo
<p>Order
processed.</p>;
%>
This
tag
style
is
the
same
as
used
in
AcAve
Server
Pages
(ASP)
or
ASP.NET.
You
can
use
it
if
you
have
enabled
the
asp_tags
conguraAon
sepng.
You
probably
have
no
reason
to
use
this
style
of
tag
unless
you
are
using
an
editor
that
is
geared
toward
ASP
or
ASP.NET.
Note
that,
by
default,
this
tag
style
is
disabled.
SCRIPT style
ASP style
142
1/27/13
Notes
on
PHP
Whitespace
are
ignored
by
php
unless
it
is
enforced
by
direcAves
such
as
\n.
Comments
are
the
same
as
in
C/C++,
in
addiAon
It
supports
shell
one
line
comment
style
using
#
<form acAon="processorder.php" method="post"> <table border="0"> <tr bgcolor="cccccc"> <td width="150">Item</td> <td width="15">QuanAty</td> </tr> <tr> <td>Keyboards</td> <td align="center"><input type="text" name="KBqty" size="3" maxlength="3"/></td> </tr> <tr> <td>CDs</td> <td align="center"><input type="text" name="CDqty" size="3" maxlength="3"/></td> </tr> <tr> <td>LCDs</td> <td align="center"><input type="text" name="LCDqty" size="3" maxlength="3" /></td> </tr> <tr> <td align="center"><input type="submit" value="Submit Order"/></td> </tr> </table> </form>
143
1/27/13
144
1/27/13
145
1/27/13
146
1/27/13
147
1/27/13
A combinaAon of all data submieed via GET or POST is also available through $_REQUEST.
148
1/27/13
Because this code will not produce any output, placing it above or below the <html> and other HTML tags that start your page makes no dierence Generally place such blocks at the start of the script to make them easy to nd. To see the value, one can use echo $KBqty. KBs<br />;
The
dot
operator
is
used
to
concatenate
string
like
the
plus
operator
in
javascript
One
can
use
single
or
double
quotaAons
for
string
In
single
quotaAons
nothing
altered,
text
is
output
as
is.
In
double
quotaAons
variables
are
replaced
by
their
values
echo
$KBqty
KBs
;
echo
$KBqty.
KBs;
IdenAers
Names
of
variables,
classes,
or
funcAons
IdenAers
can
be
of
any
length
and
can
consist
of
leeers,
numbers,
and
underscores.
IdenAers
cannot
begin
with
a
digit.
In
PHP,
idenAers
are
case
sensiAve.
$Areqty
is
not
the
same
as
$TireQty
.
FuncAon
names
are
an
excepAon
to
this
rule;
their
names
can
be
used
in
any
case.
A variable can have the same name as a funcAon. This usage is confusing, however, and should be avoided. Also, you cannot create a funcAon with the same name as another funcAon.
149
1/27/13
Variable Types
Variables that have not been given a value, have been unset Certain built-in funcAons (such as database funcAons) return variables that have the type resource. PHP changes the variable type according to what is stored in it at any given Ame.
IntegerUsed for whole numbers Float (also called double)Used for real numbers StringUsed for strings of characters BooleanUsed for true or false values ArrayUsed to store mulAple data items ObjectUsed for storing instances of classes Two special types are also available: NULL and resource.
Variable
Variables
Variable
variables
enable
you
to
change
the
name
of
a
variable
dynamically.
A
variable
variable
works
by
using
the
value
of
one
variable
as
the
name
of
another.
For
example,
you
could
set
$varname
=
CDqty;
You
can
then
use
$$varname
in
place
of
$CDqty
.
For
example,
you
can
set
the
value
of
$CDqty
as
follows:
$$varname
=
5;
This
is
exactly
equivalent
to
$CDqty
=
5;
150
1/27/13
One
important
dierence
between
constants
and
variables
is
that
when
you
refer
to
a
constant,
it
does
not
have
a
dollar
sign
in
front
of
it.
As
well
as
the
constants
you
dene,
PHP
sets
a
large
number
of
its
own.
An
easy
way
to
obtain
an
overview
of
them
is
to
run
the
phpinfo()
funcAon:
phpinfo();
echo TIREPRICE;
This
funcAon
provides
a
list
of
PHPs
predened
variables
and
constants,
among
other
useful
informaAon.
One
other
dierence
between
variables
and
constants
is
that
constants
can
store
only
boolean,
integer,
oat,
or
string
data.
These
types
are
collecAvely
known
as
scalar
values.
Variable
Scope
The
six
basic
scope
rules
in
PHP
are
as
follows:
Built-in
superglobal
variables
are
visible
everywhere
within
a
script.
Constants,
once
declared,
are
always
visible
globally;
that
is,
they
can
be
used
inside
and
outside
funcAons.
Global
variables
declared
in
a
script
are
visible
throughout
that
script,
but
not
inside
funcAons
.
Variables
inside
funcAons
that
are
declared
as
global
refer
to
the
global
variables
of
the
same
name.
Variables
created
inside
funcAons
and
declared
as
staAc
are
invisible
from
outside
the
funcAon
but
keep
their
value
between
one
execuAon
of
the
funcAon
and
the
next.
Trying
to
assign
values
to
these
variables
which
are
the
result
of
expressions
will
cause
a
parse
error.
Variables created inside funcAons are local to the funcAon and cease to exist when the funcAon terminates.
151
1/27/13
Superglobals
The
complete
list
of
superglobals
is
as
follows:
$GLOBALS
An
array
of
all
global
variables
(Like
the
global
keyword,
this
allows
you
to
access
global
variables
inside
a
funcAonfor
example,
as
$GLOBALS[myvariable]
.)
$_SERVER
An
array
of
server
environment
variables
$_GET
An
array
of
variables
passed
to
the
script
via
the
GET
method
$_POST
An
array
of
variables
passed
to
the
script
via
the
POST
method
$_COOKIE
An
array
of
cookie
variables
$_FILES
An
array
of
variables
related
to
le
uploads
$_ENV
An
array
of
environment
variables
$_REQUEST
An
array
of
all
user
input
including
the
contents
of
input
including
$_GET
,
$_POST
,
and
$_COOKIE
(but
not
including
$_FILES
since
PHP
4.3.0)
$_SESSION
An
array
of
session
variables
Scope
cont.
<?php
$a
=
1;
include
'b.inc';
?>
/*$a
is
visible
to
b.inc
script
but
not
to
funcAons
inside
the
b.inc*/
152
1/27/13
<?php $a = 1; /* global scope */ funcAon test() { echo $a; /* reference to local scope variable */ } test(); //nothing will be printed ?> ///////////////////////////EX.2 <?php $a = 1; $b = 2; funcAon Sum() { global $a, $b; //now the global scope is referenced $b = $a + $b; //$b has 3 } Sum(); echo $b; ?> Using global keyword outside a funcAon is not an error. It can be used if the le is included from inside a funcAon.
Examples
153
1/27/13
Operators
ArithmeAc
operators
Operator
+
-
*
/
%
Name
AddiAon
SubtracAon
MulAplicaAon
Division
Modulus
Example
$a
+
$b
$a
-
$b
$a
*
$b
$a
/
$b
$a
%
$b
String
operators
.
Operator
+=
-=
*=
/=
%=
.=
ConcatenaAon
$a . $b Equivalent To $a = $a + $b $a = $a - $b $a = $a * $b $a = $a / $b $a = $a % $b $a = $a . $b
Unsepng does not change the value of $b (7) but does break the link between $a and the value 7 stored in memory.
154
1/27/13
Comparison
Operators
Operator
Name
Use
==
Equals
$a
==
$b
===
IdenAcal(equal
and
same
type)
$a
===
$b
!=
Not
equal
$a
!=
$b
!==
Not
idenAcal
$a
!==
$b
<>
Not
equal
(comparison
operator)
$a
<>
$b
<
Less
than
$a
<
$b
>
Greater
than
(comparison
operator)
$a
>
$b
<=
Less
than
or
equal
to
$a
<=
$b
>=
Greater
than
or
equal
to
$a
>=
$b
Logical
Operators
Operator
!
&&
||
and
or
xor
Name
NOT
AND
OR
AND
OR
XOR
Use
!$b
$a
&&
$b
$a
||
$b
$a
and
$b
$a
or
$b
$a
x
or
$b
Result
Returns
true
if
$b
is
false
and
vice
versa
Returns
true
if
both
$a
and
$b
are
true;
otherwise
false
Returns
true
if
either
$a
or
$b
or
both
are
true;
otherwise
false
Same
as
&&,
but
with
lower
precedence
Same
as
||,
but
with
lower
precedence
Returns
true
if
either
$a
or
$b
is
true,
and
false
if
they
are
both
true
or
both
false
155
1/27/13
Other operators
If you are suppressing warnings in this way, you need to write some error handling code to check when a warning has occurred. If you have PHP set up with the track_errors feature enabled in php.ini , the error message will be stored in the global variable $php_errormsg .
Other
operators
The
ExecuAon
Operator
(a
pair
of
backAcks
(``
))
PHP
aeempts
to
execute
whatever
is
contained
between
the
backAcks
as
a
command
at
the
servers
command
line.
The
value
of
the
expression
is
the
output
of
the
command.
156
1/27/13
Checks whether the variable is an array. (All the same funcAon) Checks whether the variable is a oat. (All the same funcAon) Checks whether the variable is an integer. Checks whether the variable is a string. Checks whether the variable is a boolean. Checks whether the variable is an object. Checks whether the variable is a resource. Checks whether the variable is null. Checks whether the variable is a scalar, that is, an integer, boolean, string, or oat.
is_object()
is_resource() is_null()
is_scalar()
157
1/27/13
Example
Ex:
$a
=
56;
echo
geZype($a).<br
/>;
//int
seZype($a,
double);
echo
geZype($a).<br
/>;
echo
isset($CDqty):
.isset($CDqty).<br
/>;
echo
isset($nothere):
.isset($nothere).<br
/>;
echo
empty($CDqty):
.empty($CDqty).<br
/>;
echo
empty($nothere):
.empty($nothere).<br
/>;
158
1/27/13
ReinterpreAng
Variables
Use
type
casAng
like
in
C/C++
Using
funcAons
The
following
three
funcAons
can
be
useful
for
this
task:
int
intval(mixed
var[,
int
base]);
oat
oatval(mixed
var);
string
strval(mixed
var);
Each accepts a variable as input and returns the variables value converted to the appropriate type. The intval() funcAon also allows you to specify the base for conversion when the variable to be converted is a string. (This way, you can convert, for example, hexadecimal strings to integers.)
CondiAonal
statements
if
elseif
else
statement
if
($CDqty
<
10)
{
$discount
=
0;
}
elseif
(($CDqty
>=
10)
&&
($CDqty
<=
49))
{
$discount
=
5;
}
elseif
(($CDqty
>=
50)
&&
($CDqty
<=
99))
{
$discount
=
10;
}
else
{
$discount
=
15;
}
159
1/27/13
while Loops
IteraAons
do...while
Loops
$num
=
100;
do{
echo
$num."<br
/>";
}while
($num
<
1
)
;
160
1/27/13
IteraAons
cont.
for
and
foreach
Loops
If,
for
example,
we
have
form
elds
with
names
such
as
name1
,
name2
,
name3
,
and
so
on,
we
can
process
them
like
this:
By dynamically creaAng the names of the variables, you can access each of the elds in foreach designed to work with arrays, to be seen later.
for ($i=1; $i <= $numnames; $i++){ $temp= name$i; echo $$temp.<br />; // or whatever processing you want to do }
161
1/27/13
162
1/27/13
163
1/27/13
When you want to read data from a le, you have many choices about how much of the le to read at a Ame.
Opening
a
File
Use
the
fopen()
funcAon.
We
need
to
specify
how
we
intend
to
use
it.
This
is
known
as
the
le
mode.
164
1/27/13
Mode Mode Name Meaning r r+ w w+ x x+ a a+ b Read Read Write Write CauAous write CauAous write Append Append Binary
File modes
Open the le for reading, beginning from the start of the le. Open the le for reading and wriAng, beginning from the start of the le. Open the le for wriAng, beginning from the start of the le. If the le already exists, delete the exisAng contents. If it does not exist, try to create it. Open the le for wriAng and reading, beginning from the start of the le. If the le already exists, delete the exisAng contents. If it does not exist, try to create it. Open the le for wriAng, beginning from the start of the le. If the le already exists, it will not be opened, fopen() will return false, and PHP will generate a warning. Open the le for wriAng and reading, beginning from the start of the le. If the le already exists, it will not be opened, fopen() will return false, and PHP will generate a warning. Open the le for appending (wriAng) only, starAng from the end of the exisAng contents, if any. If it does not exist, try to create it. Open the le for appending (wriAng) and reading, starAng from the end of the exisAng contents, if any. If it does not exist, try to create it. Used in conjuncAon with one of the other modes. You might want to use this mode if your le system dierenAates between binary and text les. Windows systems dierenAate; Unix systems do not. The PHP developers recommend you always use this opAon for maximum portability. It is the default mode. Used in conjuncAon with one of the other modes. This mode is an opAon only in Windows systems. It is not recommended except before you have ported your code to work with the b opAon.
Text
Assuming
we
want
to
save
the
computer
shop
order
to
a
le,
we
can
open
this
le
for
wriAng
with
the
following:
$fp
=
fopen($DOCUMENT_ROOT/../orders/orders.txt,
w);
Usually, we use two. The rst parameter should be the le we want to open.
The document root is accessed using the PHP built-in variable $_SERVER $DOCUMENT_ROOT=$_SERVER[DOCUMENT_ROOT]; This variable points at the base of the document tree on your web server. We use the .. to point to the parent directory of the document root directory. It is a good pracAce, for security reasons, to store sensiAve data outside the director root. we do not want this le to be web accessible except through the interface that we provide. If no path is specied, the le will be created or looked for in the same directory as the script itself.
165
1/27/13
The
fourth
parameter
is
also
opAonal.
The
fopen()
funcAon
allows
lenames
to
be
prexed
with
a
protocol
(such
as
hep://
)
and
opened
at
a
remote
locaAon.
If
fopen()
opens
the
le
successfully,
a
resource
that
is
eecAvely
a
handle
or
pointer
to
the
le
is
returned
and
should
be
stored
in
a
variablein
this
case,
$fp.
You
use
this
variable
to
access
the
le
when
you
actually
want
to
read
from
or
write
to
it.
You
dont
need
this
if
you
specify
the
protocol
in
the
le
name,
see
next
slide.
This capability can be disabled by turning o the allow_url_fopen direcAve in the php.ini le.
FTP example: $handle = fopen("pp://user:pass@DomainName.com/lename.txt", "w"); Remember that the domain names in your URL are not case sensiAve, but the path and lename might be. Important: you need to have permissions to open the le you need.
166
1/27/13
@ $fp = fopen($DOCUMENT_ROOT/../orders/orders.txt, ab); if (!$fp){ echo "<p><strong> Your order could not be processed at this Ame. " .Please try again later.</strong></p></body></html>"; exit; }
The
@
symbol
in
front
of
the
call
to
fopen()
tells
PHP
to
suppress
any
errors
resulAng
from
the
funcAon
call.
Usually,
its
a
good
idea
to
know
when
things
go
wrong,
but
in
this
case
were
going
to
deal
with
that
problem
elsewhere.
You
can
also
write
this
line
as
follows:
$fp
=
@fopen($DOCUMENT_ROOT/../orders/orders.txt,
a);
WriAng
to
a
File
We
can
use
either
of
the
funcAons
fwrite()
(le
write)
or
fputs()
(le
put
string);
fputs()
is
an
alias
to
fwrite().
You
call
fwrite()
in
the
following
way:
AlternaAvely
we
can
use
fwrite($fp,
$outputstring);
Writes
the
string
in
outputstring
to
le
fp
This funcAon writes the string contained in data to the le named in lename without any need for an fopen() (or fclose()) funcAon call. This funcAon is new in PHP5, and is a matched pair for le_get_contents() The ags and context opAonal parameters are most commonly used when wriAng to remote les using, for example, HTTP or FTP.
int le_put_contents ( string lename, string data [, int ags [, resource context]])
167
1/27/13
WriAng
to
a
le
cont.
The
funcAon
fwrite()
takes
three
parameters
The
third
one
is
opAonal.
The
prototype
for
fwrite()
is
int
fwrite
(
resource
handle,
string
string
[,
int
length])
The third parameter, length, is the maximum number of bytes to write. If this parameter is supplied, fwrite() will write string to the le pointed to by handle unAl it reaches the end of string or has wrieen length bytes, whichever comes rst. Ex: fwrite($fp, $outputstring, strlen($outputstring)); Third parameter commonly used when wriAng in binary mode because it helps avoid some cross- plauorm compaAbility issues.
File
Formats
Depending
on
who
is
using
the
stored
data
le.
Beeer
to
use
a
standard,
such
as
XML
Or
invent
one
for
your
self,
but
you
have
to
follow
it
and
announce
it
to
others.
$outputstring
=
$date.\t.$CDqty.
CDs
\t.$KBqty.
KBs\t. $LCDqty.
LCDs\t\$.$totalamount.\t.
$address.\n;
Closing
a
File
When
you
nish
using
a
le
close
it
with
fclose($fp);
Returns
true
if
the
le
was
successfully
closed
or
false
if
it
wasnt.
168
1/27/13
Ex:
ock($fp,
LOCK_EX);
//should
be
unlocked
in
ver.
5.3.2,
other
wise
the
close
would
unlock
ock($fp,
LOCK_UN);
array
fgetcsv
(
resource
fp,
int
length
[,
string
delimiter
[,
string
enclosure]])
This
funcAon
breaks
up
lines
of
les
when
you
have
used
a
delimiAng
character,
such
as
the
tab
character
(as
we
suggested
earlier)
or
a
comma
(as
commonly
used
by
spreadsheets
and
other
applicaAons).
$order
=
fgetcsv($fp,
100,
\t);
The
enclosure
parameter
species
what
each
eld
in
a
line
is
surrounded
by.
If
not
specied,
it
defaults
to
(a
double
quotaAon
mark).
169
1/27/13
fpassthru(),
dumps
the
contents
of
the
le
from
the
pointers
posiAon
onward
to
standard
output.
It
closes
the
le
when
it
is
nished.
The
le()
funcAon
is
idenAcal
to
readle()
except
that
instead
of
echoing
the
le
to
standard
output,
it
turns
it
into
an
array.
We
would
call
it
using
The
le_get_contents()
funcAon
is
idenAcal
to
readle()
except
that
it
returns
the
content
of
the
le
as
a
string
instead
of
outpupng
it
to
the
browser.
$learray
=
le($DOCUMENT_ROOT/../orders/orders.txt);
Each
line
of
the
le
is
stored
in
a
separate
element
of
the
array
$fp
=
fopen($DOCUMENT_ROOT/../orders/orders.txt,
rb);
fpassthru($fp);
This code reads a single character at a Ame from the le using fgetc() and stores it in $char It also does a liele processing to replace the text end-of-line characters (\n ) with HTML line breaks (<br /> ). fgetc() returns the EOF character. You need to test feof() again ager youve read the character because you dont want to echo the EOF to the browser. string fread(resource fp, int length); Reads up to length bytes or to the end of the le, whichever comes rst.
170
1/27/13
try{}catch(){}
<?php
try
{
throw
new
ExcepAon("A
terrible
error
has
occurred",
42);
}
catch
(ExcepAon
$e)
{
echo
"ExcepAon
".
$e->getCode().
":
".
$e->getMessage()."<br
/>."
in
".
$e->getFile().
"
on
line
".
$e->getLine().
"<br
/>";
}
?>
############################################ ##########################
getCode()Returns the code as passed to the constructor getMessage()Returns the message as passed to the constructor getFile()Returns the full path to the code le where the excepAon was raised getLine()Returns the line number in the code le where the excepAon was raised getTrace()Returns an array containing a backtrace where the excepAon was raised getTraceAsString()Returns the same informaAon as getTrace, formaeed as a string __toString()Allows you to simply echo an ExcepAon object, giving all the informaAon from the above methods
171
1/27/13
To
check
whether
a
le
exists
without
actually
opening
it.
Determining
How
Big
a
File
Is:
lesize()
The
nl2br()
funcAon
converts
the
\n
characters
in
the
output
to
HTML
line
breaks
(<br
/>).
unlink($DOCUMENT_ROOT/../orders/orders.txt);
Returns
false
if
the
le
could
not
be
deleted.
This
situaAon
typically
occurs
if
the
permissions
on
the
le
are
insucient
or
if
the
le
does
not
exist.
The rewind($fp) funcAon resets the le pointer to the beginning of the le. The pell($fp) funcAon reports how far into the le the pointer is in bytes. The funcAon fseek() to set the le pointer to some point within the le. Its prototype is
int fseek ( resource fp, int oset [, int whence]) sets the le pointer fp at a point starAng from whence and moving oset bytes into the le. The opAonal whence parameter defaults to the value SEEK_SET , which is eecAvely the start of the le. The other possible values are SEEK_CUR (the current locaAon of the le pointer) and SEEK_END (the end of the le).
upload_max_le size
2M 8M
post_max_size .
172
1/27/13
You can choose whatever name you like for the le, but you should keep it in mind because you will use this name to access your le from the receiving PHP script.
173
1/27/13
We should save the le from the temporary directory (move, copy, or rename), otherwise, it will be deleted when the script ends.
174
1/27/13
// Does the le have the right MIME type? if ($_FILES[userle][type] != text/plain) { echo Problem: le is not plain text; exit; } // put the le where wed like it $uple = /uploads/.$_FILES[userle][name] ; if (is_uploaded_le($_FILES[userle][tmp_name])) { if (!move_uploaded_le($_FILES[userle][tmp_name], $uple)) { echo Problem: Could not move le to des)na)on directory; exit; } } else { echo Problem: Possible le upload aZack. Filename: ; echo $_FILES[userle][name]; exit; } echo File uploaded successfully<br><br>; // remove possible HTML and PHP tags from the le's contents $contents = le_get_contents($uple); $contents = strip_tags($contents); le_put_contents($_FILES['userle']['name'], $contents); // show what was uploaded echo '<p>Preview of uploaded le contents:<br/><hr/>'; echo nl2br($contents); echo <br/><hr/>;
175
1/27/13
This
funcAon
will
strip
o
any
directory
paths
that
are
passed
in
as
part
of
the
lename,
which
is
a
common
aeack
that
is
used
to
place
a
le
in
a
dierent
directory
on
your
server.
<?php
$path
=
"/home/hepd/html/index.php";
$le1
=
basename($path);
$le2
=
basename($path,
".php");
print
$le1
.
"<br/>";
//
the
value
of
$le1
is
"index.php"
print
$le2
.
"<br/>";
//
the
value
of
$le2
is
"index
When
the
directory
is
open,
you
can
read
a
lename
from
it
by
calling
readdir($dir)
while(false
!==
($le
=
readdir($dir)))
When
nished
reading
from
a
directory,
call
closedir($dir)
176
1/27/13
As
an
alternaAve
to
these
funcAons,
you
can
use
the
dir
class
provided
by
PHP.
It
has
the
properAes
handle
and
path,
and
the
methods
read(),
close(),
and
rewind(),
which
perform
idenAcally
to
the
nonclass
alternaAves.
<?php
$dir
=
dir("/uploads/");
echo
"<p>Handle
is
$dir->handle</p>";
echo
"<p>Upload
directory
is
$dir->path</p>";
echo
'<p>Directory
Lis)ng:</p><ul>';
while(false
!==
($le
=
$dir->read()))
//strip
out
the
two
entries
of
.
and
..
if($le
!=
"."
&&
$le
!=
"..")
{
echo
"<li>$le</li>";
}
echo
'</ul>';
$dir->close();
?>
The
disk_free_space($path)
funcAon
returns
the
number
of
bytes
free
on
the
disk
(Windows)
or
the
le
system
(Unix)
on
which
the
directory
is
located.
CreaAng
and
removing
directories
$oldumask
=
umask(0);
//change
umask.
The
inverted
umask
is
ANDed
with
permissions
of
the
mkdir
mkdir(c:\\tmp\\tes)ng,
0777);
//create
directory
with
permisions
of
(0777
AND
invert(umask))
umask($oldumask);
rmdir(c:\\tmp\\tes)ng);
//remove
directory
177
1/27/13
Arrays
Numerically
Indexed
Arrays
indices
start
at
zero
by
default
$products
=
array(
CD,
KB,
LCD
);
range()
funcAon
can
be
used
to
automaAcally
create
the
array
of
an
ascending
sequence
$numbers
=
range(1,10);
//An
array
called
numbers
with
//elements
ranging
from
1
to
10
$odds
=
range(1,
10,
2);
//
an
opAonal
third
parameter
that
//allows
sepng
the
step
size
between
values.
$leZers
=
range(a,
z);
//
can
also
be
used
with
characters
Arrays
cont.
Accessing
Array
Contents
Type
$products[0]
,
$products[1]
,
and
$products[2]
to
use
the
contents
of
the
$products
array.
change
array
elements
contents
by
using
the
=
operator.
We
can
use
loops
$products[0]
=
CDs;
for
($i
=
0;
$i<3;
$i++)
{
echo
$products[$i]."
";
}
Or
foreach
($products
as
$current)
{
echo
$current."
";
}
To
add
a
new
elementLaptops
to
the
end
of
the
array,
giving
a
total
of
four
elements:
$products[3]
=
Laptops;
178
1/27/13
The
following
code
creates
an
array
with
product
names
as
keys
and
prices
as
values:
$prices
=
array(CD=>100,
KB=>10,
LCD=>4);
We
can
access
the
contents
using
the
variable
name
prices
array
as
$prices[CD]
,
$prices[KB]
,
and
$prices[LCD]
.
The
following
code
creates
the
same
$prices
array
$prices
=
array(
CD=>100
);
$prices[KB]
=
10;
$prices[LCD]
=
4;
Or
directly
as:
$prices[CD]
=
100;
$prices[KB]
=
10;
$prices[LCD]
=
4;
Using Loops
179
1/27/13
Using
Loops
Cannot
use
a
simple
counter
in
a
loop
to
work
with
the
array
it
has
been
used
in
the
previous
example,
The
loop
can
be
used
exactly
or
by
incorporaAng
the
keys
as
for
foreach
This
funcAon
returns
the
current
element
in
an
array
and
makes
the
next
element
the
current
one.
while
($element
=
each($prices))
{
echo
$element['key'];
echo
"
";
echo
$element['value'];
echo
"<br
/>";
}
When
you
call
each()
,
it
gives
you
an
array
with
four
values
and
the
four
indices
to
the
array
locaAons.
The
locaAons
key
and
0
contain
the
key
of
the
current
element,
and
the
locaAons
value
and
1
contain
the
value
of
the
current
element.
If
you
want
to
use
the
array
twice
in
the
same
script,
you
need
to
set
the
current
element
back
to
the
start
of
the
array
using
the
funcAon
reset()
.
reset($prices);
MulAdimensional
Arrays
$products
=
array(
array(
CDS,
CDs,
100
),
array(
KBS,
Keyboards,
10
),
array(
LCD,
LCDs,
4
)
);
Or
for ($row = 0; $row < 3; $row++) { for ($column = 0; $column < 3; $column++) { echo '|'.$products[$row][$column]; } echo '|<br />'; }
$products = array( array( Code => CDS, Descrip)on => CDs, Price => 100 ), array( Code => KBS, Descrip)on => Keyboards, Price => 10 ), array( Code => LCDS, Descrip)on => LCDs, Price =>4 ) ); for ( $row = 0; $row < 3; $row++){ while ( list( $key, $value ) = each( $products[$row])){ echo |$value; } echo |<br />; }
180
1/27/13
SorAng Arrays
$products = array( , KBs, LCD ); sort($products); The array will be sorted into ascending alphabeAcal asort() to order the array according to the value of each element. ksort() to sort the array by key rather than value. $prices = array( Tires=>100, Oil=>10, Spark Plugs=>4 ); asort($prices);
When using an array with descripAve keys to store items and their prices, we use the funcAon
The
rsort()
funcAon
sorts
a
single-dimensional
numerically
indexed
array
into
descending
order.
The
arsort()
funcAon
sorts
a
one-dimensional
array
into
descending
order
using
the
value
of
each
element.
The
krsort()
funcAon
sorts
a
one-dimensional
array
into
descending
order
using
the
key
of
each
element.
The
funcAon
usort()
sorts
an
array
depending
on
a
custom
user
dened
funcAon
funcAon
compare($x,
$y)
{
if
($x[1]
==
$y[1])
{
return
0;
}
else
if
($x[1]
<
$y[1])
{
return
-1;
}
else
{
return
1;
}
}
usort($products,
'compare');
Similar to asort() , uasort() used when custom sorAng a non-numerically indexed array by value. Similar to ksort() , uksort() should be used when custom sorAng a non-numerically indexed array by key.
Can be controlled using the current(), next(), each(), prev(), reset(), and end() Calling current( $array_name ) or pos($array_name) directly ager array iniAalizaAon returns the rst element. Calling each($array_name) returns the current element before advancing the pointer. Calling next($array_name) advances the pointer and then returns the new current element.
When creaAng a new array, the current pointer is iniAalized to point to the rst element in the array. Calling either next() or each() advances the pointer forward one element.
The
prev()
funcAon
moves
the
current
pointer
back
one
and
then
returns
the
new
current
element.
The
reset()
funcAon
returns
the
pointer
to
the
rst
element
in
the
array.
The
end($array_name
)
funcAon
sends
the
pointer
to
the
end
of
the
array.
The
funcAon
explode()
split
up
each
line
so
that
you
can
apply
some
processing
and
formapng
before
prinAng.
The
output
from
this
script
is
The
explode
funcAon
has
the
following
prototype:
The
array_count_values()
funcAon
is
more
complex.
If
you
call
array_count_values($array)
,
this
funcAon
counts
how
many
Ames
each
unique
value
occurs
in
the
array
named
$array
.
array
explode(string
separator,
string
string
[,
int
limit])
181
1/27/13
Ex2:
funcAon
my_mulAply(&$value,
$key,
$factor){
$value
*=
$factor;
}
array_walk(&$array,
my_mulAply,
3);
Object-Oriented
PHP
class
classname
{
public
$aeribute1;
public
$aeribute2;
funcAon
__construct($param)
{
$this->$aeribute1=$param;
$aeribute2=$param;
echo
"Constructor
called
with
parameter
".$param."<br
/>";
}
funcAon
__destruct(){}
funcAon
operaAon1(){}
funcAon
operaAon2($param1,
$param2){}
}
$a
=
new
classname("First");
//prints:Constructor
called
with
parameter
First
$b
=
new
classname("Second");
//prints:Constructor
called
with
parameter
Second
$c
=
new
classname();
//prints:Constructor
called
with
parameter
182
1/27/13
Accessor
funcAons
class
classname
{
public
$aeribute;
}
$a
=
new
classname();
$a->aeribute
=
"value";
echo
$a->aeribute;
//bad
pracAce,
use
accessor
funcAons
##############################################################
class
classname
{
public
$aeribute1;
public
$aeribute2;
funcAon
__get($name)
{
if(
($name="aeribute1))
return
$this->$aeribute1;
else
return
$this->$aeribute2;
}
funcAon
__set
($name,
$value)
{
if(
($name="aeribute1")
&&
($value
>=
0)
&&
($value
<=
100)
)
$this->aeribute
=
$value;
}
}
$a=new
classname();
$a->$aZribute1
=
5;
//
will
call
the
__set
func)on
$b=$a->$aZribute2;
//will
call
the
__get
func)on
class A { public $aZribute1; func)on opera)on1(){} } class B extends A { public $aZribute2; func)on opera)on2(){} } PHP does not support mul)ple inheritance. ##################################################### interface Displayable { func)on display(); } class webPage implements Displayable { func)on display(){ } } We have to implement all interface func)ons
183
1/27/13
class Math { staAc funcAon squared($input) { return $input*$input; } } echo Math::squared(8); ################################### interface a { const b = 'Interface constant'; } echo a::b; #################################### Prevent method from being override class A { public $aeribute = "default value"; nal funcAon operaAon() { echo "Something<br />"; echo "The value of \$aeribute is ". $this->aeribute."<br />"; } } Prevent class from being inherited nal class A{...}
Example, home.php
184
1/27/13
Sepng
Cookies
Use
setcookie()
<?php
setcookie('avor','chocolate
chip');
?>
Cookies
are
sent
with
the
HTTP
headers,
so
if
youre
not
using
output
buering,
setcookie(
)
must
be
called
before
any
output
is
generated.
Sessions
HTTP
is
a
stateless
protocol.
This
means
that
the
protocol
has
no
built-in
way
of
maintaining
state
between
two
transacAons.
When
a
user
requests
one
page,
followed
by
another,
HTTP
does
not
provide
a
way
for
you
to
tell
that
both
requests
came
from
the
same
user.
The idea of session control is to be able to track a user during a single session on a website. Sessions in PHP are driven by a unique session ID, a cryptographically random number.
It works by creaAng a unique idenAcaAon(UID) number for each visitor and storing variables based on this ID. This helps to prevent two users' data from gepng confused with one another when visiAng the same webpage.
185
1/27/13
Sessions
cont.
Before
using
sessions,
start
it
session_start();
//
start
up
your
PHP
session!
This
registers
the
user's
session
with
the
server,
allow
you
to
start
saving
user
informaAon
and
assign
a
UID
(unique
idenAcaAon
number)
for
that
user's
session.
When
you
want
to
store
user
data
in
a
session
use
the
$_SESSION
$_SESSION['views']
=
1;
//
store
session
data
echo
"Pageviews
=
".
$_SESSION['views'];
//retrieve
data
if(isset($_SESSION['views']))
$_SESSION['views']
=
$_SESSION['views']+
1;
else
$_SESSION['views']
=
1;
To check if a session already have a value, use isset. Use unset to clear it
we
can
also
completely
destroy
the
session
enArely
by
calling
the
session_destroy
funcAon.
session_destroy();
AuthenAcaAons
There
are
two
good
ways
for
authenAcaAon:
HTTP
basic
authenAcaAon
Basic
authenAcaAon
overcomes
the
caching
problem,
but
the
browser
sAll
sends
the
password
to
the
server
with
every
request
Sessions
Session
control
overcomes
both
of
these
problems.
186
1/27/13
It is supported by web browsers and requested form scripts. Basic authenAcaAon transmits a users name and password in plain text, so it is not very secure. When combining basic authenAcaAon with SSL and digital cerAcates, all parts of a web transacAon can be protected by strong security
For an HTTP authenAcaAon script to run on Apache using PHP as an Apache module or on IIS using PHP as an ISAPI module, it needs to detect the server type and behave slightly dierently.
187
1/27/13
<?php // if we are using IIS, we need to set // $_SERVER['PHP_AUTH_USER'] and // $_SERVER['PHP_AUTH_PW'] if ((substr($_SERVER['SERVER_SOFTWARE'], 0, 9) == 'Microsog') && (!isset($_SERVER['PHP_AUTH_USER'])) && (!isset($_SERVER['PHP_AUTH_PW'])) && (substr($_SERVER['HTTP_AUTHORIZATION'], 0, 6) == 'Basic ') ) { list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6))); } // Replace this if statement with a database query or similar if (($_SERVER['PHP_AUTH_USER'] != 'user') || ($_SERVER['PHP_AUTH_PW'] != 'pass')) { // visitor has not yet given details, or their // name and password combinaAon are not correct header('WWW-AuthenAcate: Basic realm="Realm-Name"'); if (substr($_SERVER['SERVER_SOFTWARE'], 0, 9) == 'Microsog') { header('Status: 401 Unauthorized'); } else { header('HTTP/1.0 401 Unauthorized'); } echo "<h1>Go Away!</h1> <p>You are not authorized to view this resource.</p>"; } else { // visitor has provided correct details echo "<h1>Here it is!</h1> <p>I bet you are glad you can see this secret page.</p>"; } ?>
188
1/27/13
.htpass
The
Password
File
Stores
Usernames
and
Each
Users
Encrypted
Password
user1:0nRp9M80GS7zM
user2:nC13sOTOhp.ow
user3:yjQMCPWjXFTzU
user4:LOmlMEi/hAme2
To create it, you use a small program called htpasswd that comes in the Apache distribuAon.
or
The
opAonal
m
,
d
,
p
,
or
s
switches
can
be
used
if
you
want
to
specify
which
encrypAon
algorithm
(including
no
encrypAon)
you
would
like
to
use.
The
b
switch
tells
the
program
to
expect
the
password
as
a
parameter
rather
than
prompt
for
it.
htpasswd
-bc
/home/book/.htpass
user1
pass1
htpasswd
-b
/home/book/.htpass
user2
pass2
htpasswd
-b
/home/book/.htpass
user4
pass3
htpasswd
-b
/home/book/.htpass
user4
pass4
189
1/27/13
We
will
assume
the
use
of
MySQL
that
have
the
database
auth
containing
a
table
holding
the
authorized
users
for
our
example
website.
This
database
can
be
created
using
the
following
SQL
script.
use
auth;
create
table
authorized_users
(name
varchar(20),
password
varchar(40),
primary
key
(name)
);
insert
into
authorized_users
values
('username',
'password');
insert
into
authorized_users
values
('testuser',
sha1('password'));
grant
select
on
auth.*
to
'webauth'
idenAed
by
'webauth';
ush
privileges;
190
1/27/13
EncrypAng
Passwords
Storing
the
passwords
as
plain
text
is
an
unnecessary
risk.
A
one-way
hashing
algorithm
can
provide
beeer
security
with
very
liele
extra
eort.
PHP
provides
a
number
of
one-way
hash
funcAons.
The
oldest
and
least
secure
is
the
Unix
Crypt
algorithm,
provided
by
the
funcAon
crypt()
.
The
Message
Digest
5
(MD5)
algorithm,
implemented
in
the
funcAon
md5(),
is
stronger.
Stronger
yet
is
the
Secure
Hash
Algorithm
1
(SHA-1.)
which
provides
a
strong,
one-way
cryptographic
hash
funcAon.
The
prototype
for
this
funcAon
is
string
sha1
(
string
str
[,
bool
raw_output])
Given
the
string
str
,
the
funcAon
will
return
a
pseudo-random
40- character
string.
If
you
set
raw_output
to
be
true
,
you
will
instead
get
a
20-character
string
of
binary
data.
191
1/27/13
ConnecAng
to
DB
The
PHP
library
for
connecAng
to
MySQL
is
called
mysqli
(the
i
stands
for
improved).
In
PHP,
you
can
use
either
an
object-oriented
or
procedural
syntax.
@
$db
=
new
mysqli('localhost',
'bookorama',
'bookorama123',
'books');
Returns
an
object
@
$db
=
mysqli_connect('localhost',
'bookorama',
'bookorama123',
'books');
Returns
a
variable
of
type
resource
You
will
need
to
pass
this
resource
in
to
all
the
other
mysqli
funcAons.
This
is
very
similar
to
the
way
the
le-handling
funcAons,
such
as
fopen()
,
work.
In
either
method
(OOP
or
funcAon),
the
result
of
an
aeempt
for
a
connecAon
can
be
checked
for
errors
as
follows:
if
(mysqli_connect_errno())
{
echo
'Error:
Could
not
connect
to
database.
Please
try
again
later.';
exit;
}
Number of simultaneous connecAons to MySQL is congured through max_connecAons parameter in the le my.conf. Another related Apache parameter is the MaxClient in the hepd.conf le. This tells the server to reject new connecAon requests that exceeds MaxClient instead of allowing machine resources to be completely used up at busy Ames or when sogware has crashed.
ConnecAng
to
DB
It
is
a
good
pracAce
to
have
your
connecAon
account
info
in
a
separated
le
also
directory.
ConnecAng
to
a
mysql
DB
is
done
using
the
funcAon
mysqli()
<?php
//
this
is
dbconnect.php
$db_server
=
'localhost';
$db_user_name
=
ahmad';
$db_password
=
password';
$db_name
=
'somedb;
?>
<?php
include('../code/dbconnect.php);
$conn
=
@new
mysqli($db_server,
$db_user_name,
$db_password,
$db_name);
//
etc
?>
192
1/27/13
or as
To
actually
perform
the
query,
you
can
use
the
mysqli_query()
funcAon.
Before
doing
this,
however,
its
a
good
idea
to
set
up
the
query
you
want
to
run:
You
can
now
run
the
query:
$query
=
"select
*
from
books
where
".$searchtype."
like
'%".$searchterm."%'";
$result
=
$db->query($query);
$result
=
mysqli_query($db,
$query);
mysqli_select_db(db_resource, db_name)
This
funcAon
takes
each
row
from
the
result
set
and
returns
the
row
as
an
array,
with
each
key
an
aeribute
name
and
each
value
the
corresponding
value
in
the
array:
Or
you
can
use
a
procedural
approach:
$row
=
mysqli_fetch_assoc($result);
You
could
also
fetch
a
row
into
an
object
with
the
mysqli_fetch_object()
funcAon:
$row
=
$result->fetch_object();
The aeribute values are listed in each of the array values $row[0] , $row[1] , and so on. (The mysqli_fetch_array() funcAon allows you to fetch a row as either or both kinds of array.) or
$row = mysqli_fetch_object($result);
You can then access each of the aeributes via $row->)tle , $row->author , and so on.
193
1/27/13
or
mysqli_free_result($result);
or
mysqli_close($db);
to close a database connecAon. Using this command isnt strictly necessary because the connecAon will be closed when a script nishes execuAon anyway.
194
1/27/13
<html> <head> <)tle>Book-Store- New Book Entry</)tle> </head> <body> <h1>Book-Store- New Book Entry</h1> <form ac)on="insert_book.php" method="post"> <table border="0"> <tr> <td>ISBN</td> <td><input type="text" name="isbn" maxlength="13" size="13"></td> </tr> <tr> <td>Author</td> <td> <input type="text" name="author" maxlength="30" size="30"></td> </tr> <tr> <td>Title</td> <td> <input type="text" name=")tle" maxlength="60" size="30"></td> </tr> <tr> <td>Price $</td> <td><input type="text" name="price" maxlength="7" size="7"></td> </tr> <tr> <td colspan="2"><input type="submit" value="Register"></td> </tr> </table> </form> </body> </html>
newbook.html
<html>
<head> <)tle>Book Entry Results</)tle> </head> <body> <h1>Book Entry Results</h1> <?php // create short variable names $isbn=$_POST['isbn']; $author=$_POST['author']; $)tle=$_POST[')tle']; $price=$_POST['price']; if (!$isbn || !$author || !$)tle || !$price) { echo "You have not entered all the required details.<br />" ."Please go back and try again."; exit; } if (!get_magic_quotes_gpc()) { $isbn = addslashes($isbn); //Returns a string with backslashes before characters that need to be quoted in database queries etc. //These characters are single quote ('), double quote ("), backslash (\) and NUL (the NULL byte). // for example when adding the string to insert the name O'reilly $author = addslashes($author); $)tle = addslashes($)tle); $price = doubleval($price); } @ $db = new mysqli('localhost', dbUsername', dbpass', dbname'); if (mysqli_connect_errno()) { echo "Error: Could not connect to database. Please try again later."; exit; } $query = "insert into books values('".$isbn."', '".$author."', '".$)tle."', '".$price."')"; $result = $db->query($query); if ($result) { echo $db->aected_rows." book inserted into database."; //aected_rows returns the number of rows aected by the insert //use it in INSERT, UPDATE, and DELETE statements } else { echo "An error has occurred. The item was not added."; } $db->close();
insert_book.php
195
1/27/13
Useful for speeding up execuAon when you are performing large numbers of the same query with dierent data. They also protect against SQL injecAon-style aeacks.
The purpose of bind_param() is to tell PHP which variables should be subsAtuted for the quesAon marks. The rst parameter is a format string. The value you are passing here (sssd ) means that the four parameters are a string, a string, a string, and a double, respecAvely. Other possible characters in the format string are i for integer and b for blob (Binary Large OBject such as images in a database). Ager this parameter, you should list the same number of variables as you have quesAon marks in your statement. They will be subsAtuted in this order.
196
1/27/13
XML IntroducAon
- SGML is a meta-markup language - Developed in the early 1980s; ISO std. In 1986 - HTML was developed using SGML in the early 1990s - specically for Web documents - Two problems with HTML: 1. Fixed set of tags and aeributes - User cannot dene new tags or aeributes - So, the given tags must t every kind of document, and the tags cannot connote any parAcular meaning 2. There are few restricAons on arrangement or order of tag appearance in a document - One soluAon to the rst of these problems: Let each group of users dene their own tags (with implied meanings) (i.e., design their own HTMLs using SGML)
197
1/27/13
- We will refer to an XML-based markup language as a tag set - Strictly speaking, a tag set is an XML applica5on, but that terminology can be confusing - An XML processor is a program that parses XML documents and provides the parts to an applicaAon - A document that uses an XML-based markup language is an XML document 7.2 The Syntax of XML - The syntax of XML is in two disAnct levels: 1. The general low-level rules that apply to all XML documents 2. For a parAcular XML tag set, either a document type deniAon (DTD) or an XML schema
198
1/27/13
- XML names: - Must begin with a letter or an underscore - They can include digits, hyphens, and periods - There is no length limitation - They are case sensitive (unlike HTML names)
199
1/27/13
- Aeributes are not used in XML the way they are in HTML - In XML, you ogen dene a new nested tag to provide more info about the content of a tag - Nested tags are beeer than aeributes, because aeributes cannot describe structure and the structural complexity may grow - Aeributes should always be used to idenAfy numbers or names of elements (like HTML id and name aeributes)
200
1/27/13
"
-
When
the
XML
parser
encounters
a
reference
to
a
non-binary
enAty,
the
enAty
is
merged
in
-
En5ty
names:
-
No
length
limitaAon
-
Must
begin
with
a
leeer,
a
dash,
or
a
colon
-
Can
include
leeers,
digits,
periods,
dashes,
underscores,
or
colons
-
A
reference
to
an
enAty
has
the
form:
&enAty_name;
-
Predened
enAAes
(as
in
XHTML):
< > & " ' < > & " '
201
1/27/13
202
1/27/13
from
to
date
re
body
- Leaf nodes specify data types, most often PCDATA, which is an acronym for parsable character data - Data type could also be EMPTY (no content) and ANY (can have any content) - Example of a leaf declaration:
<!ELEMENT name (#PCDATA)>
203
1/27/13
SHOW planes.dtd
204
1/27/13
- Internal DTDs
<!DOCTYPE root_name [ ]>
- External DTDs
<!DOCTYPE XML_doc_root_name SYSTEM DTD_file_name>
Namespaces
When
a
tag
set
is
available
and
appropriate
for
a
parAcular
XML
document
or
class
of
documents,
it
is
beeer
to
use
it
than
to
invent
a
new
collecAon
of
element
types.
For
example
if
we
want
to
dene
a
markup
language
for
furniture
catalog
with
<chair>,
<sofa>,
and
<table>
tags.
Sogware
systems
that
process
XML
documents
must
be
capable
of
unambiguously
recognizing
the
element
names
in
those
documents.
The
soluAon
is
to
use
XML
namespace
CollecAon
of
element
and
aeribute
names
used
in
XML
documents.
The
name
of
a
namespace
usually
has
the
form
of
a
uniform
resource
idenAer
(URI)
However,
the
tag
<table>
is
used
in
XHTML
205
1/27/13
Declaring
Namespaces
Namespace
for
the
elements
and
aeributes
of
the
hierarchy
rooted
at
a
parAcular
element
is
declared
as
the
value
of
the
aeribute
xmlns.
The
form
of
a
namespace
declaraAon
for
an
element
is
<element_name
xmlns[:prex]
=
URI>
Ex:
for
xhtml
<html
xmlns
=
hep://www.w3.org/1999/xhtml>
The prex, if included, is the name that must be aeached to the names in the declared namespace. If the prex is not included, the namespace is the default for the document. most URIs are too long URI includes characters that are invalid in XML <WebCourse xmlns:webc = hep://eng.najah.edu/ce/webc> Within the WebCourse element, including all of its children elements, the names from the given namespace must be prexed with webc, as in the following element
One of the namespaces can be specied as the default by omipng the prex in any namespace declaraAon.
206
1/27/13
XML
Schemas
Problems
with
DTDs:
XML
Schema
has
Two
purposes:
Syntax
is
dierent
from
XML
-
cannot
be
parsed
with
an
XML
parser.
DTDs
do
not
allow
specicaAon
of
parAcular
kinds
of
data
Specify
the
structure
of
its
instance
XML
documents
Specify
the
data
type
of
every
element
and
aeribute
of
its
instance
XML
documents
An
XML
schema
is
an
XML
document,
so
it
can
be
parsed
with
an
XML
parser.
The
content
of
a
specic
element
can
be
required
to
be
any
one
of
44
dierent
data
types.
The
user
can
dene
new
types
with
constraints
on
exis)ng
data
types.
For
example,
a
numeric
data
value
can
be
required
to
have
exactly
seven
digits.
Dening
a
Schema
XML
schemas
are
namespace
centric.
Schemas
themselves
are
wrieen
with
the
use
of
a
collecAon
of
tags,
or
a
vocabulary,
from
a
namespace
that
is,
in
eect,
a
schema
of
schemas.
The
name
of
this
namespace
is
hep://www.w3.org/2001/XMLSchema.
Contains
many
elements
such
as
element,
schema,
sequence,
and
string.
Every
schema
has
schema
as
its
root
element
with
three
aeributes.
Namespace
of
the
schema
elements
Namespace
of
the
document
instances
elements
Level
of
the
namespace
207
1/27/13
The
name
of
every
top-level
(not
nested)
element
that
appears
in
a
schema
is
placed
in
the
target
namespace,
which
is
specied
by
assigning
a
namespace
to
the
target
namespace
aeribute:
targetNamespace
=
hep://cs.uccs.edu/planeSchema
xmlns = "hep://cs.uccs.edu/planeSchema" <!-- Next, specify non-top-level elements to be in the target namespace --> elementFormDefault = "qualied">
208
1/27/13
Example
NoAce that the name schema in this tag name does not need to be prexed because its namespace is now the default. However, all of the names being created by this schema must be prexed, both in the schema and in its instances.
<planes xmlns = "hep://cs.uccs.edu/planeSchema" xmlns:xsi =hep://www.w3.org/2001/XMLSchema- instance" xsi:schemaLocaAon = "hep://cs.uccs.edu/planeSchema planes.xsd" >
209
1/27/13
Simple (strings only, no aeributes and no nested elements) Complex (can have aeributes and nested elements) PrimiAve: string, Boolean, oat, Derived: byte, decimal, posiAveInteger,
User-dened (derived) data types specify constraints on an exis5ng type (the base type) Constraints are given in terms of facets totalDigits, maxInclusive, etc.
- Data Type Categories 1. Simple (strings only, no attributes and no nested elements) 2. Complex (can have attributes and nested elements)
210
1/27/13
- XMLS defines 44 data types - Primitive: string, Boolean, float, - Derived: byte, decimal, positiveInteger, - User-defined (derived) data types specify constraints on an existing type (the base type) - Constraints are given in terms of facets (totalDigits, maxInclusive, etc.) - Both simple and complex types can be either named or anonymous - DTDs define global elements (context is irrelevant) - With XMLS, context is essential, and elements can be either: 1. Local, which appears inside an element that is a child of schema, or 2. Global, which appears as a child of schema
- An instance could have: - Element values can be constant, specified with the fixed attribute
fixed = "three-toed <bird> Yellow-bellied sap sucker </bird>
- User-Defined Types - Defined in a simpleType element, using facets specified in the content of a restriction element - Facet values are specified with the value attribute
211
1/27/13
- There are several categories of complex types, but we discuss just one, element-only elements - Element-only elements are defined with the complexType element - Use the sequence tag for nested elements that must be in a particular order - Use the all tag if the order is not important
- Nested elements can include attributes that give the allowed number of occurrences (minOccurs, maxOccurs, unbounded) SHOW planes.xsd and planes1.xml - We can define nested elements elsewhere
<xsd:element name = "year" > <xsd:simpleType> <xsd:restriction base = "xsd:decimal" > <xsd:minInclusive value = "1990" /> <xsd:maxInclusive value = "2003" /> </xsd:restriction> </xsd:simpleType> </xsd:element>
212
1/27/13
- Validating Instances of XML Schemas - One validation tool is xsv, which is available from:
http://www.ltg.ed.ac.uk/~ht/xsv-status.html
- Note: If the schema is incorrect (bad format), xsv reports that it cannot find the schema
213
1/27/13
- An example:
<?xml version = "1.0" encoding = "utf-8 ?> <!-- xslplane.xml --> <?xml-stylesheet type = "text/xsl" href = "xslplane.xsl" ?> <plane> <year> 1977 </year> <make> Cessna </make> <model> Skyhawk </model> <color> Light blue and white </color> </plane>
- If a style sheet matches the root element of the XML document, it is matched with the template:
<xsl:template match = "/>
- XSLT documents include two different kinds of elements, those with content and those for which the content will be merged from the XML doc - Elements with content often represent HTML elements
<span style = "font-size: 14"> Happy Easter! </span>
214
1/27/13
215
1/27/13
216
1/27/13
217