Вы находитесь на странице: 1из 23

WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V

UNIT V
Building Web Applications-Cookies-Sessions-Open Source Eniron!ent-"#"-$%S&'
Building Web Applications
A web application is an application that is accessed over a network such as the Internet or an
intranet. The term may also mean a computer software application that is hosted in a browser-
controlled environment (e.g. a Java applet)
citation needed!
or coded in a browser-supported language
(such as Java"cript# combined with a browser-rendered markup language like $T%&) and reliant
on a common web browser to render the application e'ecutable.
(eb applications are popular due to the ubi)uity of web browsers# and the convenience of using
a web browser as a client# sometimes called a thin client. The ability to update and maintain web
applications without distributing and installing software on potentially thousands of client
computers is a key reason for their popularity# as is the inherent support for cross-platform
compatibility. *ommon web applications include webmail# online retail sales# online auctions#
wikis and many other functions.
History
In earlier types of cloud computing# each application had its own client program which served as
its user interface and had to be separately installed on each user+s personal computer. An upgrade
to the server part of the application would typically re)uire an upgrade to the clients installed on
each user workstation# adding to the support cost and decreasing productivity.
In contrast# web applications use web documents written in a standard format such as $T%&
(and more recently ,$T%&)# which are supported by a variety of web browsers.
-enerally# each individual web page is delivered to the client as a static document# but the
se)uence of pages can provide an interactive e'perience# as user input is returned through web
form elements embedded in the page markup. .uring the session# the web browser interprets and
displays the pages# and acts as the universal client for any web application.
In /001# 2etscape introduced a client-side scripting language called Java"cript# which allowed
programmers to add some dynamic elements to the user interface that ran on the client side. 3ntil
then# all the data had to be sent to the server for processing# and the results were delivered
through static $T%& pages sent back to the client
In /004# %acromedia introduced 5lash# a vector animation player that could be added to
browsers as a plug-in to embed animations on the web pages. It allowed the use of a scripting
language to program interactions on the client side with no need to communicate with the server.
WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V
In /000# the 6web application6 concept was introduced in the Java language in the "ervlet
"pecification version 7.7. 7./8!.
/!7!
At that time both Java"cript and ,%& had already been
developed# but A9a' had still not yet been coined and the ,%&$ttp:e)uest ob9ect had only been
recently introduced on Internet ;'plorer 1 as an Active, ob9ect.
<!
In 7==1# the term A9a' was coined# and applications like -mail started to make their client sides
more and more interactive.
Interface
(ebconverger operating system provides an interface for web applications.
Through Java# Java"cript# .$T%&# 5lash# "ilverlight and other technologies# application-
specific methods such as drawing on the screen# playing audio# and access to the keyboard and
mouse are all possible. %any services have worked to combine all of these into a more familiar
interface that adopts the appearance of an operating system. -eneral purpose techni)ues such as
drag and drop are also supported by these technologies. (eb developers often use client-side
scripting to add functionality# especially to create an interactive e'perience that does not re)uire
page reloading. :ecently# technologies have been developed to coordinate client-side scripting
with server-side technologies such as >$>. A9a'# a web development techni)ue using a
combination of various technologies# is an e'ample of technology which creates a more
interactive e'perience.
Structure
Applications are usually broken into logical chunks called 6tiers6# where every tier is assigned a
role.
?!
Traditional applications consist only of / tier# which resides on the client machine# but
web applications lend themselves to a n-tiered approach by nature.
?!
Though many variations are
possible# the most common structure is the three-tiered application.
?!
In its most common form#
the three tiers are called presentation# application and storage# in this order. A web browser is
the first tier (presentation)# an engine using some dynamic (eb content technology (such as
A"># A">.2;T# *-I# *old5usion# J">@Java# >$># >erl# >ython# :uby on :ails or "truts7) is the
middle tier (application logic)# and a database is the third tier (storage).
?!
The web browser sends
re)uests to the middle tier# which services them by making )ueries and updates against the
database and generates a user interface.
5or more comple' applications# a <-tier solution may fall short# and you may need a n-tiered
approach# where the greatest benefit is breaking the business logic# which resides on the
application tier# into a more fine-grained model.
?!
Ar adding an integration tier that separates the
data tier from the rest of tiers by providing an easy-to-use interface to access the data.
?!
5or
e'ample# you would access the client data by calling a 6listBclients()6 function instead of making
a "C& )uery directly against the client table on the database. That allows you to replace the
underlying database without changing the other tiers.
?!
WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V
There are some who view a web application as a two-tier architecture. This can be a 6smart6
client that performs all the work and )ueries a 6dumb6 server# or a 6dumb6 client that relies on a
6smart6 server.
?!
The client would handle the presentation tier# the server would have the
database (storage tier)# and the business logic (application tier) would be on one of them or on
both.
?!
(hile this increases the scalability of the applications and separates the display and the
database# it still doesn+t allow for true specialiDation of layers# so most applications will outgrow
this model.
?!
Business use
An emerging strategy for application software companies is to provide web access to software
previously distributed as local applications. .epending on the type of application# it may re)uire
the development of an entirely different browser-based interface# or merely adapting an e'isting
application to use different presentation technology. These programs allow the user to pay a
monthly or yearly fee for use of a software application without having to install it on a local hard
drive. A company which follows this strategy is known as an application service provider (A">)#
and A">s are currently receiving much attention in the software industry.
Writing web applications
There are many web application frameworks which facilitate rapid application development by
allowing the programmer to define a high-level description of the program.
1!
In addition# there is
potential for the development of applications on Internet operating systems# although currently
there are not many viable platforms that fit this model.
The use of web application frameworks can often reduce the number of errors in a program# both
by making the code simpler# and by allowing one team to concentrate 9ust on the framework. In
applications which are e'posed to constant hacking attempts on the Internet# security-related
problems can be caused by errors in the program. 5rameworks can also promote the use of best
practices such as -;T after >A"T.
Applications
Erowser applications typically include simple office software (word processors# online
spreadsheets# and presentation tools)# with -oogle .ocs being the most notable e'ample# and can
also include more advanced applications such as pro9ect management# computer-aided design#
video editing and point-of-sale.
Benefits
(eb applications do not re)uire any comple' 6roll out6 procedure to deploy in large
organiDations. A compatible web browser is all that is neededF
Erowser applications typically re)uire little or no disk space on the clientF
They re)uire no upgrade procedure since all new features are implemented on the server
and automatically delivered to the usersF
WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V
(eb applications integrate easily into other server-side web procedures# such as email
and searching.
They also provide cross-platform compatibility in most cases (i.e.# (indows# %ac#
&inu'# etc.) because they operate within a web browser window.
Drawbacks
In practice# web interfaces# compared to thick clients# typically force significant sacrifice
to user e'perience and basic usability.
(eb applications absolutely re)uire compatible web browsers. If a browser vendor
decides not to implement a certain feature# or abandons a particular platform or operating
system version# this may affect a huge number of usersF
"tandards compliance is an issue with any non-typical office document creator# which
causes problems when file sharing and collaboration becomes criticalF
Erowser applications rely on application files accessed on remote servers through the
Internet. Therefore# when connection is interrupted# the application is no longer usable
but if it uses $T%&1 A>I+s such as Affline (eb application caching
G!
# it can be
downloaded and installed locally# for offline use. -oogle -ears# although no longer in
active development# is a good e'ample of a third party plugin for web browsers that
provides additional functionality for creating web applicationsF
"ince many web applications are not open source# there is also a loss of fle'ibility#
making users dependent on third-party servers# not allowing customiDations on the
software and preventing users from running applications offline (in most cases).
$owever# if licensed# proprietary software can be customiDed and run on the preferred
server of the rights ownerF
They depend entirely on the availability of the server delivering the application. If a
company goes bankrupt and the server is shut down# the users have little recourse.
Traditional installed software keeps functioning even after the demise of the company
that produced it (though there will be no updates or customer service)F
&ikewise# the company has much greater control over the software and functionality.
They can roll out new features whenever they wish# even if the users would like to wait
until the bugs have been worked out before upgrading. The option of simply skipping a
weak software version is often not available. The company can foist unwanted features
on the users or cut costs by reducing bandwidth. Af course# companies will try to keep
the good will of their customers# but the users of web applications have fewer options in
such cases unless a competitor steps in and offers a better product and easy migrationF
The company can theoretically track anything the users do. This can cause privacy
problems.
WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V
Cookies
HTTP is Stateless
;very re)uest for a web page is an independent transaction. "ervers donHt remember who
re)uested what when. Ardinarily# this is no problem. If Joe .oakes re)uests page1.html and
then Eertha Eupkis re)uests that same page ten seconds later# does the server really care8 Ance
you start filling in forms that re)uire you to remember information# though# the statelessness of
$TT> is a pain.
*onsider this first page of a form# where Joe .oakes enters his nameI
Your name:
Joe Doaes
An the ne't page# we would like to personaliDe the response.
Thanks# Joe .oakesJ
In short# the server must somehow keep track of information from one page to another. There are
lots of ways to do this# but the one we will e'plore (because it works well with Java"cript) is
cookies.
Cookie Format
Kou set a cookie with statements like thisI
document.cookie = "cookieName=cookieData"; // generic form
document.cookie = "userName=Joe";
document.cookie = "item=toner;" +
"expires=Mon !" Jan #!!$ !%&!'&!% (M)";
document.cookie = "price='".$%;" +
"expires=Mon !" Jan #!!$ !%&!'&!% (M)";
The cookie stays around until the e'piration time. If you donHt set an e'piration date# the cookie
vanishes as soon as you e'it the browser.
The cookie data cannot contain any commas# semicolons# or whitespace. In order to
accommodate data that does contain these characters# we will URL-encode the data. That is# we
will use the built-in escape() function to encode the data in a form that contains only characters
that are allowed in a 3:&. The button below will call a function that sets a cookie with the value
in the form.
Please enter your name:
WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V
*form name="the+orm" action=","-
.lease enter /our name&*input t/pe="text" name="/ourName" /-
*input t/pe="0utton" 1alue="2et 3ookie" on3lick="set3ookie45;"-
*/form-
function set3ookie45
6
1ar response = document.the+orm./ourName.1alue;
if 4response == ""5
6
response = "M/ster/ (uest";
7
document.cookie = "/ourName=" + escape4response5;
7
Sessions
There are a number of problems that arise from the fact that $TT> is a 6stateless6 protocol. In
particular# when you are doing on-line shopping# it is a real annoyance that the (eb server can+t
easily remember previous transactions. This makes applications like shopping carts very
problematicI when you add an entry to your cart# how does the server know what+s already in
your cart8 ;ven if servers did retain conte'tual information# you+d still have problems with e-
commerce. (hen you move from the page where you specify what you want to buy (hosted on
the regular (eb server) to the page that takes your credit card number and shipping address
(hosted on the secure server that uses ""&)# how does the server remember what you were
buying8
There are three typical solutions to this problem.
1. Cookies. Kou can use $TT> cookies to store information about a shopping session# and
each subse)uent connection can look up the current session and then e'tract information
about that session from some location on the server machine. This is an e'cellent
alternative# and is the most widely used approach. $owever# even though servlets have a
high-level and easy-to-use interface to cookies# there are still a number of relatively
tedious details that need to be handledI
o ;'tracting the cookie that stores the session identifier from the other cookies
(there may be many# after all)#
o "etting an appropriate e'piration time for the cookie (sessions interrupted by 7?
hours probably should be reset)# and
o Associating information on the server with the session identifier (there may be far
too much information to actually store it in the cookie# plus sensitive data like
credit card numbers should never go in cookies).
7. U! ewriting. Kou can append some e'tra data on the end of each 3:& that identifies
the session# and the server can associate that session identifier with data it has stored
about that session. This is also an e'cellent solution# and even has the advantage that it
works with browsers that don+t support cookies or where the user has disabled cookies.
WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V
$owever# it has most of the same problems as cookies# namely that the server-side
program has a lot of straightforward but tedious processing to do. In addition# you have to
be very careful that every 3:& returned to the user (even via indirect means like
&ocation fields in server redirects) has the e'tra information appended. And# if the user
leaves the session and comes back via a bookmark or link# the session information can be
lost.
<. Hi""en for# fiel"s. $T%& forms have an entry that looks like the followingI LI2>3T
TK>;M6$I..;26 2A%;M6session6 NA&3;M6...6O. This means that# when the form is
submitted# the specified name and value are included in the -;T or >A"T data. This can
be used to store information about the session. $owever# it has the ma9or disadvantage
that it only works if every page is dynamically generated# since the whole point is that
each session has a uni)ue identifier.
"ervlets provide an outstanding technical solutionI the $ttp"ession A>I. This is a high-level
interface built on top of cookies or 3:&-rewriting. In fact# on many servers# they use cookies if
the browser supports them# but automatically revert to 3:&-rewriting when cookies are
unsupported or e'plicitly disabled. Eut the servlet author doesn+t need to bother with many of the
details# doesn+t have to e'plicitly manipulate cookies or information appended to the 3:&# and is
automatically given a convenient place to store data that is associated with each session.
$. T%e Session Tracking API
3sing sessions in servlets is )uite straightforward# and involves looking up the session ob9ect
associated with the current re)uest# creating a new session ob9ect when necessary# looking up
information associated with a session# storing information in a session# and discarding completed
or abandoned sessions.
$.& !ooking up t%e HttpSession ob'ect associate" wit% t%e current re(uest.
This is done by calling the get"ession method of $ttp"ervlet:e)uest. If this returns null# you can
create a new session# but this is so commonly done that there is an option to automatically create
a new session if there isn+t one already. Just pass true to get"ession. Thus# your first step usually
looks like thisI
$ttp"ession session M re)uest.get"ession(true)F
$.$ !ooking up Infor#ation Associate" wit% a Session.
$ttp"ession ob9ects live on the serverF they+re 9ust automatically associated with the re)uester by
a behind-the-scenes mechanism like cookies or 3:&-rewriting. These session ob9ects have a
builtin data structure that let you store any number of keys and associated values. In version 7./
and earlier of the servlet A>I# you use getNalue(6key6) to look up a previously stored value. The
return type is Ab9ect# so you have to do a typecast to whatever more specific type of data was
associated with that key in the session. The return value is null if there is no such attribute. In
version 7.7# getNalue is deprecated in favor of getAttribute# both because of the better naming
match with setAttribute (the match for getNalue is putNalue# not setNalue)# and because
setAttribute lets you use an attached $ttp"essionEinding&istener to monitor values# while
WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V
putNalue doesn+t. 2evertheless# since few commercial servlet engines yet support version 7.7# I+ll
use getNalue in my e'amples. $ere+s one representative e'ample# assuming "hopping*art is
some class you+ve defined yourself that stores information on items being purchased.
$ttp"ession session M re)uest.get"ession(true)F
S%oppingCart pre)iousIte#s *
+S%oppingCart,session.get-alue+.pre)iousIte#s.,/
if (previousItems JM null) P
do"omething(ith(previousItems)F
Q else P
previousItems M new "hopping*art(...)F
do"omething;lse(ith(previousItems)F
Q
In most cases# you have a specific attribute name in mind# and want to find the value (if any)
already associated with it. $owever# you can also discover all the attribute names in a given
session by calling getNalue2ames# which returns a "tring array. In version 7.7# use
getAttribute2ames# which has a better name and which is more consistent in that it returns an
;numeration# 9ust like the get$eaders and get>arameter2ames methods of $ttp"ervlet:e)uest.
Although the data that was e'plicitly associated with a session is the part you care most about#
there are some other pieces of information that are sometimes useful as well.
getI". This method returns the uni)ue identifier generated for each session. It is
sometimes used as the key name when there is only a single value associated with a
session# or when logging information about previous sessions.
is0ew. This returns true if the client (browser) has never seen the session# usually
because it was 9ust created rather than being referenced by an incoming client re)uest. It
returns false for pree'isting sessions.
getCreationTi#e. This returns the time# in milliseconds since the epoch# at which the
session was made. To get a value useful for printing out# pass the value to the .ate
constructor or the setTimeIn%illis method of -regorian*alendar.
get!astAccesse"Ti#e. This returns the time# in milliseconds since the epoch# at which
the session was last sent from the client.
get1a2Inacti)eInter)al. This returns the amount of time# in seconds# that a session
should go without access before being automatically invalidated. A negative value
indicates that the session should never timeout.
$.3 Associating Infor#ation wit% a Session
As discussed in the previous section# you read information associated with a session by using
getNalue (or getAttribute in version 7.7 of the servlet spec). To specify information# you use
putNalue (or setAttribute in version 7.7)# supplying a key and a value. 2ote that putNalue
replaces any previous values. "ometimes that+s what you want (as with the referring>age entry in
the e'ample below)# but other times you want to retrieve a previous value and augment it (as
with the previousItems entry below). $ere+s an e'ampleI
WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V
$ttp"ession session M re)uest.get"ession(true)F
session.put-alue+.referringPage.4 re(uest.getHea"er+.eferer.,,/
"hopping*art previousItems M
("hopping*art)session.getNalue(6previousItems6)F
if (previousItems MM null) P
previousItems M new "hopping*art(...)F
Q
"tring itemI. M re)uest.get>arameter(6itemI.6)F
previousItems.add;ntry(*atalog.get;ntry(itemI.))F
@@ Kou still have to do putNalue# not 9ust modify the cart# since
@@ the cart may be new and thus not already stored in the session.
session.put-alue+.pre)iousIte#s.4 pre)iousIte#s,/
3. 52a#ple6 S%owing Session Infor#ation
$ere is a simple e'ample that generates a (eb page showing some information about the current
session. Kou can also download the source or try it on-line.
package hallF
import 9ava.io.RF
import 9ava'.servlet.RF
import 9ava'.servlet.http.RF
import 9ava.net.RF
import 9ava.util.RF
@RR "imple e'ample of session tracking. "ee the shopping
R cart e'ample for a more detailed one.
R L>O
R >art of tutorial on servlets and J"> that appears at
R httpI@@www.apl.9hu.edu@Shall@9ava@"ervlet-Tutorial@
R /000 %arty $allF may be freely used or adapted.
R@
public class "how"ession e'tends $ttp"ervlet P
public void do-et($ttp"ervlet:e)uest re)uest#
$ttp"ervlet:esponse response)
throws "ervlet;'ception# IA;'ception P
$ttp"ession session M re)uest.get"ession(true)F
response.set*ontentType(6te't@html6)F
>rint(riter out M response.get(riter()F
"tring title M 6"earching the (eb6F
"tring headingF
Integer access*ount M new Integer(=)FF
if (session.is2ew()) P
heading M 6(elcome# 2ewcomer6F
WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V
Q else P
heading M 6(elcome Eack6F
Integer oldAccess*ount M
@@ 3se getAttribute# not getNalue# in version
@@ 7.7 of servlet A>I.
(Integer)session.getNalue(6access*ount6)F
if (oldAccess*ount JM null) P
access*ount M
new Integer(oldAccess*ount.intNalue() T /)F
Q
Q
@@ 3se putAttribute in version 7.7 of servlet A>I.
session.putNalue(6access*ount6# access*ount)F

out.println("ervlet3tilities.head(ithTitle(title) T
6LEA.K E-*A&A:MU6V5.51;4U6OUn6 T
6L$/ A&I-2MU6*;2T;:U6O6 T heading T 6L@$/OUn6 T
6L$7OInformation on Kour "essionIL@$7OUn6 T
6LTAE&; EA:.;:M/ A&I-2M*;2T;:OUn6 T
6LT: E-*A&A:MU6V55A.==U6OUn6 T
6 LT$OInfo TypeLT$ONalueUn6 T
6LT:OUn6 T
6 LT.OI.Un6 T
6 LT.O6 T session.getId() T 6Un6 T
6LT:OUn6 T
6 LT.O*reation TimeUn6 T
6 LT.O6 T new .ate(session.get*reationTime()) T 6Un6 T
6LT:OUn6 T
6 LT.OTime of &ast AccessUn6 T
6 LT.O6 T new .ate(session.get&astAccessedTime()) T 6Un6 T
6LT:OUn6 T
6 LT.O2umber of >revious AccessesUn6 T
6 LT.O6 T access*ount T 6Un6 T
6L@TAE&;OUn6 T
6L@EA.KOL@$T%&O6)F
Q
public void do>ost($ttp"ervlet:e)uest re)uest#
$ttp"ervlet:esponse response)
throws "ervlet;'ception# IA;'ception P
do-et(re)uest# response)F
Q
Q
$ere+s a typical result# shown after visiting the page several without )uitting the browser in
betweenI
WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V
PHP
>$> stands for >$>I $yperte't >reprocessor
>$> is a server-side scripting language# like A">
>$> scripts are e'ecuted on the server
>$> supports many databases (%y"C&# Informi'# Aracle# "ybase# "olid# >ostgre"C&# -eneric
A.E*# etc.)
>$> is an open source software (A"")
This means its free to use and isnHt being controlled by a single entity.
It is being developed by a group of developers
>$> synta' resembles that of Java"cript and Action"cript in different ways.
>$> is free to download and use.
>$> files may contain te't# $T%& tags and scripts.
>$> files are returned to the browser as plain $T%&.
>$> files have a file e'tension of 6.php6# 6.php<6# or 6.phtml6.
>$> can be written in any te't editor.
>$> script will be located inside special tags# much like Java"cript
e.g. 78p%p 99p%p script %ere 8:
WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V
>$> code can be located any where in the page.
>$> is case sensitive.
;very variable in >$> will have the W symbol as a prefi'
e.g. ;#y0a#e *<=o%n>/
;very line of code %3"T be terminated with a / symbol.
>$> runs on different platforms ((indows# &inu'# 3ni'# etc.)
>$> is compatible with almost all servers used today (Apache# II"# etc.)
>$> is 5:;; to download from the official >$> resourceI www.php.net
>$> is easy to learn and runs efficiently on the server side
Basic PHP Synta2
Kou cannot view the >$> source code by selecting 6Niew source6 in the browser - you
will only see the output from the >$> file# which is plain $T%&.
This is because the scripts are e'ecuted on the server before the result is sent back
to the browser.
A >$> scripting block always starts with 78p%p and ends with 8:. A >$> scripting
block can be placed anywhere in the document.
An servers with shorthand support enabled you can start a scripting block with 78
and end with 8:.
$owever# for ma'imum compatibility# we recommend that you use the standard form
(L8php) rather than the shorthand form.
L8php
8O
A >$> file normally contains $T%& tags# 9ust like an $T%& file# and some >$>
scripting code.
Eelow# we have an e'ample of a simple >$> script which sends the te't 6$ello (orld6
to the browserI
LhtmlO
LbodyO
L8php
echo 6$ello (orld6F
8O
L@bodyO
L@htmlO
;ach code line in >$> must end with a semicolon. The semicolon is a separator and
is used to distinguish one set of instructions from another.
There are two basic statements to output te't with >$>I echo and print. In the
e'ample above we have used the echo statement to output the te't 6$ello (orld6.
In >$># we use @@ to make a single-line comment or @R and R@ to make a large comment
WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V
block.
Co##ents In PHP
LhtmlO
LbodyO
L8php
@@This is a comment
@R
This is
a comment
block
R@
8O
L@bodyO
L@htmlO
PHP -ariables
Nariables are used for storing a values# like te't strings# numbers or arrays.
(hen a variable is set it can be used over and over again in your script
All variables in >$> start with a W sign symbol.
The correct way of setting a variable in >$>I
WvarBname M valueF
2ew >$> programmers often forget the W sign at the beginning of the variable. In that
case it will not work.
&et+s try creating a variable with a string# and a variable with a numberI
PHP -ariables
L8php
Wt't M 6$ello (orldJ6F
Wnumber M /4F
8O
PHP is a !oosely Type" !anguage
In >$> a variable does not need to be declared before being set.
In the previous e'ample# you see that you do not have to tell >$> which data type the
variable is.
>$> automatically converts the variable to the correct data type# depending on how
they are set.
In a strongly typed programming language# you have to declare (define) the type and
name of the variable before using it.
In >$> the variable is declared automatically when you use it.
WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V
-ariable 0a#ing ules
A variable name must start with a letter or an underscore 6B6
A variable name can only contain alpha-numeric characters and underscores
(a-X# =-0# and B )
A variable name should not contain spaces. If a variable name is more than
one word# it should be separated with underscore (WmyBstring)# or with
capitaliDation (Wmy"tring)
Strings In PHP
"tring variables are used for values that contains character strings.
(e are going to look at some of the most common functions and operators used to
manipulate strings in >$>.
After we create a string we can manipulate it. A string can be used directly in a
function or it can be stored in a variable.
Eelow# the >$> script assigns the string 6$ello (orld6 to a string variable called Wt'tI
Strings In PHP
L8php
Wt'tM6$ello (orld6F
echo Wt'tF
8O
The output of the code will beI
Strings In PHP
$ello (orld
T%e Concatenation ?perator
There is only one string operator in >$>.
The concatenation operator (.) is used to put two string values together.
To concatenate two variables together# use the dot (.) operatorI
L8php
Wt't/M6$ello (orld6F
Wt't7M6/7<?6F
echo Wt't/ . 6 6 . Wt't7F
8O
If we look at the code above you see that we used the concatenation operator two
times. This is because we had to insert a third string.
Eetween the two string variables we added a string with a single character# an empty
space# to separate the two variables.
The output of the code will beI
$ello (orld /7<?
WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V
Using t%e strlen+, function
The strlen() function is used to find the length of a string.
&et+s find the length of our string 6$ello worldJ6I
Using t%e strlen+, function
L8php
echo strlen(6$ello worldJ6)F
8O
The output of the code above will beI
/7
The length of a string is often used in loops or other functions# when it is important to
know when the string ends. (i.e. in a loop# we would want to stop the loop after the
last character in the string)
The strpos() function is used to search for a string or character within a string.
If a match is found in the string# this function will return the position of the first match.
If no match is found# it will return 5A&";.
&et+s see if we can find the string 6world6 in our stringI
L8php
echo strpos(6$ello worldJ6#6world6)F
8O
The output of the code above will beI
4
As you see the position of the string 6world6 in our string is position 4. The reason that
it is 4# and not G# is that the first position in the string is =# and not /.
1yS@!
%y"C& is a small database server
%y"C& is ideal for small and medium applications
%y"C& supports standard "C&
%y"C& compiles on a number of platforms
%y"C& is free to download and use
PHP A 1yS@!
>$> combined with %y"C& is cross-platform
(means that you can develop in (indows and serve on a 3ni' platform).
WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V
Building Web Content with PHP and MySQL
*html-
*0od/-
*ta0le 0order=1-
*tr- *8php //start of a ta0le ro9 8-
*th-3olumn 1*/th-*th-3olumn #*/th-*th-3olumn '*/th- *8php //the names
for each column 8-
*/tr-
*td-entr/1*/td-*td-entr/#*/td-*td-entr/'*/td-*8php // a ro9 of data 8-
*./tr-
*tr-
*td-entr/"*/td-*td-entr/%*/td-*td-entr/:*/td-
*/tr-
*/ta0le-
*/0od/-
*/html-
Renders as:
WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V
Using MySQL inside PHP

;is<connected = =m/s>l<connect4"localhost" "guest" "guestp9d"5;
we use a MySQL specific PHP command. When prorammatically accessin a data!ase" there
are two main approaches # you can call commands that assume a specific data!ase to
interface with" or you can call enerali$ed data!ase commands that et passed to a middle%
le&el dri&er that translate them to the commands for a specific data!ase. 'he former approach
can ma(e thins a little simpler" the latter approach allows reater fle)i!ility to easily switch a
data!ase from a MySQL data!ase to" for e)ample" Postress. We are oin to use the MySQL%
specific approach. *ote: if you don+t ha&e ,uest- on
in MySQL run
.R/*' /LL 0* trii.1 '0 2uest232localhost2 456*'47465 8Y 2uestpwd29
'he ne)t thin to notice is the &aria!le assined the return &alue of m/s>li<connect. 'his
&aria!le will !e either a numeric id for the connection or false dependin on whether or not the
proram connects to MySQL. :onnectin to a data!ase is not uaranteed to wor(. 'he
connection could fail if the data!ase ser&er is down" or if the data!ase is on another machine
WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V
and the networ( is down" etc. *ow we can chec( ;is<connected to ma(e sure e&erythin is
runnin smoothly.
'he last thin new a!out this line is the+=+ sym!ol. 'his sym!ol oes in front of a function to
indicate we want to suppress the default way PHP will handle an error. 4f we are o( with the
standard PHP error handlin we could ha&e ;ust written:
;is<connected = m/s>l<connect4"localhost" "guest" "guestp9d"5;
Howe&er" it+s a ood idea to do your own error handlin. Sometimes your users aren+t oin to
!e computer%sa&&y to ma(e sense of the error messae. Sometimes your users miht !e too
sa&&y and the default error messae miht tell them more than you want a!out your data!ase.
When we+re doin our own error handlin" you miht notice the new function die45. 5on+t let its
terrifyin name scare you off # die is a useful function. 4t will display whate&er strin you pass
it" and then it will cause the ser&er to inore all remainin PHP code.
Selecting a Database
WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V
*ow"
you want to select the trii data!ase. *otice once aain we repeat the process of ma(in a
<uery" chec(in to see that it wor(ed" and handlin the error if it didn+t.*ote: 4f you don+t ha&e trii
!uilt" from he password your MySQL" on the command line run
mys<l %u root = trii.s<lmys<l %u root = trii.s<l
unning Queries in PHP
*ow that we+&e connected to the data!ase" let+s do somethin useful. Say we want to et the
ene>id" name and 6ntre$ id from the ene ta!le in the trii data!ase" and we want to sort the
results !y their name &alue. 4n MySQL" we could do this with the <uery:
select ene>id" name" locuslin( from ene order !y name9
8ut" if we want PHP to use the results" we need to em!ed this <uery within PHP+s MySQL
framewor(. We create a strin with the <uery we want to ma(e" and then pass this strin to
m/s>l<>uer/
WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V
/ typical mys<l <uery run throuh PHP. Here MySQL doesn+t return anythin from the <uery so
all we need to do is chec( that the result isn+t false" which would indicate an error.
WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V
Populating an SQL Table with PHP
'his code snippet from populate>ta!le.php is part of a proram that populates the deadwood
ta!le with the &alues in a ta! delimited file. 4n the foreach loop" each line is accessed as a
sinle strin. 4t is cleaned !y htmlspecialchars" and then split with the e)plode function. 'he
rest is ;ust a standard MySQL <uery. Remem!er to include the sinle <uotes around each &alue
?e.. ?;line<arra/@!AB@ when the &alue is a strin" as MySQL re<uires it. You can imaine
doin more complicated thins with your PHP code here" such as processin your &alues with
php functions" or populatin different ta!les with different parts of the line ?e.. puttin
line<arra/@#A and line<arra/@'A into a historical>fiures ta!le and the rest in a
t&>show>details ta!le@
WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V
Dis!laying an SQL "able as an H"ML "able
'his code snippet from display.php performs a <uery that returns a result we want to process
e&en if the result is correct. We use a while loop to (eep assinin Arow the &alue from
mys<l>fetch>array" and accessin the Arow &alue matchin the field name which is its (ey. We
put each &alue into an htlm ta!le.
WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V
Security #otes
PHP allows you to write pro;ects <uic(ly.
B Rouhly CDE of the &ulnera!ilities affected We! ser&ers" We! applications and We! !rowsers.
B /pplications written in PHP comprise rouhly FGE of all &ulnera!ilities.
B Rouhly CFE of the We! application &ulnera!ilities can !e accounted
for !y H &ulnera!ility classes: remote file inclusion" SQL in;ection"
cross%site scriptin" and directory tra&ersal.
1 Iulnera!ilities within the PHP prorammin lanuae &ersions H and J comprised FE of total
&ulnera!ilities

Вам также может понравиться