You are on page 1of 55

Department of Information Science

Web programming manual

1. Develop and demonstrate an XHTML document that illustrates the use of external style sheet, ordered list, table, borders, padding, color and the span tag.
BASICS:
 Every XHTML document must begin with: <?xml version = 1.0 ?> <!DOCTYPE html PUBLIC -//w3c//DTD XHTML 1.1//EN http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd> <html>, <head>, <title>, and <body> are required in every document The whole document must have <html> as its root and html must have the xmlns attribute: html xmlns = http://www.w3.org/1999/xhtml A document consists of a head and a body . The <title> tag is used to give the document a title, which is normally displayed in the browsers window title bar (at the top of the display).

   

Lists
  Unordered lists The list is the content of the <ul> tag. List elements are the content of the <li> tag. Ordered lists The list is the content of the <ol> tag. Each item in the display is preceded by a sequence value.

Table            Span 

A table is a matrix of cells, each possibly having content The cells can include almost any element Some cells have row or column labels and some have data A table is specified as the content of a <table> tag A border attribute in the <table> tag specifies a border between the cells If border is set to "border", the browsers default width border is used The border attribute can be set to a number, which will be the border width Without the border attribute, the table will have no lines! Each row of a table is specified as the content of a <tr> tag The row headings are specified as the content of a <th> tag The contents of a data cell is specified as the content of a <td> tag

The <span> tag is similar to other HTML tags, they can be nested and they have id and class attributes. We use it to apply special font properties, i.e, to just a few words in a text.

Bangalore Institute of Technology

Department of Information Science

Web programming manual

PROGRAM: //prg1.css
p, table, li { font-family: "lucida calligraphy"; margin-left: 5pt; } p { margin-left: 50px; word-spacing: 5px; } body { background-color: rgb(200, 255, 205); } p, li, td { font-size: 75%; } td { padding: 0.5cm; } th { text-align: center; font-size: 85%; } h1, h2, h3, hr { text-align: center; color: #483d8b; } table { border-style: outset; background: rgb(100, 255, 255); } li { list-style-type: lower-roman; } span { color: red; background-color: yellow; font-size: 29pt; font-style: italic; font-weight: bold; } //prog1.html

Bangalore Institute of Technology

Department of Information Science

Web programming manual

<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC="_//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <link rel="stylesheet" type="text/css" href="prg1.css"/> <title>LAB PROGRAM!</title> </head> <body> <h1>Information Science & Engineering Department</h1> <h2>This header is blue</h2> <p>This paragraph has a left margin of 50 pixels and word spacing of 5 pixels</p> <table border="4"> <tr> <th width="120">NAMES</th> <th>Email</th> </tr> <tr> <td width="120">Mr R.Nagaraja</td> <td>nagarajar_ise_dept@yahoo.com</td> </tr> <tr> <td width="100">Mr J.Prakash</td> <td>jprakash_bit@gmail.com</td> </tr> <tr> <td width="120">Mr Padmanabha.J</td> <td>bit_padmanabha@rediff.com</td> </tr> </table> <hr /> <ol> <h1> <li>Padmanabh</li> <li>Anupama</li> <li>Chethana</li> </h1> </ol> <hr /> <h2>This is <span>Web programming</span> laboratory</h2> </body> </html>

Bangalore Institute of Technology

    
e s e ec

A !   4    % #' ! 4' % &  % 12 ! !'1 %#2 12#   ! !'  "# !% & C "$'1 9 ( ( 0 ( ) 3 )  12# !% @ ! %$#'0 #%) '   %"  " 2 $  (%! @ 1  # 1%#%)1 !' % ! #" 0' !' %1 0 1"  ) ! '# !'1 !% & ( C 0 #'$  B'#" @ & (  11% ! !'1 B'#"$ !%1 !' %#%"  )6 A !'0 @ # @    @  % !%  ' '1 2'& % ) % )12 !$  ! 2 1! !' % ! #" !$21' $'#0 9 %2 ! "28#%$ #% $ % #' 7 65 ! ! #43 ! !'1 !$21' 0' !' %#%" )  (%! ' & #%$ #" !  
CSS i

   

De

Sc e ce

OUT UT

DESCRIPTION:

l t i i i ti l it

ti

i t ti titi i t

il t

y
t l t t ti t t ti i l i l t t i ilit i t i ti l lti l t l t t ll t t t i t i t l l i ilit t l l itt

tti

t li t

i il

Department of Information Science

Web programming manual

2. Develop and demonstrate an XHTML file that includes Javascript script for the following problems: a) Input: A number n obtained using prompt Output: The first n Fibonacci numbers
PROGRAM: //prog2a.html
<?xml version = "1.0" encoding = "utf-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>FIBONACCI SERIES</title> </head> <body> <script type="text/javascript"> var fib1=0,fib2=1,fib=0; var num = prompt("Enter a number : \n", ""); if(num!=null && num>0) { document.write("<h1>" + num + " Fibonocci numbers are as follows</h1>"); if(num==1) document.write("<h3> "+ fib1 + "</h3>"); else { document.write("<h3>" + fib1 + "</h3>"); document.write("<h3>" + fib2 + "</h3>"); } for(i=3;i<=num; i++) { fib= fib1 + fib2; document.write("<h3>" + fib + "</h3>"); fib1=fib2; fib2=fib; } } else alert("No Proper Input"); </script> </body> </html>

Bangalore Institute of Technology

