BCA 236-Computer Networks & Web Programming Laboratory PDF
BCA 236-Computer Networks & Web Programming Laboratory PDF
BCA 236-Computer Networks & Web Programming Laboratory PDF
S.Y.B. C. A. (Science)
SEMESTER III
Lab Course
BCA - 236
Computer Networks
&
Web Programming Laboratory
From the Chairman’s Desk
It gives me a great pleasure to present this workbook prepared by the Board of studies in Computer
Applications.
The workbook has been prepared with the objectives of bringing uniformity in implementation of
lab assignments across all affiliated colleges, act as a ready reference for both fast and slow learners
and facilitate continuous assessment using clearly defined rubrics.
The workbook provides, for each of the assignments, the aims, pre-requisites, related theoretical
concepts with suitable examples wherever necessary, guidelines for the faculty/lab administrator,
instructions for the students to perform assignments and a set of exercises divided into three sets.
I am thankful to the Chairman of this course and the entire team of editors. I am also thankful to the
reviewers and members of BOS, Mr. Rahul Patil and Mr. Arun Gangarde. I thank all members of
BOS and everyone who have contributed directly or indirectly for the preparation of the workbook.
Constructive criticism is welcome and to be communicated to the Chairman of the Course and
overall coordinator Mr. Rahul Patil. Affiliated colleges are requested to collect feedbacks from the
students for the further improvements.
I am thankful to Hon. Vice Chancellor of Savitribai Phule Pune University Prof. Dr. Nitin
Karmalkar and the Dean of Faculty of Science and Technology Prof. Dr. M G Chaskar for their
support and guidance.
Priyamveda U. Patil
Mrs. Veena Kiran Gandhi
Sneha Ganesh Chavan
Aparna Tushar Gohad
Preeti Gawade
Mohsin Tamboli
Compiled By:
Prof. Kishor Dhane ( Chairman, Computer Networks & Web Programming Laboratory)
VPASC,Baramati
Reviewed By:
Assignment Completion Sheet
Lab Course BCA 236: Computer Networks & Web Programming
Laboratory
1. Networking Commands
7. CSS
8. Basics of JavaScript
9. Functions in JavaScript
13. Cookies
14. XML
This is to certify that Mr/Ms. _____________________________
Date:______________
Coaxial Cable Connector:The most common type of connector used with coaxial cables is the
Bayone-Neill-Concelman (BNC) connector. Different types of adapters are available for BNC connectors,
including a T-connector, barrel connector, and terminator. Connectors on the cable are the weakest points in
any network. To help avoid problems with your network, always use the BNC connectors that crimp,
rather screw, onto the cable.
3. Fiber Optic Cable:Fiber optic cabling consists of a center glass core surrounded by several layers of
protective materials. It transmits light rather than electronic signals eliminating the problem of electrical
interference. This makes it ideal for certain environments that contain a large amount of electrical
interference. It has also made it the standard for connecting networks between buildings, due to its immunity
to the effects of moisture and lighting.
Fiber optic cable has the ability to transmit signals over much longer distances than coaxial and twisted pair.
It also has the capability to carry information at vastly greater speeds. This capacity broadens communication
possibilities to include services such as video conferencing and interactive services. The cost of fiber optic
cabling is comparable to copper cabling; however, it is more difficult to install and modify. 10BaseF refers to
the specifications for fiber optic cable carrying Ethernet signals.
Types of devices:
1. Repeater – A repeater operates at the physical layer. Its job is to regenerate the signal over the same
network before the signal becomes too weak or corrupted so as to extend the length to which the signal can be
transmitted over the same network. An important point to be noted about repeaters is that they do not amplify
the signal. When the signal becomes weak, they copy the signal bit by bit and regenerate it at the original
strength. It is a 2 port device.
2. Hub – A hub is basically a multiport repeater. A hub connects multiple wires coming from different
branches, for example, the connector in star topology which connects different stations. Hubs cannot filter
data, so data packets are sent to all connected devices. In other words, collision domain of all hosts
connected through Hub remains one. Also, they do not have intelligence to find out best path for data
packets which leads to inefficiencies and wastage.
3. Bridge – A bridge operates at data link layer. A bridge is a repeater, with add on the functionality of
filtering content by reading the MAC addresses of source and destination. It is also used for interconnecting
two LANs working on the same protocol. It has a single input and single output port, thus making it a 2 port
device.
4. Switch – A switch is a multiport bridge with a buffer and a design that can boost it efficiency (a large
number of ports imply less traffic) and performance. A switch is a data link layer device. The switch can
perform error checking before forwarding data, which makes it very efficient as it does not forward packets
that have errors and forward good packets selectively to correct port only.
5. Routers – A router is a device like a switch that routes data packets based on their IP addresses. Router is
mainly a Network Layer device. Routers normally connect LANs and WANs together and have a
dynamically updating routing table based on which they make decisions on routing the data packets. Router
divide broadcast domains of hosts connected through it.
6. Gateways- A gateway, as the name suggests, is a passage to connect two networks together that may
work upon different networking models. They basically work as the messenger agents that take data from
one system, interpret it, and transfer it to another system. Gateways are also called protocol converters and
can operate at any network layer. Gateways are generally more complex than switch or router.
LAB Exercise:
SET A
1. Use ping command to check connectivity of any website.
2. Use ping command to check connectivity of your departmental server by using ip address.
3. Write a command to get name of your computer.
4. Use traceroute command to trace the route of ant packet.
5. See the output of netstat command.
6. Write a command to display information of user.
7. Use nmap command to display information of any website using website name or ip address of site.
8. Use nslookup command to display ipaddress or DNS of website.
SET B
1. Check your computer lab setup. Check the types of cables and devices used.
Note: Instructors are expected to show types of cables and devices that are available in college lab.
Assignment Evaluation
0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]
LAB Exercise:
SET A
1. Type a command to get MAC and IP address of your machine.
2. Try all options of the same command.
SET B
1. Identify the topology used in your computer lab with the help of instructor.
Draw that topology in your notebook.
Assignment Evaluation
0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]
Distraction-free interface
Auto-completion feature
Plug-in options for extended functionalities.
Cons
Inside the <head> tag, there is one tag that is always included: <title>,
<title>This is where we insert the page name as it will appear at the top of the browser window or tab.
III. HTML documents :
HTML documents are text files made up of HTML elements.
HTML elements are defined using HTML tags.
HTML Tags :
o HTML tags are used to mark-up HTML elements
o HTML tags are surrounded by the two characters < and >
o The surrounding characters are called angle brackets
o HTML tags normally come in pairs like <b> and </b>
o The first tag in a pair is the start tag, the second tag is the end tag
o The text between the start and end tags is the element content
o HTML tags are not case sensitive, <b> means the same as <B>
2. <body>
This is my first homepage. <b>This text is bold</b>
</body>
This HTML element starts with the start tag <body>, and ends with the end tag
</body>.
The purpose of the <body> tag is to define the HTML element that contains the
body of the HTML document.
Headings :
Headings are defined with the <h1> to <h6> tags.
<h1> defines the largest heading And <h6> defines the smallest heading.
<h1>This is a heading</h1>
<h2>This is a heading</h2>
<h3>This is a heading</h3>
<h4>This is a heading</h4>
<h5>This is a heading</h5>
<h6>This is a heading</h6>
HTML automatically adds an extra blank line before and after a heading.
Paragraphs :
Paragraphs are defined with the <p> tag.
<p>This is a paragraph</p>
<p>This is another paragraph</p>
HTML automatically adds an extra blank line before and after a paragraph.
<pre>
This is useful for preserving the format,
It displays text the way you type them.
</pre>
Line Breaks :
The <br> tag is used when you want to end a line, but don't want to start a new
paragraph.
The <br> tag forces a line break wherever you place it.
For example : <p>This <br> is a para<br>graph with line breaks</p>
The <br> tag is an empty tag. It has no closing tag.
We can use the <br> element whenever you need to add an HTML new line
to separate your paragraphs with a horizontal line instead of a simple HTML paragraph break,
use the <hr> element
For example:
<h1>S.Y.B.C.A</h1>
<h2>Web Technology </h2>
<p>It is a course designed for S.Y.B.C.A </p>
<hr>
<h2>CN</h2>
<p>Study the basic concepts of computer networks.</p>
Comments :
The comment tag is used to insert a comment in the HTML source code.
Acomment will be ignored by the browser.
You can use comments to explain yourcode, which can help you when you edit the source code at a later date.
<!-- This is a comment -->
Note that you need an exclamation point after the opening bracket, but not before
the closing bracket.
Summarize above tags :
Tag Description Tag Description
<html> Defines an HTML document
<body> Defines the document's body
<h1> to <h6> Defines header 1 to header 6
<p> Defines a paragraph
<br> Inserts a single line break
<hr> Defines a horizontal rule
<!--> Defines a comment
href Attribute
The <a> tag defines a hyperlink. The href attribute specifies the URL of the page the link goes to:
Example
<a href="https://www.google.com">Search Engine</a>
Example
<img src="imag1.jpg" alt="My Image">
Solved Assignments.
I. Check the output of the following :
1. <Html>
<Head>
<Title>The First Page</title>
</head>
<Body>
Hello World
</body>
</html>
2. <!DOCTYPE html>
<html>
<body>
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
<h4>This is heading 4</h4>
<h5>This is heading 5</h5>
<h6>This is heading 6</h6>
</body>
</html>
Explanation of example:
• The <!DOCTYPE html> declaration defines this document to be HTML5.
• The <html> element is the root element of an HTML page.
• The <head> element contains meta information about the document.
• The <title> element specifies a title for the document.
• The <body> element contains the visible page content.
3.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>coffee restaurant </title>
</head>
<body>
Coffee Restautant
The Restaurant
The Coffee Restaurant offers casual lunch and dinner fare in a hip atmosphere. The menu changes regularly
to highlight the freshest ingredients.
Catering
You have fun... we'll do the cooking. Coffee Restautant can handle events from snacks for club to elegant
corporates..
Location and Hours New Highway,Mumbai ; Monday through Thursday 11am to 9pm, Friday and
Saturday, 11am to midnight
</body>
</html>
Explanation:
Create the document head that contains the title for the page. Insert <head> and </head> tags before the
content. Within the head element, add information about the character encoding <meta charset="utf-8">, and
the title, “Black Goose Bistro”, surrounded by opening and closing <title> tags
4.<!DOCTYPE html>
<html>
<head>
<title>Display_Paragraph</title>
</head>
<body>
<pre>
This paragraph has multiple
lines. But it is displayed
as it is unlike the paragraph
tag.
</pre>
<pre>
This paragraph has multiple
spaces. But it is displayed
as it is unlike the paragraph
tag.
</pre>
</body>
</html>
5.
<!-- Write HTML code here -->
<head>
<title>Wel-Come All</title>
<style type="text/css">
h1{
color:#0FFFF0;
background-color: hsl(200, 50%, 20%);
color: hsl(200, 20%, 90%);
h4{
color:rgb(0, 255, 0);
background-color: hsl(150, 20%, 40%);
color: hsl(360, 30%, 90%);
}
li{
color:rgba(11, 99, 150, 1);
background-color: hsl(250, 45%, 60%);
color: hsl(175, 35%, 87%);
}
</style>
</head>
<body>
<h1>Wel-Come All</h1>
<h4>Subjects for SY</h4>
<ul>
<li>Data Structure</li>
<li>Computer Networks</li>
<li>Web Tecnology</li>
</ul>
</body>
</html>
LAB Exercise:
Set A
1. Create an html page with all the different text styles (bold, italic and underlined) and its combinations on
separate lines. State style of each line in its text.
2.Create an html page containing the polynomial expression as follows:
A0+A1X+A2X2+A3X3
3. Write a HTML script to display following screen in figure 1.
Set B
1. Create an html page with red background with a message “warning” in large size blinking.
Add scrolling text “read the message” below it.
Set C :
<head>
<title>Image Hyperlink Example</title>
</head>
<body>
<p>Click following link</p>
<ahref="google.com"target="_self">
<imgsrc=Myimg.png"alt="Search"border="0"/>
</a>
</body>
</html>
_self Opens the linked document in the same frame as it was clicked (this is default)
_top Opens the linked document in the full body of the window
Set C:
1.From Assignment 1 , Set C, Program 2
a. Insert the image for each historical place
b. Create a hyperlink on all images .
c. on clicking the image the information of those places.
Assignment Evaluation
0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]
This assignment will be divided into two parts Part I will be about Git and Part II about GitHub.
PART-I
Before we get started with what is git and GitHub we need to understand the sheer importance of it and
why is it widelyused in the IT industry extremely.
To begin with, I would like to introduce you to the Version Control System (VCS). It tracks the history of
changes as people and teams collaborate on projects together. As the project evolves, teams can run tests,
fixbugs, and contribute new code with the confidence that any version can be recovered at any time.
Developers can review project history to find out:
Which changes were made?
Who made the changes?
When were the changes made?
Why were the changes needed?
Why GitHub?
Apart from definition, I would like to take you through real-world scenarios to understand this in a
very Crispway. In a company, you aren't the only person who works on a project but the entire team
does. Thework is divided between all the team members. Now if you and one of your colleagues are
working on thesame web page and didn't communicate with each other about it there will be clashes.
To avoid that git helpsyou to know who is working on which part of the code as well as when you
make numerous changes to yourcode. You submit the changes once to git and next time you think I
need to make more changes to it.
Then you change it and again submit it. You end up doing this 6 times more. So, there will be a total of
8files which you have submitted serving the same purpose but some modification done to the file.
Each file has a different modification. Then you end up thinking what I did the 3rd time was the
perfect code. The best partis you can get the 3rd modified file and restore it. That is about Version
Control System.
Developers work in every time zone. With a Distributed VCS like Git, collaboration can happen any
time while maintaining source code integrity. Using branches, developers can safely propose changes
to production code.
GitHub has your various versions of your files that are stored on the cloud. There are many VCS but
why we choose just GitHub? Because it is open source as well as the above benefits listed above.
Git is a remote repository which is only limited to your personal computer or laptop.
GitHub hosts your remote repository online on web page so others can see your work.
Both of them are collaborated. Git commands are used to upload the project on the GitHub
"BY THE WAY GIT AND GITHUB ARE NOT SAME"
Installation of Git:
Lets go ahead and see how the installation is supposed to be done, it would be based on windows10
64bit, but there would be youtube videos for unix, macbook and windows7.
1) Pen Browser and then type this url: https://git-scm.com/downloads
This below page would open.
Click on next.
3) Path in which git will be stored. Keep it default if you don’t want to change it.
Click on next after that.
4) Select the required fields and then click on next.
6) There will be multiple options given to you on for your preference if not vim editor you
can
Choose any other editor from the drop down and then click on next.
7) Instead of manually going and setting the path git gives you an option to set the path in
the installation itself so select second option and click on next.
8) Click on the first option of OpenSSL Library and then click on next.
9) For the next all pictures you just have to select whatever given and click on next.
10) Click on install after selecting enable experimental support for pseudo consoles.
11) Once you click on install it will start installing on your pc/ laptop.
12) When done installing this pop will appear. Select both options and click on next.
13) It will open Release Notes related to Git and you can go through the details of git.
14) It will parallelly open Git Bash Terminal as well. It is a command prompt like shell
Which acts completely like linux terminal accepting commands like ls.
15) Create a folder on the desktop to make it remote repository. Which makes it will be only
used
For programs or projects.
16) Get into the folder you made. Right click and you’d see options like given below. Select
GitBash and it will open the GitBash terminal in there or you can use the cd command to
go
The files location as well.
17) The Git Bash Terminal would open will path as git folder as shown below.
18) Later on, type these commands to set user name and email id which you will register on
Github account. Given one wrong command the second one to show you how errors
appear.
Even if one thing is missing in the command.
1) git status
Show modified files in working directory, staged for your next commit.
SETUP & INIT configuring user information, initializing and cloning repositories
1) gitinit
Initialize an existing directory as a Git repository.
BRANCH & MERGE Isolating work in branches, changing context, and integrating changes
1) git branch
List your branches. a * will appear next to the currently active branch.
3) git checkout
Switch to another branch and check it out into your working directory.
b. Once you double click the image will appear on your screen.
c. A pop will appear on your screen like the image given below. Click on Sign in to GitHub.com
d. Then registration/signup link will be showcased by the website. If you don’t have an account.
Click on Create an account.
f. It will prompt if you have filled anything wrong just like the below image.
g. Once you fill all the details it will ask you to verify your account:
h. Verification will be sent to your email id which you have given while registration. Go to your email and
check once and verify it from there. Click on verify button.
1) When I create a new repository it will take me to this particular page inside which there is a code section.
You have to select that command and then paste it on the Git Bash from git folder which we made it earlier.
Command: git remote add origin “<your githuburl, not mine>”.
2) In this you remote repository is added. Next, step would be to go settings at top right corner and click on
settings.
3) Once you go on settings you have to go at and select SSH and GPG keys section on left middle section of web
page.
4) Then in this you will have to select generate ssh keys which is highlighted for you. Click on it.
5) Then go on to the link which is highlighted below it would open in new tab.
6) Then copy this link and then paste it on your GitBash Terminal.
Copy the above command and instead of you email type your email id which you have registered it with
github
And used it as user.email during git.
7) I have overidded it but in your case it wont have any option. When it asks for enter passphrase just keep on
hitting
The enter button.
Key gets generated in here. Now, we want to deploy this ssh key.
8) Then run this command to get agent key.
Command: eval $(ssh-agent -s)
Once you type this command hit enter then you’ll se agent id as output.
10) Then go back to the GitHub web page. Click on adding yourssh key to ssh-agent which is highlighted.
11) Which will take you to the section link which you’d have to link.
13) When you copy paste this command with cat. It will give you the following output.
14) Then you have to select the entire output copy it and then paste it at new ssh key. Which is marked in red
15) Then add the copied ssh-key and give it appropriate name to it.
And then click on the green button named add ssh key.
16) Go to your repository and then you’d be able to see this. Then click on ssh which is highlighted.
17) Then copy paste the part which is next to it. With simple command on git bash terminal.
20) Then type this command: to push all the files to your github using git
If you check website you’ll see all your files using git add, git commit command and in the end git push.
AND WE’RE DONE! For more understanding of such concepts you can refer to the YouTube channel:
https://www.youtube.com/c/DecodegetItSimplified
LAB Exercise
Set A:
a) Create a GitHub account.
b) Download and install git on computer or laptop.
c) Create your own repository for each subject.
d) Collaborate Remote Repository with GitHub using GitBash Terminal.
e) Upload html programs on your repository and share the link with your professor to see.
Assignment Evaluation
Eg:
To-do list
Shopping list
3 <ul></ul>
This tag defines unordered
type = disc/square/circle Specifies
<ul>
list of items. Each itemthe
in bullet type. <li>Pune</li>
the list is marked with a <li>Mumbai</li>
bullet. <ul type = "disc"> <li>Nagpur</li>
<ul type = "circle"> </ul>
<ul type = "square">
<ul type="square">
<li>Pune</li>
<li>Mumbai</li>
<li>Nagpur</li>
</ul>
Table:
A table is a two dimensional matrix, consisting of rows and columns. HTML tables are intended for
displaying data in columns on a web page. Tables contains information such as text, images, forms,
hyperlinks etc. Tags used to create table are given in the following table.
Sr. No.
Tag Description Attribute
1 <table> It is used to create border=number
</table> table. Draws an outline around the table rows and cells of width equal to
number. By default table have no borders number =0.
width=number
Defines width of the table.
cellspacing=number
Sets the amount of cell space between table cells. Default value is 2
cellpadding=number
Sets the amount of cell space, in number of pixels between the
cellborder and its contents. Default is 2
bgcolor="#rrggbb"
Sets background color of the table
bordercolor="#rrggbb"
Sets border color of the table
align=left|right|center
Aligns the table. The default alignment is
left.frame=void|above|below|hsides|lhs|rhs|vsides|box|border
Tells the browser where to draw borders around the table
2 <tr> Creates a table row.align=left|right|center
</tr> Aligns the data in cell. The default alignment is left.
3 <th> Creates a table
</th> heading.
4 <td> Data cells are rowspan=number
</td> inserted in a row of
Specifies number of rows a cell should span.
table. colspan=number
Specifies number of columns a cell should span
align=left|right|center
Aligns the data in cell. The default alignment is left.
bgcolor="#rrggbb"
Sets background color of the table.
Sample program for HTML table.
<!DOCTYPE html>
<html>
<body>
SET A
1. Write the HTML code to display the rainbow color names using Ordered List. Modify the code to
display eachcolor name with the same color of rainbow using font tag. Apply page background color as
black.
[Hint: <font size=6 color=red><li>Red</li></font>]
3. Write the HTML code to display list of any three car companies. For each company display list car
models. Display car model as hyperlink. On click of car model it should display an image of that car in
another window. Use ordered or unordered list of your choice.
[Hint: Create separate HTML page for each car model which will display an image.
Use <li><a href="swift.html">Swift</a></li>]
SET B
1. Write the HTML code to display day wise SYBCA time table in tabular format.
2. Write the HTML code which generates the following output. Add more colors in following table.
HTML Colors
SET C
1. Write the HTML code to display names of html text formatting tags and output in tabular format.
Add more html text formatting tags in following table.
b Bold
I Italic
U Underline
2. Write the HTML code to display Product and its subtypes in tabular format. Add more products of
your choice in following table.
Assignment Evaluation
0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]
3: Needs Improvement [ ] 4: Complete [ ] 5: Well done [ ]
<!DOCTYPE html>
<html>
<head>
<title>HTML Target Frames</title>
</head>
<frameset cols = "20%, *">
<frame src = "menu.html" name = "menu_page" />
<frame src = "main.html" name = "main_page" />
</frameset>
</html>
menu.html
<!DOCTYPE html>
<html>
<body>
<a href = "http://www.google.com" target = "main_page">Google</a>
</body>
</html>
main.html
<!DOCTYPE html>
<html>
<body>
<h3>This is main page and content from link will be displayed here.</h3>
</body>
</html>
To see the result open test.html in browser. It will display output as follows.
<!DOCTYPE html>
<html>
<body>
<form action="" method="post">
<h3>Quick Contact</h3>
<h4>Contact us today, and get reply within 24 hours!</h4>
Name : <input type="text"></input><br><br>
Email id : <input type="text"></input><br><br>
Type your message : <textarea></textarea><br><br>
<input type="submit">Submit</input>
</form>
</body>
</html>
LAB Exercise:
SET A
1. Write the HTML code which generates the following output.
2. Write the HTML code to divide the frame into different sections as shown below and add
appropriate html files toeach frame.
3. Write the HTML code to divide page vertically in two sections. On left side display list of any three
car companies. For each company display list car models. Use ordered or unordered list of your choice.
Display car model as hyperlink. On click of car model it should display an image of that car in right
sidewindow.
[Hint: Use target attribute of anchor tag]
SET B
SET C
1. Create the HTML page which gives details of your college, containing College Heading. Add nested
list of courses offered by college for various streams. Add your college photograph and message. Save this
page as“College.html”.
2. Design the HTML form to take the information of a student registering for the course such as name,
address, gender, date of birth, birthplace(to be selected from a list of city/country) ,telephone number,
email ,course (to be selected from a list of courses) etc. One should provide button to submit as well as
Reset the form contents.Save this page as “Register.html” and embed the above page “COLLEGE.HTML”
in this page. (HINT: Use inline frame.)
Assignment Evaluation
0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]
Advantages of CSS:
1. Control layout of many documents from one single style sheet.
2. More precise control of layout.
3. Apply different layout to different media-types (screen, print, etc.).
4. Numerous advanced and sophisticated techniques.
There are three ways one can apply CSS to an HTML document.
Method 1:
In-Line Method – By writing text next to it. (The attribute style).
To apply CSS to HTML is by using the HTML attribute style. Here is the example of applying red
background to HTML page and applying CSS to h1 tag:
Test.html
<html>
<head>
<title>Example</title>
</head>
<body style="background-color: #FF0000;">
<h1 style="color:blue;margin-left:30px;">This is a heading</h1>
<p>This is a red page</p>
</body>
</html>
Method 2:
Internal Method – By specifying tag at the top of the page. (The tag style).
Another way is to include the CSS codes using the HTML tag <style>. For example:
Test.html
<!DOCTYPE html>
<html>
<head>
<style>
body
{
background-color: #FF0000;
}
h1
{
color:blue;
margin-left:30px;
}
</style>
</head>
<body>
<h1>Internal CSS example!</h1>
</body>
</html>
Method 3:
External Method – By writing a separate CSS file. (Link to a style sheet).
Style sheets are separate files full of CSS instructions (with the file extension .css). When any web
pageincludes an external style sheet, its look and feel will be controlled by this CSS file (unless you decide
to overridea style using one of these above two types). This is how you change a whole website at once.
And that's perfect ifyou want to keep up with the latest fashion in web pages without rewriting every page!
In external CSS <link> tag defines therelationshipbetween adocument andan externalresource.
For Example:
Test.html mystyle.css
<!DOCTYPE html> body
<html> {
<head> background-color: #FF0000;
<link rel="stylesheet" type="text/css" }
href="mystyle.css"> h1
</head> {
<body> color: blue;
<h1> margin-left: 30px;
ExternalCSS example! }
</h1>
</body>
</html>
Following table shows the list of properties used in CSS stylesheet:
Sr. No Tag/Property Property with Values
1 Colors and Background 1) color: colorName
2) background-color: colorName
3) background-image: url(path/image)
4) background-repeat: repeat,repeat-x,repeat-y
2 Font 1) font-family: fontName
2) font-style: italic,oblique
3) font-size: pixels/percentage
4) font-weight: bold,bolder,lighter(100-900)
3 Text 1) text-decoration: underline,overline,line-through, blink
2) text-align: left,right,center,justify
3) text-transform: capitalize,uppercase,lowercase
4) text-indent: number
5) vertical-align: sub,super,top,middle,bottom
4 Margin 1) margin-top: 100px
2) margin-bottom: 100px
3) margin-left: 100px
4) margin-right: 100px
5) margin: 100px 40px 10px 70px
5 Border 1) border-style: solid,double,groove,inset,outset,ridge
2) border-color: colorName
3) border-width: number
4) border-top-width: number
5) border-bottom-width: number
6) border-left-width: number
7) border-right-width: number
8) border-top: width style color
9) border-bottom: width style color
10) border-left: width style color
11) border-right: width style color
12) border: width style color
6 List 1) list-style: disc,circle,square,decimal,lower-roman,
upper-roman,lower-alpha, upper-alpha
Applying CSS using id or class
Using id: The id attribute specifies a unique id for an HTML element. The value of the id attribute must be
unique within the HTML document.The id attribute is used to point to a specific style declaration in a style
sheet. To define CSS use # character followed by id name and then write CSS properties in {} curly
braces.
<!DOCTYPE html>
<html>
<head>
<style>
#myHeader
{
background-color: lightblue;
color: black;
padding: 40px;
text-align: center;
}
</style>
</head>
<body>
<h1 id="myHeader">My Header</h1>
</body>
</html>
Using class: A class name can be used by multiple HTML elements, while an id name must only be used
by one HTML element within the page. To define CSS use dot (.) character followed by css class name
and then write CSS properties in {} curly braces. The css class can be used multiple times.
<!DOCTYPE html>
<html>
<head>
<style>
/* Style all elements with the class name "city" */
.city
{
background-color: red;
color: white;
padding: 10px;
}
</style>
</head>
<body>
Here both the first and second nested div element is floating to the left inside their parent element. The text
wraps nicely around the two floating elements.
<!DOCTYPE html>
<html>
<body>
<div id="container" style="width:500px;">
<div id="header" style="background-color:#FFA500;">
<h1 style="margin-bottom:0;">Main Title of Web Page</h1></div>
<div id="menu" style="background-color:#FFD700;height:200px;width:90px;float:left;
border-right: 1px solid black ">
<b>Menu</b><br>
HTML<br>
CSS<br>
JavaScript</div>
<div id="content" style="background-
color:#EEEEEE;height:200px;width:390px;float:left; margin-left:10px">
Content goes here</div>
<div id="footer" style="background-color:#FFA500;clear:both;text-align:center;">
This is footer part </div>
</div>
</body>
</html>
2. Write the HTML code to generate same output as above by using External CSS.
SET B
Assignment Evaluation
0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]
JavaScript is scripting language and not any programming language. Before we deep dive into learning
JavaScript we need to understand why we are learning JavaScript and its role in website making.
JavaScript makes the
Web page response which means if you created a web page and you want your client to fill whatever is in
the web page.
Once the Client is done with filling the form on web page he/she would click on submit button and they
would expect some action occurs and it redirects them to different page or give them a message.
JavaScript is used for making the Web pages interactive with end user, moving images and for validation
purpose as well.
Other Scripting languages can be: VBScript, Python, JavaScript, PHP, Ruby, Lua and many more.
Syntax: -
<html> <html>
<head> <body>
<script language=‖JavaScript‖> OR <script language=‖JavaScript‖>
//JavaScript code //JavaScript code
</script> </script>
</head> </body>
Points to keep in mind:
</html> </html>
1) JavaScript is a Case sensitivelanguage.
2) The JavaScript program code ends withsemicolon.
3) Comments are defined using // or /**/.
Variables: A variable is container which stores the value and can be changed over period of time.
Declaration: var<nameOfTheVariable> = <value>;
Example: varaccountBalance = 1500;
Pro-tip: Give your variable name a meaningful name related to the program. It is good practice.
Identifier:As the name suggest it is used to identify. Identifiers are names like variable names, keywords,
Functions and labels. There are some rules for naming as well like:
First character must be a letter or underscore (_) or a dollar sign ($), which means numbers aren’t allowed
as first character while naming.
Operators:An operator is a symbol that tells to perform a certain mathematical, logical manipulation.
Operators in JavaScript are:
1) Assignment Operators: which are used to assign (=), (+=), (-=), (*=), (/=), (%=).
Eg: var balance = 300; (this shows balance variable is assigned 300 value).
2) Arithmetic Operators: In this you’d see Addition (+), Subtraction (-), Multiplication (*) and many more.
3) Comparison Operators: Used for comparing two values.
4) Logical Operators: Boolean conditions like &&, || and !
5) Conditional/ Ternary Operators: Condition? expression 1 : expression 2
It takes three operands and returns the value of expression1 if the condition is true or else it will return
Value of expression 2.
Control Structures: They are just the loops which we have learned in earlier classes.
Let us see the loops one by one.
1) if … else
2) switch case
3) do while loop
4) while loop
5) for loop
1) If … else
The if statement is the fundamental control statement that allows JavaScript to make decisions and execute
statements conditionally.
Syntax:
if(expression){
Statement(s) to be executed if expression istrue
}
Example:
<scripttype="text/javascript">
<!--
var age =20;
if( age >18)
{
document.write("<b>Qualifies for driving</b>");
}
//-->
</script>
2) Switch case
The basic syntax of the switch statement is to give an expression to evaluate and several different statements to
execute based on the value of the expression. The interpreter checks each case against the value of the expression
until a match is found. If nothing matches, a default condition will be used.
Syntax:
switch(expression){
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}
Example:
<scripttype="text/javascript">
<!--
var grade='A';
document.write("Entering switch block<br/>");
switch(grade){
case'A':document.write("Good job<br/>");
break;
case'B':document.write("Pretty good<br/>");
break;
case'C':document.write("Passed<br/>");
break;
case'D':document.write("Not so good<br/>");
break;
case'F':document.write("Failed<br/>");
break;
default:document.write("Unknown grade<br/>")
}
document.write("Exiting switch block");
//-->
</script>
3) Do while Loop
The do...while loop is similar to the while loop except that the condition check happens at the end of the loop. This
means that the loop will always be executed at least once, even if the condition is false.
Syntax:
do{
Statement(s) to be executed;
}while(expression);
Example:
<scripttype="text/javascript">
<!--
var count =0;
document.write("Starting Loop"+"<br/>");
do{
document.write("Current Count : "+ count +"<br/>");
count++;
}while(count <0)
document.write("Loop stopped!");
//-->
</script>
This will produce following result:
Starting Loop
Current Count: 0
Loop stopped!
4) While Loop
The purpose of a while loop is to execute a statement or code block repeatedly as long as expression is true. Once
expression becomes false, the loop will be exited.
Syntax:
while(expression){
Statement(s) to be executed if expression istrue
}
Example:
<scripttype="text/javascript">
<!--
var count =0;
document.write("Starting Loop"+"<br/>");
while(count <5){
document.write("Current Count : "+ count +"<br/>");
count++;
}
document.write("Loop stopped!");
//-->
</script>
This will produce following result:
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Loop stopped!
5) For Loop
The for loop is the most compact form of looping and includes the following three important parts −
The loop initialization where we initialize our counter to a starting value. The initialization statement is executed
beforethe loop begins.The test statement which will test if the given condition is true or not. If condition is true then
codegiven inside the loop will be executed otherwise loop will come out. The iteration statement where you can
increase or decrease your counter.
Syntax:
for(initialization; test condition; iteration statement){
Statement(s) to be executed if test condition istrue
}
Example:
<scripttype="text/javascript">
<!--
var count;
document.write("Starting Loop"+"<br/>");
for(count =0; count <4; count++){
document.write("Current Count : "+ count );
document.write("<br/>");
}
document.write("Loop stopped!");
//-->
</script>
This will produce following result which is similar to while loop −
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Loop stopped!
Dialog Boxes:-
There are three types of dialog boxes.
3 prompt dialog box The prompt dialog box is used to accept input from the user. It
displays predefined message, a text box with default valueand
Syntax:- OK and Cancelbutton.
prompt(―message‖,
―defaultValue‖);
<html>
<head>
<script>
if(confirm("do u want to continue?"))
document.write("Welcome");
else
document.write("Good bye");
2. Sample Program for Prompt Dialogbox:-
</script>
<html>
</head>
<head>
</html>
<script>
var fn=prompt("Enter your First Name");
var ln=prompt("Enter your Surname");
document.write("My name is" + fn + " "+ ln);
</script>
</head>
</html>
3
0
LAB Exercise
Set A:
1. Write a JavaScript program to print factorial of a givennumber.
2. Write a JavaScript program to check whether given number is perfect ornot.
3. Write a JavaScript program to check whether given number is Armstrong number ornot.
4. WriteaJavaScriptprogramtoacceptanumber from useranddisplaythat
numberinword (e.g.226 Two Two Six)
Set B:
Assignment Evaluation
Structure of Function:
function add(number1, number2){
return number1+number2
}
Small Program:
varaddingTwoNum = add(3,4); // add() invokes the function with arguments
given.
function add(number1, number2){ // here number1 and number2 are 3, 4 which are parameters.
return number1+number2
}
A. Predefined Functions :- JavaScript provides several predefined functionswhich means JavaScript has functions
Made already which you just need to use it. Few functions are listed below:
<html>
<body>
<script>
functionconvertStoI() {
varr = parseInt("1011", 2);
document.write(parseInt("226 Successful"));
}
convertStoI();
</script>
</body>
</html>
2) Sample Program for Math Function:-
<!DOCTYPE html>
<html>
<body>
<script>
document.write("Power="+Math.pow(2,3));
document.write("<br>Round="+Math.round(4.7));
document.write("<br>Round="+Math.round(4.4));
document.write("<br>Root="+Math.sqrt(16));
document.write("<br>Absolute="+Math.abs(-2.7));
document.write("<br>Ceil="+Math.ceil(4.4));
document.write("<br>Ceil="+Math.ceil(4.7));
document.write("<br>Floor="+Math.floor(4.7));
</script>
</body>
</html>
3) Sample Program for String and Date Function:-
<!DOCTYPE html>
<html>
<body>
<head>
<title>Show good morning good night wish as per time Javascript</title>
</head>
<script type="text/javascript">
document.write("<center><font size=+3 style='color: green;'>");
document.write("Good Noon!");
} else if (hr >= 12 && hr <= 17) {
document.write("Good Afternoon!");
} else {
document.write("Good Evening!");
}
document.write("</font></center>");
</script>
</html>
</body>
</html>
B. User defined Functions:-
Functions are declared and created using the function keyword and we can customize it according to our
needs.
A function has,
1. A name for thefunction.
2. A list of parameters / arguments that will be accepting values passed to the function whencalled.
3. A block of JavaScript code that defines what the functiondoes.
Syntax :-
function functionName(parameter1,parameter2,----- )
{
//JavaScript Code
}
Place of Declaration:
Functions can be declared anywhere within an HTML file, but if the function is called before it is
declared and parsed, it will lead to an error condition. Therefore declaring functions within the
<head>---</head> tags of the HTML file, ensures that all functions will be parsed before they are
invoked or called.
Function Call:-To call a function, use function‘s name and its parameters as a statement.
Returningavalue:-User define
functionscanreturnvaluesusingreturnstatement.Thereturnstatementcanbe used to return any valid
expression that evaluates to a singlevalue.
<html>
<body>
<script>
function cubeOfNumber(num)
{
return (num*num*num);
}
var cube=cubeOfNumber(4);
document.write(Cube of a Number=+ cube);
</script>
<body>
</html>
Array:- An array is a collection of similar data type variables.
Declaration Syntax:-
vararrName=new Array(arr_length);
Example:-
varplayerName=new Array();
player_Name[50]=Sachin Tendulkar;
player_Name[100]=Rahul Dravid;
TYPES OF ARRAYS:
Dense Array:-
A dense array is an array that has been created with each of its elements being assigned a specific value.
They are declared and initialized at the same time. Listing the values of the array elements in the array
declaration creates dense arrays.
Syntax :-
vararrName=new Array(val0,val1,val2, ------- ,valn);
Example :-
1. var n=new Array(10,20,30,40,50);
2. vararr=new Array(abc,10,20,pqr);
Since array is a JavaScript object, arrays have several methods associated with them via which the
array and its elements content can be manipulated. These methods are,
<html>
<body>
<script>
vararr=new Array(10,20,30,40);
document.write("Join="+arr.join()+"<br>");
document.write("Join="+arr.join("x")+"<br>");
document.write("Reverse"+arr.reverse()+"<br>")
3
; document.write("Length="+arr.length+"<br>");
5
</script>
</body>
</html>
LAB Exercise
Set A
1. Write a JavaScript code to greet the user according to the currenttiming.
2. Write a JavaScript Program to read a number from user, store its
factors into the array and display that array.
3. Write a menu driven program using JavaScript to perform the following
operations on anarray
a. Display anArray
b. Sort elements of anarray
c. Reverse elements of anarray
d. Search a given element from anarray
Set B
1. WriteamenudrivenprogramusingJavaScripttofindsquare-
root,powerandabsolutevalue ofagiven number.
2. Write a JavaScript code to accept date from the user. If date entered by the user
is
1stJanuary
thenprint―HappyNewYear‖,if25thDecemberthenprint―MerryChristmas,
if14thJanuarythen―happyMakarsankranti,otherwiseprint―HaveaGoodDaymessage
;
3. Write a menu driven program using JavaScript to perform the
followingoperations.
1. Insert an element instack
2. Delete an element fromstack
3. Display the contents ofstack
4. Insert an element inqueue
5. Delete an element fromqueue
6. Display the contents ofqueue
Set C
1. Write a JavaScript program to display a Multiplication table in tabular format
usingfunction.
2. Write a JavaScript code to calculate maximum, minimum, sum and average of
numbers in anarray.
3. Write a JavaScript code to accept birth-date and print the age of auser.
Assignment Evaluation
Verification is the process of checking that the software meets the specification.
It includes checking documents, design, codes and programs.
A website can before getting live it goes under validation stage.
JavaScript provides a way to validate form's data on the client's computer before sending it to
the web server. Form validation generally performs two functions.
Basic Validation − First of all, the form must be checked to make sure all the mandatory fields
are filled in. It would require just a loop through each field in the form and check for data.
Data Format Validation − Secondly, the data that is entered must be checked for correct form
and value. Your code must include appropriate logic to test correctness of data.
For example: If a form field (firstName) is empty, this function alerts a message, and returns
false, to prevent the form from being submitted.
Sample example:
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["firstName"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
</script>
</head>
<body>
</body>
</html>
For example this will be your registration form:
You have to make sure the textbox is not empty as well as you have to make user input correct
values in the textbox’s. Drop down must be selected same goes with radio button. The
checkbox must be checked otherwise it would accept Register Now button getting clicked. If
everything is filled perfectly only then it should go on to next page.
<!DOCTYPE html>
<html lang="en"><head>
<meta charset="utf-8">
<title>JavaScript Form Validation using a sample registration form</title>
<meta name="keywords" content="example, JavaScript Form Validation, Sample registration
form" />
<meta name="description" content="This document is an example of JavaScript Form
Validation using a sample registration form. " />
<link rel='stylesheet' href='js-form-validation.css' type='text/css' />
<script src="sample-registration-form-validation.js"></script>
</head>
<body onload="document.registration.userid.focus();">
<h1>Registration Form</h1>
Use tab keys to move from one input field to the next.
<li><label for="country">Country:</label></li>
<li><select name="country">
<option selected="" value="Default">(Please select a country)</option>
<option value="AF">Australia</option>
<option value="AL">Canada</option>
<option value="DZ">India</option>
<option value="AS">Russia</option>
<option value="AD">USA</option>
</select></li>
</form>
</body>
</html>
Now let’s see the Cascading Style Sheet, make sure you save it as .css file or you can
embed it as well in html but it is mostly advised to keep css apart from html code.
h1 {
margin-left: 70px;
}
form li {
list-style: none;
margin-bottom: 5px;
}
form ul li label{
float: left;
clear: left;
width: 100px;
text-align: right;
margin-right: 10px;
font-family:Verdana, Arial, Helvetica, sans-serif;
font-size:14px;
}
form textarea {
float: left;
width: 350px;
height: 150px;
}
[type="submit"] {
clear: left;
margin: 20px 0 0 230px;
font-size:18px
}
p{
margin-left: 70px;
font-weight: bold;
}
Now it is time to see JavaScript validation: using the function formValidation.
function formValidation()
{
var uid = document.registration.userid;
var passid = document.registration.passid;
var uname = document.registration.username;
var uadd = document.registration.address;
var ucountry = document.registration.country;
var uzip = document.registration.zip;
var uemail = document.registration.email;
var umsex = document.registration.msex;
var ufsex = document.registration.fsex; if(userid_validation(uid,5,12))
{
if(passid_validation(passid,7,12))
{
if(allLetter(uname))
{
if(alphanumeric(uadd))
{
if(countryselect(ucountry))
{
if(allnumeric(uzip))
{
if(ValidateEmail(uemail))
{
if(validsex(umsex,ufsex))
{
}
}
}
}
}
}
}
}
return false;
}
LAB Exercise
Set A
1. Write a JavaScript code to design registration form.
2. Draw a flowchart for one entire module and show its working.
3. Write JavaScript code for formValidation.
Set B
1. Write a menu driven program using JavaScript to find square root, power and absolute value of
a given number and validate them.
2. Write a JavaScript code using Bootstrap for sign-up form.
3. Write a JavaScript function for Calculator and verify them.
Assignment Evaluation
} function userid_validation(uid,mx,my)
{
var uid_len = uid.value.length;
if (uid_len == 0 || uid_len >= my || uid_len < mx)
{
alert("User Id should not be empty / length be between "+mx+" to "+my);
uid.focus();
eturn false;
}
return true;
}
function passid_validation(passid,mx,my)
{
var passid_len = passid.value.length;
if (passid_len == 0 ||passid_len >= my || passid_len < mx)
{
alert("Password should not be empty / length be between "+mx+" to "+my);
passid.focus();
return false;
}
return true;
}
function allLetter(uname)
{
var letters = /^[A-Za-z]+$/;
if(uname.value.match(letters))
{
return true;
}
else
{
alert('Username must have alphabet characters only');
uname.focus();
return false;
}
}
function alphanumeric(uadd)
{
var letters = /^[0-9a-zA-Z]+$/;
if(uadd.value.match(letters))
{
return true;
}
else
{
alert('User address must have alphanumeric characters only');
uadd.focus();
return false;
}
}
function countryselect(ucountry)
{
if(ucountry.value == "Default")
{
alert('Select your country from the list');
ucountry.focus();
return false;
}
else
{
return true;
}
}
function allnumeric(uzip)
{
var numbers = /^[0-9]+$/;
if(uzip.value.match(numbers))
{
return true;
}
else
{
alert('ZIP code must have numeric characters only');
uzip.focus();
return false;
}
}
function ValidateEmail(uemail)
{
var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(uemail.value.match(mailformat))
{
return true;
}
else
{
alert("You have entered an invalid email address!");
uemail.focus();
return false;
}
} function validsex(umsex,ufsex)
{
x=0;
if(umsex.checked)
{
x++;
} if(ufsex.checked)
{x++;
}
if(x==0)
{
alert('Select Male/Female');
umsex.focus();
return false;
}
else
{
alert('Form Succesfully Submitted');
window.location.reload()
return true;
}
}
A. EventHandling
An event occurs when something happens in a browser window.
When a function is assigned to an event handler, that function will run when that event occurs.
Syntax:-
eventHandler="clickHandler()"
This handler will cause the function clickHandler() to be executed whenever the event is
triggered.
EventHandler Description
onabort Occurs when loading of image was interrupted
onblur Occurs when element loses focus
onchange Occurs when element gets modified
onclick Occurs when element gets clicked
ondblclick Occurs when element gets double clicked
onfocus Occurs when an element received focus
onkeydown Occurs when a key was pressed when an element has focus
Occurs when a keystroke was received by the element
onkeypress
onkeyup Occurs when a key was released when the element has focus
onload Occurs when an element was loaded
onmousedown Occurs when the mouse button was pressed on the element
onmousemove Occurs when the mouse pointer moves while inside the element
onmouseout Occurs when the mouse pointer was moved outside the element
onmouseover Occurs when the mouse pointer was moved onto the element
onmouseup Occurs when the mouse button was released on the element.
onreset Occurs when the form's reset button was clicked
Onresize Occurs when the containing window or frame was resized
Onselect Occurs when text within the element was selected
Onsubmit Occurs when a form is being submitted
Onunload Occurs when the content is being unloaded (e.g. window being closed)
Onscroll Occurs when the user scrolls (in any direction and with any means).
<script language=JavaScript>function
printMsg()
{
alert(Hello world!);
}
</script>
</head>
<body ondblclick="printMsg()">
</body>
</html>
LAB Exercise
Set A
a. Write a JavaScript function to validate email-id using regular expression.
b. Write a JavaScript program for accepting name and mobile number from
user and perform following validation:
i. Check all fields should not contain a nullvalue
ii. Check name field contains onlyalphabets
iii. Mobile No. field should be of 10 digitslong.
c. WriteaJavaScriptprogramtocomparethevaluesofpasswordandconfirmedp
asswordfieldanddisplay message accordingly. Also perform the
validation to check any of the field should not beempty.
Set B
1. WriteaJavaScriptprogramtoreademployeedetailsandgeneratepay-
slipwhichwillcalculatenetsalary of an employee.
2. Write a Java Script program to design Customer Account Details Form and
perform validation on pan number field. (pan number is of only 10 characters
long, out of which first 5 characters are alphabets, next 4 characters are digits
and last character is alphabet)
3. Design a form to accept product name, quantity, rate and discount for the
product purchased by the user. Write a JavaScript code to calculate total bill. If
quantity is less than 5 then there is any discount, Ifquantity is greater than 5 and
less than 25 then discount is 5%, If quantity is greater than 25 and less than 50
then discount is 15%, If quantity is greater than 50 discount is20%.
Set C
1. Write a JavaScript code to change the background color of the webpage.
2. Write a menu driven program using JavaScript code to perform followingoperations,
a. Jump to the previous webpage
b. Jump to the next webpage
c. Jump to the two page before from currentpage
d. Jump to the two page after from current page.
Assignment Evaluation
2.
3. Write the HTML code to display Top 5 resorts in Goa. Make use of HTML tags and CSS that you have
studied till now.
SET B:
1. Write the appropriate code to display the output below :
2.
SET C:
2.
Assignment Evaluation
0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]
In your "php.ini" file, search for the file_uploads directive, and set it to On:
file_uploads = On
There is one global PHP variable called $_FILES. This variable is an associate double dimension
array and keeps all the information related to uploaded file.
name
The name of the file, as supplied by the browser. It's difficult to make meaningful use of this,
as the client machine may have different filename conventions than the web server (e.g., if the
client is a Windows machine that tells you the file isD:\PHOTOS\ME.JPG, while the web
server runs Unix, to which that path is meaningless).
type
size
The size of the uploaded file (in bytes). If the user attempted to upload a file that was too large,
the size is reported as 0.
tmp_name
The name of the temporary file on the server that holds the uploaded file. If the user attempted
to
upload a file that was too large, the name is reported as "none".
For example :
• $_FILES['filename']['tmp_name'] − the uploaded file in the temporary directory on the
webserver.
The correct way to test whether a file was successfully uploaded is to use the function
is_uploaded_file(), as follows:
if (is_uploaded_file($_FILES['toProcess']['tmp_name'])
// successfully uploaded
The call to move_uploaded_file() automatically checks whether it was an uploaded file. When a script
finishes, any files uploaded to that script are deleted from the temporary directory.
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select File to upload:
</form>
</body>
</html>
<?php
$target_path = "D:/uploads/";
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
}
else{
echo "There was an error uploading the file, please try again!";
}
?>
Form Validation:
When you allow users to input data, you typically need to validate that data before using it or
storing it for later use. There are several strategies available for validating data like Form
Fields should not be empty. Check type of data entered by user or length of data entered by
user. (e.g check age of person is integer or cannot be negative etc.) Check specific conditions
for form fields(e.g. email validation).
PHP provides empty() function to check a variable is empty. We can use this function to
check if all the text fields are empty or not. isset() function can be used to check the gender
radio button is checked or not. We can validate email format by using PHP filter_var()
function.
empty(var_name) : The empty() function is used to check whether a variable is empty or not.
isset(var_name) : this function determines if a variable is set and is not NULL
filter_var(var, filtername, options) : The filter_var() function filters a variable with
thespecified filter.
Consider the following script to validate email.
<?php
$email = "[email protected]";
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
echo("$email is a valid email address");
} else {
echo("$email is not a valid email address");
}
?>
Example : Design form which accepts name and gender . If fields are blank display error message
“All fields are required” otherwise display information
<html>
<head>
<style>
</style>
</head>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["name"]))
else
$name = $_POST["name"];
if (!isset($_POST["gender"]))
$genderErr = "Gender is required";
else
$gender =$_POST["gender"];
?>
<?php
{
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $gender;
}
?>
</body>
</html>
Lab Assignments:
SET A:
1. Write a PHP Program to Upload the file and display its information like name, size, type , etc.
2. Write a PHP program to accept student information like name, address, class and Upload
student photo and display same on form.
SET B:
1. Write a PHP program to accept Name , address , Pincode ,Gender information. If any field
isblank , it display error message “all fields are required” . If pincode is more than 6 digits , it
should give error.
2. Write a PHP program to accept empno, name, pan card information, email . If any field is
blank , form should display error message “all fields are required”. Pan card number should be
10 digits and First 5 characters should be letter , next 4 characters should be digit and last
character should be letter.
3. Write a PHP script to create a form that accept theusers full name and their email addresses.
Use case conversion function to capitalize the first letter of each name, user submits and print
result back to browser. Check that the user’s email address contains the @ symbol.
SET C:
1) Write a PHP script for creating a self-processing page for a form. The form should allow the
user to enter the following attributes: Username, user city
preference(pune/Mumbai/Chennai/kolkata),user birth date, occupation, sex. If any of the
values is not entered by the user, the page is presented again with a message specifying the
attributes that are empty. Any form attributes that the user already entered, are set to the values
the user entered. The text of submit button changes from “create” to “continue”, when the user
is correcting the form. Display the details entered by the user on the next form
Assignment Evaluation
0: Not Done [ ] 1: Incomplete [ ]
2: Late Complete [ ]
Cookies :
• A cookie is basically a string that contains several fields. A server can send one or more
cookies to a browser in the headers of a response. Some of the cookie’s fields indicate the
pages for which the browser should send the cookie as part of the request.
• name : A unique name for a particular cookie. You can have multiple cookies with differentnames and
attributes. The name must not contain whitespace or semicolons.
• value : The arbitrary string value attached to this cookie. The original Netscape specificationlimited the
total size of a cookie (including name, expiration date, and other information) to 4
KB, so while there’s no specific limit on the size of a cookie value, it probably can’t be much larger than
3.5 KB.
• expire : The expiration date for this cookie. If no expiration date is specified, the browsersaves the
cookie in memory and not on disk. When the browser exits, the cookie disappears. The expiration date is
specified as the number of seconds.
• path : The browser will return the cookie only for URLs below this path. The default is thedirectory in
which the current page resides.
• domain : The browser will return the cookie only for URLs within this domain. The default isthe server
hostname.
• secure :The browser will transmit the cookie only over https connections. The default is false,meaning that
it’s okay to send the cookie over insecure connections
This function creates the cookie string from the given arguments and creates a Cookie header with that
string as its value. Because cookies are sent as headers in the response, setcookie() must be called before
any of the body of the document is sent.
When a browser sends a cookie back to the server, you can access that cookie through the $_COOKIE
array. The key is the cookie name, and the value is the cookie’s value field.
Consider a sample program to keep track of number of times the web page has been accessed
<?php
if(isset($_COOKIE['accesses']))
$cnt = $_COOKIE['accesses'];
else
$cnt = 0 ;
setcookie('accesses', ++$cnt);
Deleting Cookies
You can delete a cookie by calling the same setcookie() function with the cookie name and
any value (such as an empty string) however this time you need the set the expiration date
in the past.
<?php
// Deleting a cookie
setcookie("username", "", time()-3600);
?>
Sessions :
Session allow us to easily create multi page forms, save user authentication information from page topage,
and store persistent user preferences on a site. A session can be defined as a series pf related interactions
between a single client and the Web server. The session may consist of multiple requests to the same script or
a variety of different resources on the same web site.
To enable sessions for a page, call session_start()before any of the document has been generated:
<html>
...
</html>
This assigns a new session ID if it has to, possibly creating a cookie to be sent to the browser, and loads any
persistent variables from the store. into the associative array $HTTP_SESSION_VARS. The keys are the
variables’ names (e.g., $HTTP_SESSION_VARS['hits'])
Functions :
bool session_start ([ array $options = [] ] ) :to enable session for a page. This function assigns a
new session ID to the new session.
bool session_register ( mixed $name [, mixed $... ] ) : to register a variable with the session by passing
the name of the variable. When a session is started, you can store any number of variables in the
$_SESSION superglobal array and then access them on any session enabled page.
string session_id ([ string $id ]) : session_id() is used to get or set the session id for the current session.
bool session_destroy ( void ) : session_destroy() destroys all of the data associated with the current
session. It does not unset any of the global variables associated with the session, or unset the session
cookie. To use the session variables again, session_start() has to be called.
bool session_unregister( string $name ) : session_unregister() unregisters the global variablenamed
name from the current session.
$_SESSION['page_count'] += 1;
else
$_SESSION['page_count'] = 1;
Lab Exercise
SET A
1. A web application that lists all cookies stored in the browser on clicking “list cookies” button, add
cookies if necessary.
2. 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.
3. Write a script to keep track of number of times the web page has been accessed using session.
4. Create a login form with a username and password. Once the user logs in, the second form should be
displayed to accept user details (name, city, phoneno). If the user doesn’t enter information within a
specified time limit, expire his session and give a warning otherwise Display Details using sessions.
5. Write PHP program to store Customer information like customer no, name, address, mobile no. On
second page, accept product code, product name, Qty, Rate. Display Bill on third page including
customer and product details.
SET B
1. Write a PHP script to accept username and password. If in the first three chances, username and password
entered is correct, then display second form, otherwise display error message.
2. Create a form to accept student information (name, class, address). Once the student information is
accepted, accept marks in next form (Java, PHP, SE, OS, Pract1, and Pract2). Display the mark sheet for
the student in the next form containing name, class, marks of the subject, total and percentage using
cookies.
3. Change the preferences of your web page like font style, font size, font color, background color using
cookie. Display selected settings on next web page and actual implementation (with new settings) on third
web page.
4. Create a form to accept employee details like name, address and mobile number. Once the employee
information is accepted, then accept LIC information like policy_no, name, premium. Display
employee details and LIC details on next form.
5. Write a PHP script to accept Employee details (Eno, Ename, Add.) on first page. On second page accept
earning (Basic, DA, HRA). On third page Print Employee Information (Eno, Ename, Add, Basic, DA,
HRA, Gross)
SET C
1. Write a program to create a shopping mall. User must be allowed to do purchase from three pages.
Each page should have a page total. The fourth page should display a bill, which consists of a page
total of whatever the purchase has been done and print the total. (Use $_SESSION).
Assignment Evaluation
0: Not Done[] 1: Incomplete[] 2: Late Complete [ ]
Introduction to XML :
XML stands for EXtensible Markup Language. It is a text-based markup language derived from
Standard Generalized Markup Language (SGML). XML was designed to store and transport data.
XML was designed to be both human- and machine-readable. XML is a markup language much
like HTML. XML was designed to describe data. XML tags are not predefined . You must define
your own tags.XML is self describing.
XML document are well – formed and valid. A well - formed XML document follows the basic
XML syntax rules.A valid document also follows the rules imposed by a DTD or an XSD.
1. XMLdeclaration
2. Document typedeclaration
Document Elements Section:
Document Elements are the building blocks of XML. These divide the document into a
hierarchy of sections, each serving a specific purpose.
XML declaration :
It contains details that prepare an XML processor to parse the XML document. It is optional, but
when used, it must appear in the first line of the XMLdocument.
<?xml version="version_number" encoding="encoding_declaration" standalone="standalone_status" ?>
XML Tags :
XML tags are case sensitive. The tag <Letter> is different from the tag <letter>. Opening and
closing tags must be written with the same case.
For example,
<Message>This is incorrect</message>
<message>This is correct</message>
XML Elements :
An XML file is structured by several XML-elements, also called XML-nodes or XML-tags.
XML-elements' names are enclosed by triangular brackets <>.
EachXML-elementneedstobeclosedeitherwithstartorwithendelementsasshownbelow:
<element> .......... </element>.
An XML document can have only one rootelement
An XML-element can contain multiple XML-elements as its children, but the children
elements must notoverlap.
In XML, all elements must be properly nested within eachother.
XML attributes:
An XML-element can have one or moreattributes.
Attribute names in XML (unlike HTML) are case sensitive. That is, HREF andhrefare
considered two different XMLattributes.
Same attribute cannot have two values in asyntax
So XML follows tree structure
<root>
<child>
<subchild> ............................... </subchild>
</child>
</root>
<?xml version = “1.0” ?>
<BookStore>
<Books>
<PHP>
</PHP>
<PHP>
</PHP>
</Books>
</BookStore>
<title>Programming PHP</title>
<publication>O’RELLY</publication>
<title>Beginners PHP</title>
<publication>WROX</publication>
SimpleXML :
SimpleXMLis an extension that allows us to easily manipulate and get XMLdata.
The SimpleXML extension is the tool of choice for parsing an XMLdocument.
SimpleXML turns an XML document into a data structure you can iterate through like a
collection of arrays andobjects.
The SimpleXML extension includes interoperability with the DOM for writing XML
filesand built-in XPathsupport.
SimpleXMLis easier to code than the DOM, as its nameimplies.
addAttribute() $book->addAttribute(“Category” ,
adds an attribute to theaddAttribute(name, value);
SimpleXML element. “Technical”);
• With SimpleXML, all the elements in XML document are represented as tree of SimpleXMLElement
objects. Any given element’s children are available as propertiesof elements SimpleXMLElementobject.
• For example ,We can access element name as properties $book->title , $book->publisheretc.
Consider an application that reads “Book.xml” file into simple XML object. Display attributes and
elements.
//book .xml
<?xml version='1.0' encoding='UTF-8'?>
<bookstore>
<book category="Technical">
<title> LET US C </title>
<author> YASHWANT KANETKAR </author>
<year> 1980 </year>
</book>
<book category="Cooking">
<title> COOKING EVERYDAY </title>
<author> TARALA DALAL</author>
<year> 2000 </year>
</book>
<book category="YOGA">
<title> LIGHT ON YOGA </title>
<author> B.K.IYENGAR </author>
<year> 1990 </year>
</book>
</bookstore>
// book.php
<?php
$xml = simplexml_load_file("book.xml");
}
}
}
?>
XSLT Introduction
This tutorial will teach you how to use XSLT to transform XML documents into other formats (like
transforming XML into HTML).
XSLT is used to transform an XML document into another XML document, or another type of document
that is recognized by a browser, like HTML and XHTML. Normally XSLT does this by transforming each
XML element into an (X)HTML element.
With XSLT you can add/remove elements and attributes to or from the output file. You can also rearrange
and sort elements, perform tests and make decisions about which elements to hide and display, and a lot
more.
A common way to describe the transformation process is to say that XSLT transforms an XML source-
tree into an XML result-tree.
?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<trbgcolor="#9acd32">
<th>Title</th>
<th>Artist</th>
</tr>
<xsl:for-each select="catalog/cd">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
LAB Exercise:
SETA:
1) Create a XML file which gives details of movies available in “Mayanagari CD Store” from
following categories a) Classical b) Action c) Horror
Elements in each category are in the following
format <Category>
</Category>
Save the file with name “movies.xml”.
2) Create a XML file which gives details of books available in “ABC Bookstore” from following
categories.
1) Technical
2) Cooking
3) Yoga
and elements in each category are in the following format
<Book>
<Book_PubYear> --------------</Book_PubYear>
<Book_Title> --------------</Book_Title>
<Book_Author>---------------</Book_Author>
</Book>
Save the file as “Book.xml”
3) Write a PHP script to create XML file named “Course.xml”
<Course><Computer
Science>
<Student name>.......</Student
name><Class name>......</Class
name><percentage>.....</percentage></
Computer Science>
</Course>
<Movie>
<Title>Holiday</Title>
<Movie>
<Title>LOC</Title>
</CD Store>
2) Write a script to create “cricket.xml” file with multiple elements as shown below:
<CricketTeam>
<Team country=”India”>
<player>____</player>
<runs>______</runs>
<wicket>____</wicket>
</Team>
</CricketTeam>
Write a script to add multiple elements in “cricket.xml” file of category, country=”Australia”.
3) Write a PHP script to accept an XML file which should comprise the following:
<cricket>
<player>abc</player>
<runs>1000</runs>
<wickets>50</wickets>
<noofnotout>10</noofnotout>
</cricket>
For at least 5 players. Display the details of players who have scored more than 1000 runs and at least
50 wickets.
SET C:
1) Write a PHP script to accept an XML file which should comprise the following :
<languages><lang
name="C"><appeared>1972</appeared
><creator>Dennis
Ritchie</creator></lang>
</languages>
For at least 5 records. Display the details of C language.
Assignment Evaluation
0: Not Done[] 1: Incomplete[] 2: Late Complete [ ]