VPXPI` Y QP GW GS G IR FPXE VIE


e s e ec

XEWIEH VISHHEF VPFD U

IPS EHFP IR P I H FED G G Q Q G


e

De

Sc e ce

I S

OUTPUT:

1.

2.

y e

DESCRIPTION:
i t the fi t n Fi nacci numbers using the write method of the Document object Thi It uses the prompt method to collect a string of input from the user. It takes two parameters: the string that prompts the user for input and a default string in case the user does not t pe a string before pressing one of the two buttons, i.e, OK and Cancel.

ec

f p

De

Sc e ce

ubtfbe sfpeebc sgca r

sgugfw v hg dt dp d fi cgub sfb

fgp becg fi g f e cba d d h h d x x y y x

b) Input: A number n obtained using prompt Output: A table of numbers from 1 to n and their squares using alert
PROGRAM: //prog2b.html
<?xml version = " .0" encoding = "utf-8" ?> <!DOCTYPE html PUB IC "-//W C//DTD XHTM 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>NUMBERS & SQU RES</title> </head> <body> <script type="text/javascript"> var num = prompt "Enter a number : \n", "" ; if(num >0 && num !=null { msgstr="Number and its S uares are \n"; for(i=1;i <= num; i { msgstr = msgstr + i + " - " + i*i + "\n"; } alert(msgstr); } else alert("No input supplied"); </script> </body> </html>

OUTPUT:
1.

ec

De

Sc e ce

gf e e d
8

egi h f g e

p o k oqq j n

2.

DESCRIPTION:
This program prints a table of numbers from 1 to n and their squares using alert method. It uses the prompt method to obtain a number from the user.

ec

w {

De

Sc e ce

swsv ~w{vvst ~xtr }


9

~xxw yx u u{ u wz txs ~ws

wx{ svtx wz x w v tsr u u y y u

Department of Information Science

Web programming manual

3. Develop and demonstrate an XHTML file that includes Javascript script that uses functions for the following problems: a) Parameter: A string Output: The position in the string of the left -most vowel
BASICS: XHTML
    An XHTML document is a mix of content and controls Controls are tags and their attributes Tags often delimit content and specify something about how the content should be arranged in the document Attributes provide additional information about the content of a tag

JAVASCRIPT
     A client-side HTML-embedded scripting language Only related to Java through syntax Dynamically typed and not object-oriented Provides a way to access elements of HTML documents and dynamically change them Directly embedded <script type=text/javascript> <!-Javascript here --> </script> Indirect reference <script type=text/javascript src=tst_number.js/>

PROGRAM: //prog3a.html
<?xml version = "1.0" encoding = "utf-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>VOWEL POSITION IN STRING</title> <script type="text/javascript"> function disp(str) { var alphaExp = /^[a-zA-Z]+$/; if(!str.value.match(alphaExp)) { alert("Input should be only alphabets"); return false; } var i, index = -1; for(i=0;i<str.value.length;i++) {

Bangalore Institute of Technology

10

if(str.value[i =='a' || str.value[i =='e' || str.value[i =='i' || str.value[i =='o' || str.value[i =='u' || str.value[i ==' ' || str.value[i =='E' || str.value[i =='I' || str.value[i =='O' || str.value[i =='U') { index = i; break; } } if(index == -1) alert("No vowel found"); else alert("The leftmost position of the vowel is " + (index+1)); } </script> </head> <body> <form> Enter a string : <input type="text" name="string" maxlength="30"> <input type="button" value="Click me!" onclick="disp(string)"> </form> </body> </html>

OUTPUT:
1.

ec

De

Sc e ce


11

2.

3.

DESCRIPTION:
The program starts comparing from the beginning of the string and stops when it finds a vowel and assigns the value of the position to the variable index, else the value remains -1. The actual position is one more than the value obtained since arrays are indexed starting from 0.

ec

De

Sc e ce


12

Department of Information Science

Web programming manual

b) Parameter: A number Output: The number with its digits in the reverse order
//prog3b.html
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <title>REVERSE OF A NUMBER</title> <head> <script type="text/javascript"> function disp(num) { var alphaexp = /^[0-9]+$/; if(!num.value.match(alphaexp)) { alert("Input should be a positive number"); return false; } var rn=0, n=Number(num.value); while(n!=0) { r=n%10; n=Math.floor(n/10); rn=rn 10+r; } alert("The number "+num.value+" in reverse is "+rn); } </script> </head> <body> <form> Enter a number: <input type ="text" name="number"> <input type="button" value="Click me!" onclick="disp(number)"> </form> </body> </html>

Bangalore Institute of Technology

13

OUTPUT:
1.

2.

DESCRIPTION:
The JavaScript has a function to calculate the reverse of the given number. First we run a check to find if the entered input is a positive number. Then we repeatedly extract each digit from the number starting at the units position by using modulus of 10.

ec

De

Sc e ce


14

Department of Information Science

Web programming manual

4. a) Develop and demonstrate, using Javascript, an XHTML document that collects the USN(the valid format is: a digit from 1 to 4 followed by two uppercase characters followed by two digits followed by two uppercase characters followed by three digits; no embedded spaces allowed) of the user. Event handler must be included for the form element that collects this information to validate the input. Messages in the alert window must be produced when errors are detected.
BASICS: Events and Event Handling
    Event-driven programming is a style of programming in which pieces of code, event handlers, are written to be activated when certain events occur Events represent activity in the environment including, especially, user actions such as moving the mouse or typing on the keyboard An event handler is a program segment designed to execute when a certain event occurs Events are represented by JavaScript objects

Setting a Handler
   Using an attribute, a JavaScript command can be specified: <input type=button name=myButton onclick=alert(You clicked the button!) /> A function call can be used if the handler is longer than a single statement <input type=button name=myButton onclick=myHandler() />

PROGRAM: //prog4a.html
<?xml version = "1.0" encoding = "utf-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>VALIDATION OF USN</title> </head> <script type="text/javascript"> function formValidator() { var usn = document.getElementById('req1'); if(isCorrect(usn)) { return true; } return false; } function isCorrect(elem1) { alphaExp1=/^[1-4][A-Z][A-Z][0-9][0-9][A-Z][A-Z][0-9][0-9][0-9]$/ if(elem1.value.length == 0) { alert("USN is empty"); elem1.focus(); return false;

Bangalore Institute of Technology

15

} else if(!elem1.value.match(alphaExp1)) { alert("USN should be in D DD DDD format"); elem1.focus(); return false; } alert("USN is correct"); return true; } </script> <body> <form onsubmit="return formValidator()"> Enter your USN in D DD DDD format: <input type="text" id="req1" /> <input type="submit" value="Check Field" /> </form> </body> </html>

OUTPUT:
1.

ec

De

Sc e ce


16

2.

3.

DESCRIPTION:
The program takes the USN of the student in the D DD DDD format. When the user enters the USN and clicks on the Submit button of the form, the JavaScript will validate the USN entered. The script will return true if the USN entered is in the correct format. Otherwise, it will return false. ppropriate messages are displayed. The focus method causes the element to be put in focus, which positions the cursor in the element.

ec

De

Sc e ce


17

Department of Information Science

Web programming manual

b) Modify the above program to get the current semester also(restricted to be a number from 1 to 8)
//prog4b.html
<?xml version = "1.0" encoding = "utf-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>VALIDATION OF USN & SEM</title> <script type='text/javascript'> function formValidator() { var usn = document.getElementById('req1'); var sem = document.getElementById('req2'); if(isCorrect(usn)) { if(isPerfect(sem)) return true; } return false; } function isPerfect(elem2) { var alphaExp2 = /^[1-8]$/; if(elem2.value.length == 0) { alert("Semester number is empty"); elem2.focus(); return false; } else if(!elem2.value.match(alphaExp2)) { alert("Invalid semester number"); elem2.focus(); return false; } alert("Semester number is correct"); return true; } function isCorrect(elem1) { var alphaExp1=/^[1-4][A-Z][A-Z][0-9][0-9][A-Z][A-Z][0-9][0-9][0-9]$/; if(elem1.value.length == 0) { alert("USN is empty"); elem1.focus(); return false; } else if(!elem1.value.match(alphaExp1)) { alert("USN should be in DAADDAADDD format"); elem1.focus();

Bangalore Institute of Technology

18

return false; } alert("USN is correct"); return true; } </script> </head> <body> <form onsubmit="return formValidator()"> Enter your USN in D DD DDD format: <input type="text" id="req1" /> <br /> Enter your semester: <input type="text" id="req2" /> <br /> <input type="submit" value="Check Field" /> </form> </body> </html>

OUTPUT:
1.

ec

De

Sc e ce


19

2.

3.

DESCRIPTION
The program takes the USN and SEM of the student in the D DD DDD format. When the user enters the USN, SEM and clicks on the Submit button of the form, the JavaScript will validate the USN and SEM entered. The script will return true if the USN and SEM entered is in the correct format. Otherwise, it will return false. ppropriate messages are displayed. The focus method causes the element to be put in focus, which positions the cursor in the element.

ec

De

Sc e ce


20

Department of Information Science

Web programming manual

5. a) Develop and demonstrate, using Javascript, an XHTML document that contains three short paragraphs of text, stacked on top of each other, with only enough of each showing so that the mouse cursor can be placed over some part of them. When the cursor is placed over the exposed part of any paragraph, it should rise to the top to become completely visible.
//prog5a.html
<html> <head> <title>Stack</title> <script type="text/javascript" > var top="a1"; <!-- This function is such that, each time a particular paragraph is clicked, that paragraphs z-index is increased to 10, thereby making it rise to the top and become completely visible When mouse is . moved over another paragraph, the paragraph which had previously risen above moves to the bottom of the stack -- > function toTop(newTop) { domTop = document.getElementById(top).style; domNew = document.getElementById(newTop).style; domTop.zIndex="0"; domNew.zIndex="10"; if((top!="a1")&&(newTop!="a1")) document.getElementById('a1').style.zIndex="5"; else if((top!="a2")&&(newTop!="a2")) document.getElementById('a2').style.zIndex="5"; else if((top!="a3")&&(newTop!="a3")) document.getElementById('a3').style.zIndex="5"; top=newTop; } </script> <!-- We are making a simple style sheet of each paragraph, initializing all the z-index to 0, assigning different colors and relative positions to each of them -- > <style type="text/css"> .box1 { position:absolute; top:0; left:0; z-index:0; background-color:#FF0000 } .box2 { position:absolute; top:50px; left:100px; z-index:0; background-color:#0000FF} .box3 { position:absolute; top:100px; left:200px; z-index:0; background-color:#FFFF00} </style> </head> <!-- The body contains the 3 paragraphs, everytime the mouse is placed over a particular paragraph, the toTop() function is called and that para rises to the top -- > <body> <p> <p class="box1" id="a1" onmouseover="toTop('a1')"> 1111111111111111111111111111111111111111111111111111111<br /> 1111111111111111111111111111111111111111111111111111111<br /> 1111111111111111111111111111111111111111111111111111111<br /> 1111111111111111111111111111111111111111111111111111111<br /> 1111111111111111111111111111111111111111111111111111111<br /> 1111111111111111111111111111111111111111111111111111111<br /> 1111111111111111111111111111111111111111111111111111111<br /> </p> <p class="box2" id="a2" onmouseover="toTop('a2')"> 2222222222222222222222222222222222222222<br />

Bangalore Institute of Technology

21

De

Sc e ce

2222222222222222222222222222222222222222<br /> 2222222222222222222222222222222222222222<br /> 2222222222222222222222222222222222222222<br /> 2222222222222222222222222222222222222222<br /> 2222222222222222222222222222222222222222<br /> </p> <p class="box3" id="a3" onmouseover="toTop('a3')" > 33333333333333333333333333333333333333333333333<br /> 33333333333333333333333333333333333333333333333<br /> 33333333333333333333333333333333333333333333333<br /> 33333333333333333333333333333333333333333333333<br /> 33333333333333333333333333333333333333333333333<br /> 33333333333333333333333333333333333333333333333<br /> </p> </body> </html>

OUTPUT:
Initial configuration with mouse placed on the paragraph of 3s

ec

    
e 22

 

     

De

Sc e ce

When mouse is moved over to the paragraph of 2s, paragraph of 3s which was previously visible on top, goes to the bottom of the stack

When mouse is moved over to the paragraph of 3s, paragraph of 2s which was previously visible on top, goes to the bottom of the stack

ec

21#" 0#'"" 0$  ) (
e 23

# ' #$' !" $ %#& %$ !# " ! 

0$2$#4 3 %$ !1 !' ! #& $2 0#

Department of Information Science

Web programming manual

b) Modify the above document so that when a paragraph is moved from the top stacking position, it returns to its original position rather than to the bottom.
PROGRAM: //prog5b.html
<html> <head> <title>Stack</title> <script type="text/javascript" > var top="a1"; <!-- This function is such that, each time a particular paragraph is clicked, that paragraphs zindex is increased to 10, thereby making it rise to the top and become completely visible -- > function toTop(newTop) { domTop = document.getElementById(top).style; domNew = document.getElementById(newTop).style; domTop.zIndex="0"; domNew.zIndex="10"; top=newTop; } </script> <!-- We are making a simple style sheet of each paragraph, initializing all the zindex to 0, assigning different colors and relative positions to each of them -- > <style type="text/css"> .box1 { position:absolute; top:0; left:0; z-index:0; background-color:#FF0000 } .box2 { position:absolute; top:50px; left:100px; z-index:0; background-color:#0000FF} .box3 { position:absolute; top:100px; left:200px; z-index:0; background-color:#FFFF00} </style> </head> <!-- The body contains the 3 paragraphs, everytime the mouse is placed over a particular paragraph, the toTop() function is called and that para rises to the top -- > <body> <p> <p class="box1" id="a1" onmouseover="toTop('a1')"> 1111111111111111111111111111111111111111111111111111111<br /> 1111111111111111111111111111111111111111111111111111111<br /> 1111111111111111111111111111111111111111111111111111111<br /> 111111111111111111111111111111111111111111 1111111111111<br /> 1111111111111111111111111111111111111111111111111111111<br /> 1111111111111111111111111111111111111111111111111111111<br /> 1111111111111111111111111111111111111111111111111111111<br /> </p> <p class="box2" id="a2" onmouseover="toTop('a2')"> 2222222222222222222222222222222222222222<br /> 2222222222222222222222222222222222222222<br /> 2222222222222222222222222222222222222222<br /> 2222222222222222222222222222222222222222<br /> 2222222222222222222222222222222222222222<br /> 2222222222222222222222222222222222222222<br /> </p> <p class="box3" id="a3" onmouseover="toTop('a3')" > 33333333333333333333333333333333333333333333333<br />

Bangalore Institute of Technology

24

De

Sc e ce

33333333333333333333333333333333333333333333333<br /> 33333333333333333333333333333333333333333333 33<br /> 3 33333333333333333333333333333333333333333333333<br /> 33333333333333333333333333333333333333333333333<br /> 33333333333333333333333333333333333333333333333<br /> </p> </body> </html>

OUTPUT:
Initial configuration with mouse placed on the paragraph of 3s

When mouse is moved over to the paragraph of 2s, paragraph of 3s which was previously visible on top, goes to its original position

ec

I6H@69 G@D9967 GA75 F E


e 25

@ D @AD 8697A B@C BA 8@ 9 8765

GAIA@Q P BA 8H 8D 8 @C 7AI6 G@6

De

Sc e ce

When mouse is moved over to the paragraph of 3s, paragraph of 2s which was previously visible on top, goes to its original position rather than to the bottom of stack as in previous program

ec

fSeWSV dWaVVST dXTR c b


e 26

W a WXa USVTX YW` YX UW V UTSR

dXfXWh g YX Ue Ua U W` TXfS dWS

Department of Information Science

Web programming manual

6. a) Design an XML document to store information about a student in an engineering college affiliated to VTU. The information must include USN, name, name of college, branch, year of joining and e-mail id. Make up sample data for 3 students. Create a CSS style sheet and use it to display the document.
BASICS: XML
   Extensible Markup Language (XML) is a way to apply structure to a web page. XML provides a standard open format and mechanisms for structuring a document so that it can be exchanged and manipulated. Like HTML, XML uses tags to mark-up data content. Unlike HTML, in XML we define our own tags that meet the exact needs of our document. The custom tags make our data easier to organize and search. When creating an XML document, we must begin with the XML declaration statement. This statement alerts the browser or other processing tools that this document contains XML tags. The declaration looks like this: <?xml version=1.0?>

XSL
  Extensible Stylesheet Language (XSL) is a language for expressing style sheets specifically for use with XML. It consists of two parts:  Extensible Stylesheet Language Transformer (XSLT)a language for transforming XML documents. XSLT engines are typically used to convert XML into a strict form of HTML known as XHTML.  Formatting Objects (FO)an XML vocabulary for specifying formatting semantics. Formatting Objects are not widely implemented at present (IE5.0 does not implement them). These two parts form the basis of the XSL style sheet that describes how the structured content of the XML data file should be displayed.

PROGRAM: //prog6a.xml
<?xml version = "1.0"?> <?xml-stylesheet type = "text/css" href = "prog6a.css" ?> <students> <VTU> <USN> 1BI07IS001 </USN> <name> Aarti </name> <college> BIT </college> <branch> ISE</branch> <YOJ> 2007 </YOJ> <email> aarti89@gmail.com </email> </VTU> <VTU> <USN> 1BI08CS006</USN> <name> Babu </name> <college> BIT </college> <branch> CSE </branch>

Bangalore Institute of Technology

27

Department of Information Science


<YOJ> 2008 </YOJ> <email> babu007@rediffmail.com </email> </VTU> <VTU> <USN> 1DS09ME005 </USN> <name> Bharat </name> <college> DSIT </college> <branch> Mech </branch> <YOJ> 2009</YOJ> <email> bharat_gowda@yahoo.com </email> </VTU> </students>

Web programming manual

//prog6a.css
USN { font-weight: bold; display: block; color: red; font-family: courier, prestige; font-size: 20pt; } name, college, branch, YOJ, email { font-variant: small-caps; color: navy; display: block; font-size: 15pt; }

Bangalore Institute of Technology

28

De

Sc e ce

OUTPUT:

DESCRIPTION:
The XM defines a STUDENTS tag at the root level to hold information of all the students. To segregate information for each student, a VTU tag is defined within the STUDENTS tag. For each student, the USN, name, college name, branch, year of joining and e-mail ID are stored in separate tags: USN, N ME, COLLEGE, BRANCH, YOJ, EMAIL which are opened and closed within each VTU tag. There is a reference to a CSS sheet which is used to display the information from the XML.

ec

ptps txsspq uqi y


e 29

t x tux rpsqu vtw vu rt s rqpi

uut vu r rx r tw qup tp

Department of Information Science

Web programming manual

b) Create an XSLT style sheet for one student element of the above document and use it to create a display of that element.
PROGRAM: //prog6b.xml
<?xml version = "1.0"?> <?xml-stylesheet type = "text/xsl" href = "prog6b.xsl" ?> <VTU> <USN> 1BI07IS001 </USN> <name> Aarti </name> <college> BIT </college> <branch> ISE </branch> <YOJ> 2007 </YOJ> <email> aarti89@gmail.com </email> </VTU>

//prog6b.xsl
<?xml version = "1.0"?> <xsl:stylesheet version = "1.0" xmlns:xsl = "http://www.w3.org/1999/XSL/Transform" xmlns = "http://www.w3.org/1999/xhtml"> <xsl:template match = "VTU"> <html> <head> <title> STUDENT DESCRIPTION </title> </head> <body> <h2> VTU STUDENT DESCRIPTION </h2> <span style="font-style: italic; color: blue;">USN:</span> <xsl:value-of select = "USN" /> <br /> <span style="font-style: italic; color: blue;">NAME:</span> <xsl:value-of select = "name" /> <br /> <span style="font-style: italic; color: blue;">COLLEGE:</span> <xsl:value-of select = "college" /> <br /> <span style="font-style: italic; color: blue;">BRANCH:</span> <xsl:value-of select = "branch" /> <br /> <span style="font-style: italic; color: blue;">YEAR OF JOIN:</span> <xsl:value-of select = "YOJ" /> <br /> <span style="font-style: italic; color: blue;">E-MAIL:</span> <xsl:value-of select = "email" /> <br /> </body> </html> </xsl:template> </xsl:stylesheet>

Bangalore Institute of Technology

30

De

Sc e ce

OUTPUT:

DESCRIPTION:
The XML defines a STUDENTS tag at the root level to hold information of all the students. To segregate information for each student, a VTU tag is defined within the STUDENTS tag. For each student, the USN, name, college name, branch, year of joining and e-mail ID are stored in separate tags: USN, NAME, COLLEGE, BRANCH, YOJ, EMAIL which are opened and closed within each VTU tag. There is a reference to an XSL sheet which is used to display the information from the XML. The XSL is defined such that when the template matches to VTU, all the information stored in all the tags under VTU is displayed.

ec

gf e e d
e 31

egi h f g e

De

Sc e ce

7. a) Write a Perl program to display various server information li e server name, server software, server protocol, CGI revision, etc.
//prog7a.pl
#! C:/Perl/bin/perl -w use CGI':standard'; print "content-type:text/html","\n\n"; print "<html>\n"; print "<head> <title> SERVER INFORMATION </title> </head>\n"; print "<body><h1> About this server </h1>","\n"; print "<hr><h3>"; print "Server name : ",$ENV{'SERVER NAME'},"<br>"; print "Running on port : ",$ENV{'SERVER P ORT'},"<br>"; print "Server Software : ",$ENV{'SERVER S OFTWARE'},"<br>"; print "Server protocol : ",$ENV{'SERVER PROTOCOL'},"<br>"; print "CGI-Version : ",$ENV{'GATEWAY_INTERFACE'},"<br>"; print "Root Document : ",$ENV{'DOCUMENT_ROOT'},"<br>"; print "</h3><hr>\n"; print "</body></html>\n"; exit(0);

OUTPUT:

ec

xkwokn vosnnkl vplj u t


e

{ { {

o s ops mknlp qor qp mo n mlkj

vpxpoz y qp mw ms m or lpxk vok

32

Department of Information Science

Web programming manual

DESCRIPTION:
The above program uses CGI standard and should be saved under folder cgi-bin which is a subdirectory of public.html. All these server related information are stored as a list of Environment variables. Environment variables are used by the operating system to store bits of information that are needed to run the computer. They are called environment variables because we rarely need to use them and they simply remain in the background as just another part of the overall computing environment of our system. When the Perl process is started, it is given a copy of the environment variables to use as needed. These environment variables can be accessed in a Perl program and printed using $ENV function. We use print command to print these accessed values.

NOTE:
The Perl files are stored in C://wamp/bin/apache/Apache2.2.11/cgi-bin/folder_name/file_name.

Bangalore Institute of Technology

33

De

Sc e ce

b) Write a Perl program to accept UNIX command from an HTML form and to display the output of the command executed.
//prog7b.html
<?xml version = "1.0" encoding = "utf-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>EXECUTION OF UNIX COMMANDS</title> </head> <body> <form action="http://localhost/cgi-bin/divya/prog7b.pl"> Enter command: <input type="text" name="com"> <input type="submit" name="Submit"> </form> </body> </html>

//prog7b.pl
#! C:/perl/bin/perl -w use CGI':standard'; print "content-type:text/html \n\n"; $c=param('com'); $v=system($c); print "<html>\n"; print "<head> <title> COMMAND EXECUTED </title> </head>\n"; print "<body><h1>","\n"; print "</h1></body></html>\n"; exit(0);

OUTPUT:

ec

}} }~ ~|
e 34

}~  ~}|

   ~} }

De

Sc e ce

DESCRIPTION:
Above program accepts a UNIX command from the user using the HTML file. The code to execute this command is embedded in a Perl program. A reference to this Perl program is given in the form action field. Command to be executed is entered in the text box. Once Submit is pressed, entered command is passed to the Perl program, where we use system() command to execute the command. system() command does exactly the same thing as exec list, except that a fork is done first, and the parent process waits for the child process to complete. system() executes the command specified. It doesn't capture the output of the command. system() accepts as argument either a scalar or an array. If the argument is a scalar, system() uses a shell to execute the command ("/bin/sh -c command"). If the argument is an array it executes the command directly, considering the first element of the array as the command name and the remaining array elements as arguments to the command to be executed.

ec


e 35

Department of Information Science

Web programming manual

8. a) Write a Perl program to accept the user name and display a greeting message randomly chosen from a list of 4 greetings.
PROGRAM: //prog8a.pl
#! C:/perl/bin/perl -w use CGI ':standard'; @coins = ("Welcome to Web Programming Lab","Have a nice time in lab", "Practice all the programs", "Well done.Good Day"); $range = 4; #>>>pick a random number in the range $random_number = int(rand($range)); if(param) { print header(); #>>>set the title in the title bar, the background colour and the text colour print start_html(-title=>"USER NAME",-bgcolor=>"brown",-text=>"white"); #>>>initialize a variable cmd to store the user entered input $cmd=param("Name"); #>>>print the data along with the randomly picked phrase in the array coins print b("Hello $cmd, $coins[$random_number]"),br(); print start_form(); print submit(-value=>"Back"); print end_form(); print end_html(); } else { print header(); print start_html(-title=>"ENTER USER NAME",-bgcolor=>"skyblue",-text=>"black"); #>>>set the name and value attributes for textfield and submit print "<h3>Enter username: </h3>"; print start_form(),textfield(-name=>"Name",-value=>" "), submit(-name=>"submit", -value=>"Submit"),reset(); print end_form(); print end_html(); }

Bangalore Institute of Technology

36

De

Sc e ce

OUTPUT:

DESCRIPTION:
In the above program, 4 greeting messages are given in an array named coins. In Perl, arrays begin with the symbol @ and variables with the symbol $. The array elements are referenced through subscripts delimited by square brackets([ ]). The subscript can be any numeric valued expression. Output is directed to the screen with the print operator. The operand for print is one or more string literals, separated by commas.

ec


e 37

De

Sc e ce

b) Write a Perl program to keep track of the number of visitors visiting theweb page and to display this count of visitors, with proper headings.
PROGRAM: //prog8b.pl
#! C:/perl/bin/perl -w use CGI ':standard'; use CGI::carp qw(WarningsToBrowser); print header(); #>>>Set the title in the title bar, the background color and the text colour print start_html(-title=>"WEB PAGE COUNTER", -bgcolor=>"yellow",-text=>"black"); open(FILE,'<count.txt'); $count=<FILE>; close(FILE); $count++; open(FILE,'>count.txt'); print FILE "$count"; print b("This page has been viewed $count times"); close(FILE); print end_html();

OUTPUT:

DESCRIPTION:
In the above program, a variable count is used to keep track of the number of times the page is viewed. This count is stored in a file called count.txt. Whenever the page is visited again, the file count.txt is opened, the count in it is incremented, displayed on screen and updated back in the file before closing it. The open function establishes a relationship between a filehandle and a files external name. The 1st parameter to open is the filehandle, the 2nd specifies the files external name and how it will be used. The > file use specification indicates the file is to be opened for output and writing is to begin at the files beginning overwriting any data written there already.

ec


e 38

De

Sc e ce

9. Write a Perl program to display a digital clock which displays the current time of the server.
PROGRAM: //prog9.pl
#!C:/perl/bin/perl -w #>>> specifies where the Perl interpreter is use CGI':standard'; #>>> to use standard module available in CGI.pm to generate html tags print "Refresh: 1\n"; #>>> refresh the page after 1 sec print "Content-Type: text/html\n\n"; #>>> setting content of the server response to html document print start_html(-title=>"DIGITAL CLOCK",-bgcolor=>"orange",-text=>"black"); #>>> uses CGI.pm to print the title, setting background colour ($s,$m,$h)=localtime(time); #>>> to get the current time print br,br,"The current system time is $h:$m:$s"; #>>> equivalent to<br /><br /> of xhtml and print the time print br,br,hr,"In words $h hours $m minutes $s seconds"; #>>>ends the HTML document by printing the </BODY> and </HTML> tags print end_html;

OUTPUT:

ec


e 39

Department of Information Science

Web programming manual

10. Write a Perl program to insert name and age information entered by the user into a table created using MySQL and to display the current contents of this table.
PROGRAM: //prog10.html
<?xml version = "1.0" encoding = "utf-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <body> <form action="http://localhost/cgi-bin/divya/prog10.pl"> Name : <input type="text" name="name"> <br /> Age : <input type="text" name="age"> <br /> <input type="submit" value="Submit"> </form> </body> </html>

//prog10.pl
#! C: /perl/bin/perl -w use CGI ':standard'; print "Content-type: text/html\n\n"; print "<html><title>Result of insert operation </title>"; use DBI; #<<< to connect to database interface with database name-divya, login ID-root & password-ise123 $dbh=DBI->connect("DBI:mysql:divya","root","ise123"); #<<< to store the values of name and age from the input entered in the text boxes of the form $name=param("name"); $age=param("age"); $qh=$dbh->prepare("insert into student values('$name','$age')"); $qh->execute(); $qh=$dbh->prepare("select from student"); $qh->execute(); print "<table border size=1><tr><th>Name</th><th>Age</th></tr>"; #<<< to display data retrieved from the database to the HTML page while ( ($name,$age)=$qh->fetchrow()) { print "<tr><td>$name</td><td>$age</td></tr>"; } print "</table>"; #<<< to inform that the database operation is finished $qh->finish(); #<<< close the connection to the database $dbh->disconnect(); print"</html>";

Bangalore Institute of Technology

40


e s e ec

De

OUTPUT:

MySQL console:

Sc e ce

41

De

Sc e ce

DESCRIPTION:
Before executing the above program, we need to do the following steps: a. Click on the Wamp Server icon in the task bar. Select MySQL -> MySQL Console b. MySQL console opens asking for password. The password(ise123) is entered c. Database is created using the following command: create database database_name; d. To use the database created, the following command is used: use database_name; e. Create the table student using the following SQL command: create table student ( name varchar(20), age int(2) ); A screenshot of the above steps performed is included in the output.

ec


e 42

11. Write a PHP program to store current date -time in a COOKIE and display the Last visited on date-time on the web page upon reopening of the same page.
PROGRAM: //prog11.php
<?php //start of the program date_default_timeZone_set('Asia/Calcutta'); //to set the time zone //Calculate 60 days in the future using seconds * minutes * hours * days + current time $inTwoMonths = 60 * 60 * 24 * 60 + time(); //To create cookie with name lastVisit whose value is the date and time returned by date() setcookie('lastVisit', date("G:i - m/d/y"), $inTwoMonths); if(isset($_COOKIE['lastVisit'])) { $visit = $_COOKIE['lastVisit']; //To print the time and date of last visit echo "Your last visit was - ". $visit; } else echo "You have got some stale cookies!"; ?>

OUTPUT:
1.

2.

ec

De

Sc e ce

43

Department of Information Science DESCRIPTION:


 

Web programming manual

 

  

A cookie is a small object of information that consists of a name and a textual value. It is created by some software system on the server. It is assigned a lifetime at the time of creation. Once it reaches its associated lifetime, the cookie is deleted from the browsers host machine. A cookie is set in PHP with the setcookie function. This function takes one or more parameters. The first parameter is mandatory, it is the cookies name given as a string. The second parameter, if present, is the new value for the cookie, also a string. If the value is absent, setcookie undefines the cookie. The third parameter, when present, is the expiration time in seconds for the cookie given as an integer. The default value for the expiration time is zero, which specifies that the cookie is destroyed at the end of the current session. date(G:I m/d/y) function returns the current date and time in the format specified as the parameter.  G - 24hr format of an hour  i-minutes  m-numeric representation of the month  d-day of the month ,2digits with leading zeros  y-a two digit representation of the year date_default_timeZone_set(Asia/Calcutta) is the function which sets the default time zone used by all date/time functions in a script. The time zone identifier is passed as a parameter to it. time() function returns the current time in seconds The other cookie operations are getting the cookies and their values from subsequent browser requests. In PHP, cookie values are treated much like form values. All cookies that arrive with a request are placed in the implicit $_COOKIE array, which has the cookie names as keys and the cookie values as values. A PHP script can test whether a cookie came with a request by using the isset predicate function on the associated variable.

NOTE:
The PHP files are stored in C://wamp/www/folder_name/file_name

Bangalore Institute of Technology

44

12. Write a PHP program to store page views count in SESSION, to increment the cont on each refresh, and to show the count on web page.
PROGRAM: //prog12.php
<?php session_start(); //a session ID is created and recorded //session key-value pairs are created or changed by assignments to the _SESSION array $_SESSION["count"]++; //each time the page is loaded, the count is incremented echo "<p>The counter is now <b>$_SESSION[count]</b></p>". "<p>Reload this page to increment</p>";

OUTPUT:

ec

 

De

Sc e ce

      

   ! 

      

        

45

Department of Information Science

Web programming manual

13. Create an XHTML form with name, address line 1, address line 2 and e-mail text fields. On submitting, store the values in MySQL table. Retrieve and display the data based on name.
PROGRAM: //prog13a.php
<html> <head><title>Result of insert operation</title></head> </body> <?php //connect to database with server-localhost, user-root and password-ise123 $dbh=mysql_connect('localhost','root','ise123') or die(mysql_error()); //select the database mysql_select_db('divya') or die(mysql_error()); //isset-to determine if a variable is set and is not NULL if(isset($_POST['name'])) { $nme=$_POST['name']; $ad1=$_POST['add1']; $ad2=$_POST['add2']; $eml=$_POST['email']; if($nme!="" && $ad1!="") { //insert details into table contact $query=mysql_query("INSERT INTO contact VALUES('$nme','$ad1','$ad2','$eml')"); echo "<h2>1 row inserted</h2>"; } else echo "<h2>Missing field(s)</h2>"; } //terminate the connection mysql_close($dbh); ?> </body> </html>

//prog13b.php
<html> <head><title>Search Result</title></head> <body> <?php $link=mysql_connect("localhost","root","ise123") or die(mysql_error()); mysql_select_db("divya") or die(mysql_error()); $n=$_POST["name1"]; if($n == null) { print "<h2>Please enter the search element </h2>"; } else {

Bangalore Institute of Technology

46

Department of Information Science

Web programming manual

print "Entered Name is <h4> \"$n\" </h4>"; //search and retrieve records based on name $var=mysql_query("SELECT FROM contact WHERE name='$n'"); $num_rows=mysql_num_rows($var); if($num_rows > 0) { echo"<table border size=1>"; echo"<tr><th>Name</th><th>Address 1</th><th>Address 2</th><th>E-mail</th></tr>"; //fetch every row of the result and display in table while ($arr=mysql_fetch_row($var)) { echo "<tr><td>$arr[0]</td><td>$arr[1]</td><td>$arr[2]</td><td>$arr[3]</td></tr>"; } echo"</table>"; } else { print "<h4>No such records found</h4>"; } mysql_free_result($var); } mysql_close($link); ?> </body> </html>

//prog13c.html
<html> <head><title>Enter Details</title></head> <body> <h3>Enter the Details</h3> <form action=http://localhost/prog13a.php method="post"> Name: <input type="text" name="name"><br /> Address1: <input type="text" name="add1"><br /> Address2: <input type="text" name="add2"><br /> Email: <input type="text" name="email"><br /> <input type=submit> </form> <h3>Search Details</h3> <form action=http://localhost/prog13b.php method="post"> Enter name for search: <input type="text" name="name1"><br /> <input type=submit> </form> </body> </html>

Bangalore Institute of Technology

"

47

)7 ) ( 9 5

) 6 2 ( 1 % )7 $ ( $ 5 80 & &&

7$6($' (2''$% )%# 4 5 5 3

()2 $'%) (1 ) ( ' %$# & & 0 0 &

De

Sc e ce

( 2

OUTPUT:

1.

2.

ec

y e

48

FT F E V R

F S I E H B FT A E A R UG C CC

TASEAD EIDDAB FB@ Q R R P

EFI ADBF EH F E D BA@ C C G G C

De

Sc e ce

E I

3.

ec

y e

49

4.

NOTE:
All the PHP and HTML programs need to be stored in C://wamp/www. Also, create database contact using the following command: create table contact( name varchar(20), address1 varchar(30), address2 varchar(30), email varchar(40));

ec

b f

De

Sc e ce

qXpbXa bfaaXY cYW h i i g

cq c b s i

bcf XaYc be c b a YXW ` ` d d `

c p f b e Y cq X b X i rd ` ``

50

Department of Information Science

Web programming manual

14. Using PHP and MySQL, develop a program to accept book information viz. Accession number, title, authors, edition and publisher from a web page and store the information in a database and to search for a book with the title specified by the user and to display the search results with proper headings.
PROGRAM: //prog14a.php
<html> <head><title>Result of insert operation</title></head> </body> <?php //connect to database with server-localhost, user-root and password-ise123 $dbh=mysql_connect('localhost','root','ise123') or die(mysql_error()); //select the database mysql_select_db('divya') or die(mysql_error()); //isset-to determine if a variable is set and is not NULL if(isset($_POST['accno'])) { $ano=$_POST['accno']; $ttl=$_POST['title']; $aut=$_POST['author']; $pbl=$_POST['publi']; $edi=$_POST['edn']; if($ano!="" && $ttl!="") { //insert details into table book $query=mysql_query("INSERT INTO book VALUES('$ano','$ttl','$aut','$pbl','$edi')"); echo "<h2>1 row inserted</h2>"; } else echo "<h2>Missing field(s)</h2>"; } //terminate the connection mysql_close($dbh); ?> </body> </html>

//prog14b.php
<html> <head><title>Search Result</title></head> <body> <?php $link=mysql_connect("localhost","root","ise123") or die(mysql_error()); mysql_select_db("divya") or die(mysql_error()); $t=$_POST["title1"]; if($t == null) { print "<h2>Please enter the search element </h2>"; } else

Bangalore Institute of Technology

51

Department of Information Science

Web programming manual

{ print "Entered Title is <h4> \"$t\" </h4>"; //search and retrieve records based on name $var=mysql_query("SELECT FROM book WHERE title='$t'"); $num_rows=mysql_num_rows($var); if($num_rows > 0) { echo"<table border size=1>"; echo"<tr><th>Accession No.</th><th>Title</th><th>Author</th><th>Publication</th><th>Edition</th></tr>"; //fetch every row of the result and display in table while ($arr=mysql_fetch_row($var)) { echo "<tr><td>$arr[0]</td><td>$arr[1]</td><td>$arr[2]</td><td>$arr[3]</td><td>$arr[4]</td></tr>"; } echo"</table>"; } else { print "<h4>No such records found</h4>"; } mysql_free_result($var); } mysql_close($link); ?> </body> </html>

//prog14c.html
<html> <head><title>Enter Details</title></head> <body> <h3>Enter the Details</h3> <form action=http://localhost/prog14a.php method="post"> Accession Number: <input type="text" name="accno"><br /> Title: <input type="text" name="title"><br /> Author: <input type="text" name="author"><br /> Publication: <input type="text" name="publi"><br /> Edition: <input type="text" name="edn"><br /> <input type=submit> </form> <h3>Search Details</h3> <form action=http://localhost/prog14b.php method="post"> Enter title of the book for search: <input type="text" name="title1"><br /> <input type=submit> </form> </body> </html>

Bangalore Institute of Technology

52

w v v x xx

vvy yyvw wu

vyw y wvu x x x

De

Sc e ce

OUTPUT:

1.

2.

ec

y e

53

j l h

i e d j h k

ji e g h h f

e d

De

Sc e ce

3.

ec

y e

54

4.

NOTE:
Create the table book using the following command: create table book( accno varchar(10), title varchar(30), author varchar(30), publication varchar(30), edition int(2));

ec

r v

De

Sc e ce

{nzrnq rvqqno som x y y w

s{ s r } y

rsv nqos ru s r q onm p p t t p

s z v r u o s{ n r n y |t p pp

55

You might also like