R-16 IV/I Unit-I: HTML, Css UNIT-II: Java Script Unit-Iii: XML, Ajax Unit-Iv: PHP Unit-V: Perl Unit-Vi: Ruby
R-16 IV/I Unit-I: HTML, Css UNIT-II: Java Script Unit-Iii: XML, Ajax Unit-Iv: PHP Unit-V: Perl Unit-Vi: Ruby
UNIT-IV: PHP
UNIT-V: PERL
UNIT-VI: RUBY 1
Hyper Text Markup Language
2
The Internet is the global system of interconnected computer networks that
uses the Internet protocol suite (TCP/IP) to communicate between networks
and devices. ...
W W W – World Wide Web. It is the collections of Networks that make up
the internet
URL – Uniform Resource Locator. The internet uses url to identify
resources available on the internet
protocol://domainname:port/websitename/webpagename
http://10.1.1.30:80/ecap/default.aspx
HTTP – Hyper Text Transfer Protocol .The communications protocol used to
connect to Web servers on the Internet or on a local network (intranet).
Its primary function is to establish a connection with the server and send
HTML pages back to the user's browser.
It allows your web browser (i.e. Google Chrome, Mozilla Firefox, Apple
Safari or Internet Explorer) to communicate with the server where any given
website is hosted.
UNIT-1 HTML 3
UNIT-1 HTML 4
Web Application
A web application (or web app) is an application software that runs on
a web server, unlike computer-based software programs that are stored locally on
the Operating System (OS) of the device. Web applications are accessed by the
user through a web browser with an active internet connection.
Common web applications include email, online retail sales, online auctions,
wikis, instant messaging services and more.
Web Server
A web server is a computer that runs websites. It's a computer program that
distributes web pages as they are requisitioned. The basic objective of the web
server is to store, process and deliver web pages to the users. This
intercommunication is done using Hypertext Transfer Protocol (HTTP).
UNIT-1 HTML 6
HTML
Hyper Text Markup Language – The Language of Web Pages on the
World Wide Web.
HTML is a text formatting language.
HTML is a presentation language.
It is a collection of tags and elements.
Element
HTML element is the collection of start tag, its attributes, an end tag and everything in
between.
<body bgcolor=‘red’>Hello</body>
Tag
HTML tag (either opening or closing) is used to mark the start or end of an element
<body>,</body>
Attribute
An attribute is a keyword that is used in opening tag to give more information to the Web
Browser
<hr color=‘green’></hr>
<hr> - is a tag
color – attribute
green - value
UNIT-1 HTML 7
Block-level Elements
A block-level element always starts on a new line and takes up the full width
available (stretches out to the left and right as far as it can).
Here are the some block-level elements in HTML:
<p>,<div>,<form>,<table>,<ol>,<ul>,<h1>--<h6>,<hr>
Inline Elements
An inline element does not start on a new line and it only takes up as much width as
necessary.
<b>,<I,<br>,<img>,<span>,<input>
UNIT-1 HTML 8
Basic Structure of HTML document
<HTML>
<HEAD>
<TITLE>My Profile Page</TITLE>
</HEAD>
<BODY>
This is what is displayed.
</BODY>
</HTML>
◦ The file extension can be .html or .htm
◦ Comments <!-- code -->
UNIT-1 HTML 9
The Body Element
The BODY element of a web page is an
important element in regards to the page’s
appearance.
Attributes:
bgcolor
background
text
link
<body bgcolor=‘green’ text=‘white’>
<body background=‘bg1.gif’>
UNIT-1 HTML 10
Headings, <H1> </H6>
<HTML>
<HEAD>
<TITLE> Example Page</TITLE>
</HEAD>
<BODY> Heading 1
<H1> Heading 1 </H1>
<H2> Heading 2 </H2> Heading 2
<H3> Heading 3 </H3> Heading 3
<H4> Heading 4 </H4> Heading 4
<H5> Heading 5 </H5>
Heading 5
<H6> Heading 6 </H6>
Heading 6
</BODY>
</HTML>
UNIT-1 HTML 11
Break <BR>
Line breaks allow you to decide where the text will break on a line or continue to the end
of the window.
A <BR> is an empty Element, meaning that it may contain attributes but it does not
contain content.
The <BR> element does not have a closing tag.
Hello World<br>
<br>Hello World
Horizontal Rule <HR>
The <HR> element causes the browser to display a horizontal line (rule) in your
document.
<HR> does not use a closing tag, </HR>.
attribute : color,align,size,width
<hr color=‘red’ width=’50%’ align=‘center’ size=‘2’>
Paragraph <p></p>
A paragraph always starts on a new line, and browsers automatically add some white space (a
margin) before and after a paragraph.
attribute : align
values : left, right, center
<p align=‘right’>Hello World</p>
UNIT-1 HTML 12
<B> Bold </B>
UNIT-1 HTML 13
List Elements
unordered list — used to group a set of related items in no particular order
ordered list — used to group a set of related items in a specific order
description list — used to display name/value pairs such as terms and
definitions
LI : to provide items in the List.
<UL> - UNORDERED LIST
attribute : type
values : circle, square, disk(default)
<ul type=‘square’>
<li>C</li>
</ul>
<OL> - ORDERED LIST
attribute : type
values : 1,a,A,i,I,
<ol type=‘A’>
<li>C</li>
</ol>
<DL> - DESCRIPTION LIST
<dt> - Defines a term in a description list
<dd> - Describes the term in a description list
UNIT-1 HTML 14
<IMG>
attributes
SRC :This value will be a URL (location of the image)
Alternate Text (ALT): This is a text field that describes an image or acts as a label.
It is displayed when they position the cursor over a graphic image.
Alignment (ALIGN): This allows you to align the image on your page.
Width (WIDTH): is the width of the image in pixels.
Height (HEIGHT): is the height of the image in pixels.
Border (BORDER): is for a border around the image, specified in pixels.
HSPACE: is for Horizontal Space on both sides of the image specified in pixels. A
setting of 5 will put 5 pixels of invisible space on both sides of the image.
VSPACE: is for Vertical Space on top and bottom of the image specified in pixels. A
setting of 5 will put 5 pixels of invisible space above and bellow the image.
<img src=‘logo.gif’ alt=‘Logo’ width=‘200’ height=‘200’ border=‘2’></img>
UNIT-1 HTML 15
<a> - anchor
HTML anchor tag defines a hyperlink that links one
page to another page. It can create hyperlink to other
web page as well as files, location, or any URL.
attributes
href : Specifies the URL of the page the link goes to
target : Specifies where to open the linked document
<a href=‘Two.html’>Two</a>
UNIT-1 HTML 16
Tables
The <TABLE></TABLE> element has four sub-elements:
1. Table Row<TR></TR>.Table Header <TH></TH>.
2. Table Data <TD></TD>.Caption <CAPTION></CAPTION>.
<table> attributes
BGColor: Some browsers support background colors in a table.
Width: you can specify the table width as an absolute number of
pixels or a percentage of the document width. You can set the width
for the table cells as well.
Border: You can choose a numerical value for the border width,
which specifies the border in pixels.
CellSpacing: Cell Spacing represents the space between cells and is
specified in pixels.
CellPadding: Cell Padding is the space between the cell border and
the cell contents and is specified in pixels.
Align: tables can have left, right, or center alignment.
Background: Background Image.
UNIT-1 HTML 17
<td> and <th> attributes
Colspan: Specifies how many cell columns of the table this cell
should span.
Rowspan: Specifies how many cell rows of the table this cell
should span.
Align: cell data can have left, right, or center alignment.
Valign: cell data can have top, middle, or bottom alignment.
Width: you can specify the width as an absolute number of pixels
or a percentage of the document width.
Height: You can specify the height as an absolute number of pixels
or a percentage of the document height.
UNIT-1 HTML 18
Basic Table Code
UNIT-1 HTML 19
<FONT>
The font tag is used to change the color, size, and type of a text.
attributes:
Size : to adjust the size of the text ( 1 to 7)
Face/Type : to set the type of the font
Color : to set the text color
UNIT-1 HTML 20
Frames
A framed page is actually made up of multiple HTML
pages. There is one HTML document that describes how
to break up the single browser window into multiple
windowpanes. Each windowpane is filled with an
HTML document.
Main.html
Top.html
L
e
f
t
Right.html
.
h
t
m
l
UNIT-1 HTML 21
The <FRAMESET> describes the amount of screen real estate given to each windowpane by
dividing the screen into ROWS or COLS.
The <FRAMESET> will then contain <FRAME> elements, one per division of the browser
window.
<frameset> attributes
◦ rows
◦ cols
◦ bordercolor
◦ frameborder : yes or no
<frame> attributes
◦ name
◦ src
◦ scrolling : yes or no
◦ noresize
◦ marginwidth
◦ marginheight
UNIT-1 HTML 22
Main.html
Top.html
<html>
<body bgcolor=‘green’>
<font color=‘white’><h1>USHA RAMA COLLEGE OF
ENGINEERING</h1></font>
</body>
</html>
UNIT-1 HTML 23
left.html
<html>
<body bgcolor=‘pink’>
<a href=‘aboutus.html’ target=‘right’>About Us<a><br>
<a href=‘departments.html’ target=‘right’>Departments<a><br>
<a href=‘facilities.html’ target=‘right’>Facilities<a><br>
<a href=‘contact.html’ target=‘right’>Contact Us<a><br>
</body>
</html>
right.html
<html>
<body bgcolor=‘yellow’ text=‘red’>
<h5>
Usha Rama College of Engineering and Technology, established by Usha Rama
Educational Academy, with the aim of inculcating quality education to students and
produce young technocrats having good knowledge. The college is approved by
AICTE and affiliated to JNTU-Kakinada. It is sponsored by Chicago based Multi
Million Dollar Advansoft group.
</h5>
</body>
</html>
UNIT-1 HTML 24
Summary of Tags
<head>
<title>
<body>
<h1>---</h6>
<p>
<br>
<hr>
<img>
<a>
Lists : <ul>,<ol>,<dl>
Table : <table>,<caption>,<tr>,<th>,<td>
<font> , <marquee>
Frames : <frameset>, <frame>
<b>,<i>,<u>,<em>
<center>,<sub>,<sup>
<big>,<small>
<strong>,<strike>
UNIT-1 HTML 25
Forms
Forms add the ability to web pages to not only provide the person
viewing the document with dynamic information but also to
obtain information from the person viewing it, and process the
information.
Objectives:
Upon completing this section, you should be able to
1. Create a FORM.
2. Add elements to a FORM.
3. Define CGI (Common Gateway Interface).
4. Describe the purpose of a CGI Application.
5. Specify an action for the FORM.
Forms work in all browsers.
Forms are Platform Independent.
UNIT-1 HTML 26
Forms
To insert a form we use the <FORM></FORM> tags. The rest of
the form elements must be inserted in between the form tags.
<HTML> <HEAD>
<TITLE> Sample Form</TITLE>
</HEAD>
<BODY BGCOLOR=“FFFFFF”>
<FORM ACTION = http://www.xnu.com/formtest.asp>
<P> First Name: <INPUT TYPE=“TEXT” NAME=“fname”
MAXLENGTH=“50”> </P>
<P> <INPUT TYPE=“SUBMIT” NAME=“fsubmit1” VALUE=“Send
Info”> </P>
</FORM>
</BODY> </HTML>
UNIT-1 HTML 27
<FORM> element attributes
ACTION: is the URL of the CGI (Common Gateway
Interface) program that is going to accept the data from
the form, process it, and send a response back to the
browser.
UNIT-1 HTML 28
Form Controls
◦ Text Box
◦ Password Field
◦ Text Area
◦ Check Box
◦ Radio Button
◦ Hidden Control
◦ File Upload
◦ Choice Control
◦ Push Button
◦ Submit Button
◦ Reset Button
UNIT-1 HTML 29
Text Box
This is a single-line editable control
<input type=‘text’>
<input type=‘text’ size=’20’>
<input type=‘text’ size=’20’ value=‘URCE’>
<input type=‘text’ size=’20’ value=‘URCE’ readonly>
<input type=‘text’ maxlength=‘20’>
Password Field
It contains only “*” .
<input type=‘password’ size=‘20’ value=‘URCE’ readonly>
Text Area
It can be used to enter multiple lines and multiple characters . It is created with
<textarea>.
<textarea rows=‘10’ cols=‘20’></textarea>
<textarea rows=‘10’ cols=‘20’>Welcome</textarea>
UNIT-1 HTML 30
Check Box
This is Known as on or off control and displays small box with in tickmark in
it.It does not provide tickmark by default. It is unchecked.
<input type=‘checkbox’>I Agree
<input type=‘checkbox’ checked>I Agree
Radio Button
Displayed usually as a circle. When selected displays a dot in the middle.
<input type=‘radio’ name=‘gender’>Male
<input type=‘radio’ name=‘gender’>Female
<input type=‘radio’ name=‘gender’ checked>Female
Hidden Control
This control is used to store data that is not visible to the user.
<input type=‘hidden’ name=‘empid’ value=‘101’>
Fileupload Control
This control allow the user to upload files to the Web Server.
<input type=‘file’ name=‘profilepic’>
UNIT-1 HTML 31
Choice Control or Selection List
This is like a drop down list boxes. It is created the <select> tag.
attributes :
size : specifies the number of items to be displayed at a time.
multiple : specifies more than 1 item to be selected.
<select name=‘courses’>
<select name=‘courses’ size=4>
<select name=‘courses’ size=4 multiple>
◦ <option> tag
This tag is used to provide items to drop down list.
<option value=‘’>itemtext</option>
<select name=‘courses’>
<option value=‘1000’>C</option>
<option value=‘1500’>CPP</option>
<option value=‘4000’>Java</option>
</select>
UNIT-1 HTML 32
Button
Buttons are the standard and clickable buttons.
<input type=‘button’ value=‘’>
Value attribute specifies the caption of the button.
◦ Submit Button
The submit button is used to send data from client to Web Server.
<input type=‘submit’> - Submit Query
<input type=‘submit’ value=‘’>
◦ Reset Button
It is used to allow the user to clear all the input data they have entered.
<input type=‘reset’> - Reset
<input type=‘reset’ value=‘’>
UNIT-1 HTML 33
UNIT-1 HTML 34
HTML HTML5
It didn’t support audio and video without the It supports audio and video controls with the use
It does not allow drag and drop effects. It allows drag and drop effects.
Not possible to draw shapes like circle, HTML5 allows to draw shapes like circle,
It is almost impossible to get true One can track the GeoLocation of a user easily
UNIT-1 HTML-5 2
HTML5 Features
The canvas element for drawing
The video and audio elements for media
playback
Better support for local offline storage
New content specific elements, like
article, footer, header, nav, section
New form controls, like date, datetime,
email, url, color, image, number, tel
UNIT-1 HTML-5 3
HTML5 document
<!DOCTYPE html>
<html lang="en">
<head>
<title>Simple HTML5 document</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
UNIT-1 HTML-5 4
Structure Of HTML 5 Document
UNIT-1 HTML-5 5
<header> Tag
The <header> element represents a container for introductory content
or a set of navigational links.
<header>
<h1>Main page heading here</h1>
<p>Posted by John Doe</p>
</header>
UNIT-1 HTML-5 6
<nav> Tag
The <nav> element is used to mark up a collection of links to external
pages or sections within the current page. As well as being used for the
main website navigation.
<nav>
<ul>
<li><a href="#chapter-one">Chapter One</a>
<li><a href="#chapter-two">Chapter Two</a>
<li><a href="#chapter-three">Chapter Three</a>
</ul>
</nav>
o/p :
Chapter One
Chapter Two
Chapter Three
UNIT-1 HTML-5 7
<article> Tag
The article element represents a component of a page that consists
of a self-contained composition in a document
Ex. Blog, newspaper article
O/P :
This is the main header
Apple
The apple is the pomaceous fruit of the apple tree...
... UNIT-1 HTML-5 8
<section> Tag
The section tag divides the content into section and subsections. The
section tag is used when requirements of two headers or footers or any
other section of documents needed.
<h1>How to Fish</h1>
<section>
<h2>Introduction</h2>
<p>People have been catching fish for food since before recorded
history…</p>
</section>
<section>
<h2>Equipment</h2>
<p>The first thing you’ll need is a fishing rod or pole that you find
comfortable and is strong enough for the kind of fish you’re expecting to
land…</p>
</section>
UNIT-1 HTML-5 9
<aside> Tag
The HTML <aside> element represents a portion of a document whose
content is only indirectly related to the document's main content.
Asides are frequently presented as sidebars or call-out boxes.
<aside>
<p>The Rough-skinned Newt defends itself with a deadly
neurotoxin.</p>
</aside>
UNIT-1 HTML-5 10
<footer> Tag
The <footer> element is used to represent information about a
section such as the author, copyright information, or links to related
web pages.
<footer>
Copyright Matt West 2014
</footer>
O/P :
UNIT-1 HTML-5 11
<progress> tag
The HTML <progress> element displays an indicator showing the
completion progress of a task, typically displayed as a progress bar.
attributes :
Value : It defines that how much work the task has been completed.
Max : It defines that how much work the task requires in total.
UNIT-1 HTML-5 12
<audio> tag
HTML audio tag is used to define sounds such as music and other
audio clips. Currently there are three supported file format for HTML 5
audio tag.
◦ mp3, wav , ogg
attributes:
controls : It defines the audio controls which is displayed with play/pause buttons.
Autoplay : It specifies that the audio will start playing as soon as it is ready.
Loop :It specifies that the audio file will start over again, every time when it is completed.
Muted : It is used to mute the audio output.
Preload : It specifies the author view to upload audio file when the page loads.
Src : It specifies the source URL of the audio file.
<audio controls>
<source src="myAudio.mp3" type="audio/mpeg">
<source src="myAudio.ogg" type="audio/ogg">
</audio>
UNIT-1 HTML-5 13
<vedio> tag
HTML 5 supports <video> tag also. The HTML video tag is used for
streaming video files such as a movie clip, song clip on the web page.
Currently, there are three video formats supported for HTML video tag:
◦ Mp4 , webM , ogg
attributes:
Controls : It defines the video controls which is displayed with play/pause buttons.
Height : It is used to set the height of the video player.
Width : It is used to set the width of the video player.
Poster : It specifies the image which is displayed on the screen when the video is not played.
Autoplay : It specifies that the video will start playing as soon as it is ready.
Loop : It specifies that the video file will start over again, every time when it is completed.
Muted : It is used to mute the video output.
Preload : It specifies the author view to upload video file when the page loads.
Src : It specifies the source URL of the video file.
<video controls>
<source src="movie.ogg" type="video/ogg">
</video>
UNIT-1 HTML-5 14
New Form Elements
color
color provide a user interface element that lets a user specify a color,
either by using a visual color picker interface
date
date create input fields that let the user enter a date, either with a
textbox that validates the input or a special date picker interface.
email
email is used to let the user enter and edit an e-mail address, or, if the
multiple attribute is specified, a list of e-mail addresses.
<input type="email" id="email“>
UNIT-1 HTML-5 15
New Form Elements
image
image is used to create graphical submit buttons, i.e. submit buttons
that take the form of an image rather than text.
<input type="image" id="image" alt="Login“ src=“button.gif">
number
number is used to let the user enter a number. They include built-in
validation to reject non-numerical entries.
<input type="number" id="tentacles" name="tentacles“ min="10"
max="100">
tel
tel is used to let the user enter and edit a telephone number.
<input type="tel" id="phone" name="phone"
pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
required>
<small>Format: 123-456-7890</small>
UNIT-1 HTML-5 16
New Form Elements
url
url is used to let the user enter and edit a URL
<input type="url" name="url"
id="url“placeholder="https://example.com"
size="30“ required>
datetime-local
datetime-local create input controls that let the user easily enter both a
date and a time, including the year, month, and day as well as the time
in hours and minutes.
<input type="datetime-local" id="meeting-time"
name="meeting-time" value="2018-06-12T19:30"
min="2018-06-07T00:00" max="2018-06-14T00:00">
UNIT-1 HTML-5 17
1
ADAVANTAGES OF CSS
UNIT-1 CSS 2
Inline or Attribute style
• Inline styles are used to apply the unique style rules to an element by
putting the CSS rules directly into the start tag. It can be attached to an
element using the style attribute.
• The style attribute includes a series of CSS property and value pairs.
Each "property: value" pair
<h1 style=“color:white;background-color:blue”>Hello</h1>
tag
property
attribute value
UNIT-1 CSS 3
Internal or tag or Embedded style
• Embedded or internal style sheets only affect the document they are
embedded in.
UNIT-1 CSS 5
CSS PROPERTIES
UNIT-1 CSS 6
Color and Background Properties
• The color property defines the text color of an element.
h1 { color: red; }
p { color: purple; }
UNIT-1 CSS 7
• background-color
body { background-color: green; }
• background-image
body { background-image: url(“bg1.gif"); }
• background-repeat
body { background-image: url("images/gradient.png");
background-repeat: repeat-x; }
• background-attachment
body {
background-image: url("images/bell.png");
background-repeat: no-repeat;
background-attachment: fixed;
}
• background-position
body {
background-image: url("images/robot.png");
background-repeat: no-repeat;
background-position: right top;
} UNIT-1 CSS 8
• FONT Properties
• CSS provide several properties for styling the font of the text, including
changing their face, controlling their size and boldness, managing variant, and
so on.
The font properties are:
font-family : to specify the font to be used to render the text
body { font-family: Arial, Helvetica, sans-serif; }
font-style : to set the font face style for the text content of an element
values : normal, italic or oblique.
p{ font-style: oblique; }
font-size : to set the size of font for the text content of an element.
p{ font-size: 20px;}
p {
border: 5px solid red;
}
UNIT-1 CSS 11
• LINK Properties
• A link has four different states — link, visited, active and hover. These four
states of a link can be styled differently through using the following anchor
pseudo-class selectors.
a:link : define styles for normal or unvisited links.
a:visited : define styles for links that the user has already visited.
a:hover : define styles for a link when the user place the mouse pointer over it.
a:active : define styles for links when they are being clicked.
a:link { /* unvisited link */
color: YELLOW;
text-decoration: none;
border-bottom: 1px solid;
}
a:visited { /* visited link */
color: RED;
}
a:hover { /* mouse over link */
color: GREEN;
border-bottom: none;
}
a:active { /* active link */
color: BLUE;
} UNIT-1 CSS 12
• LIST Properties
• CSS provides the several properties for styling and formatting the most
commonly used unordered and ordered lists.
UNIT-1 CSS 13
• CSS Selectors
• A CSS selector is a pattern to match the elements on a web page. The style rules associated
with that selector will be applied to the elements that match the selector pattern.
CSS Element Selector : The Element selector selects the HTML element by name.
p { color: blue; }
CSS ID Selector : The id selector is used to define style rules for a single or unique element.
The id selector is defined with a hash sign (#) immediately followed by the id value.
<style> <body>
#error { <p id="error">This is a
color: #ff0000; warning!</p>
}
</style>
</body>
CSS Class Selector :The class selectors can be used to select any HTML
element that has a class attribute. All the elements having that class will be
formatted according to the defined rule. The class selector is defined with a period
sign (.) immediately followed by the class value.
<style>
.blue { <h1 class="blue">This is a
color: red; heading</h1>
} <p class="blue">This is a
</style> paragraph.</p>
14
UNIT-1 CSS
• CSS Selectors
Global or Universal Selector
CSS universal selectors select any type of elements in an HTML page.
An asterisk ( i.e. "*" ) is used to denote a CSS universal selector. An asterisk
can also be followed by a selector. This is useful when you want to set a style
for of all the elements of an HTML page or for all of the elements within an
element of an HTML page.
* { CSS-Property: value; ........................ }
*{
color: blue; /* color of all the elements should be blue */
background: silver; /* silver background is set for all the
elements */
}
Select all elements inside <div> elements and set their background color
to yellow:
div * {
background-color: yellow;
}
15
UNIT-1 CSS
• CSS BOX MODEL
• All HTML elements can be considered as boxes. In CSS, the term "box
model" is used when talking about design and layout.
• The CSS box model is essentially a box that wraps around every HTML
element. It consists of:
margins, borders, padding, and the actual content
16
UNIT-1 CSS
• CSS BOX MODEL
Margin - Clears an area outside the border. The margin is transparent
Border - A border that goes around the padding and content
Padding - Clears an area around the content. The padding is transparent
Content - The content of the box, where text and images appear
<!DOCTYPE html>
<html>
<head>
<style>
div {
background-color: lightgrey; width: 300px; border: 15px solid green;
padding: 50px; margin: 20px; }
</style>
</head>
<body>
<h2>Demonstrating the Box Model</h2>
<p>The CSS box model is essentially a box that wraps around every HTML element. It
consists of: borders, padding, margins, and the actual content.</p>
<div>
Content
</div>
</body>
</html> 17
UNIT-1 CSS
• CSS POSITION PROPERTY
The CSS position property defines the position of an element in a document.
This property works with the left, right, top, bottom and z-index properties to
determine the final position of an element on a page.
position: value;
Value Description
Normal position for the element (where top, right,
static bottom, and left have no effect)
div { position: static; }
18
UNIT-1 CSS
• CSS CURSOR PROPERTY
The cursor property specifies the mouse cursor to be displayed when pointing
over an element.
cursor: value;
•Embedding the JavaScript code between a pair of <script> and </script> tag.
<script> document.write(“HEELO”);</script>
•Creating an external JavaScript file with the .js extension and then load it
within the page through the src attribute of the <script> tag.
<script src="js/hello.js"></script>
•Placing the JavaScript code directly inside an HTML tag using the special tag
attributes such as onclick, onmouseover, onkeypress, onload, etc.
<button onclick="alert('Hello World!')">Click Me</button>
UNIT-2 JAVA SCRIPT 3
•JavaScript Syntax
•JavaScript Variables
Variables are fundamental to all programming languages. Variables are used to
store data, like string of text, numbers, etc. The data or value stored in the
variables can be set, updated, and retrieved whenever needed
•You can create a variable with the var keyword.
•JavaScript Variables
Variables are fundamental to all programming languages. Variables are used to
store data, like string of text, numbers, etc. The data or value stored in the
variables can be set, updated, and retrieved whenever needed
•You can create a variable with the var keyword.
•Arithmetic Operators
+,-,*,/,%
•Assignment Operators
=,+=,-=,*=,/=.%=
•Comparison Operators
<,>,<=,>=,==,!=
•The if statement
The if statement is used to execute a block of code only if the specified
condition evaluates to true.
if(condition){
// Code to be executed
}
•for…in
loops through the properties of an object.
for(variable in object) {
// Code to be executed
}
•for…of
loops over iterable objects such as arrays, strings, etc.
for(var variable of array)
{
// Code to be executed
}
• break
terminates the current execution of the loop
break;
• continue:
terminates the current iteration of the loop
continue;
UNIT-2 JAVA SCRIPT 12
•JavaScript Arrays
Arrays are complex variables that allow us to store more than one value or a
group of values under a single variable name. JavaScript arrays can store any
valid value, including strings, numbers, objects, functions, and even other
arrays, thus making it possible to create more complex data structures such as
an array of objects or an array of arrays.
Creating an Array
var myArray = [element0, element1, ..., elementN];
var colors = ["Red", "Green", "Blue"];
var myArray = new Array(element0, element1, ..., elementN);
var colors = new Array["Red", "Green", "Blue"];
•Accessing the Elements of an Array
Array elements can be accessed by their index using the square bracket
notation. An index is a number that represents an element's position in an
array.Array indexes are zero-based.
document.write(colorss[0]);
•Getting the Length of an Array
The length property returns the length of an array
document.write(colors.length);
UNIT-2 JAVA SCRIPT 13
•JavaScript Functions
A function is a group of statements that perform specific tasks and can be kept and
maintained separately form main program. Functions provide a way to create
reusable code packages which are more portable and easier to debug
•Functions makes the code much easier to maintain — Since a function created once
can be used many times, so any changes made inside a function automatically
implemented at all the places without touching the several files.
• There are several ways to assign an event handler.The simplest way is to add
them directly to the start tag of the HTML elements using the special event-
handler attributes. For example, to assign a click handler for a button element,
we can use onclick attribute, like this:
• To keep the JavaScript seperate from HTML, you can set up the event handler
in an external JavaScript file or within the <script> and </script> tags, like this:
Features of DHTML
document.getElementsByTagName(tagname)
var x = document.getElementsByTagName("LI").length;
Remove Element
The removeChild() method is used to remove element.
24
UNIT-2 JAVA SCRIPT
2) The global flag (g)
• Without the global flag, the RegExp object only checks if there is a match in a
string and returns the first match.
• When the g flag is available, the RegExp looks for all matches and returns all
of them.It’s possible to combine flags e.g., gi flags combine the ignore (i) and
the global flag (g) flags.
• The exec() method of the RegExp performs a search for a match in a string
and returns an array that contains detailed information about the match.
25
UNIT-2 JAVA SCRIPT
Searching strings
• The method str.match(regexp) returns all matches of regexp in the string str.
• To find all matches, you use the global flag (g). And to find the matches
regardless of cases, you use the ignore flag (i).
var str = "Are you Ok? Yes, I'm OK";
var result = str.match(/OK/gi);
console.log(result); [“Ok”,”OK”]
Replacing strings
The replace() method to replace the first occurrence of the string.
var str = "Are you OK? Yes, I'm OK.";
var result = str.replace('Ok','fine');
console.log(result); Are you fine? Yes, I'm OK
26
UNIT-2 JAVA SCRIPT
Searching strings
The search() method uses an expression to search for a match, and returns the
position of the match.
var re = /Are/i;
var str = 'hi There! How are you?';
var index = str.search(re);
document.write(index); // 14
28
UNIT-2 JAVA SCRIPT
Regular Expression Quantifiers
Quantifiers match a number of instances of a character, group, or character
class in a string.
Exact count {n}
A number in curly braces {n}is the simplest quantifier. When you append it
to a character or character class, it specifies how many characters or
character classes you want to match.
var str = 'ECMAScript 2020';
var re = /\d{4}/;
var result = str.match(re);
console.log(result); // [“2020”]
+ - Match one or more times.
var phone = "+1-(408)";
var result = phone.match(/\d+/g);
console.log(result); // [“1”,”408”]
* - Match zero or more times.
var str = 'JavaScript is not Java';
var re = /Java\w*/g
var results = str.match(re);
console.log(results); // [“JavaScript”,”Java”]
29
UNIT-2 JAVA SCRIPT
Quantifier Description
* Match zero or more times.
+ Match one or more times.
? Match zero or one time.
{n} Match exactly n times.
{ n ,} Match at least n times.
{n,m} Match from n to m times.
• Whole numbers:/^\d+$/
• Decimal numbers:/^\d*.\d+$/
• Whole numbers and decimal numbers:/^\d*(.\d+)?$/
• Negative, positive whole numbers & decimal numbers:/^-?\d*(.\d+)?$/
30
UNIT-2 JAVA SCRIPT
Regular Expression Sets and Ranges
Sets
The square brackets search for any character in a set.
var str = 'How cats, rats, and bats became Halloween animals';
var re = /[cbr]ats/g;
var results = str.match(re);
console.log(results); // [“cats”,”rats”,”bats”]
Ranges
The square brackets can contain character ranges. For example, [a-z] is a character
range from a to z. And [0-9] is a digit from 0 to 9.
Excluding ranges
To negate a range, you use the excluding range like: [^...].
For example, [^0-9] matches any character except a digit.
Or, the [^aeiou] matches any character except 'a', 'e', 'i', 'o' and 'u'.
31
UNIT-2 JAVA SCRIPT
Java Script Objects
Company Model
Year Color
here
• Car is an Object
• Company, Model, Year and Color are properties of Car
• start(), stop() and accelerate() are methods of Car object.
32
UNIT-2 JAVA SCRIPT
Java Script Object Creation
• Object Literal
• Instance of Object
• Constructor Function
33
UNIT-2 JAVA SCRIPT
Java Script Built-in Objects
Math Object
• Math object is a built-in static object.
• It is used for performing complex math operations.
Methods Description
abs() Returns the absolute value of a number.
acos() Returns the arccosine (in radians) of a
number.
ceil() Returns the smallest integer greater than or
equal to a number.
cos() Returns cosine of a number.
floor() Returns the largest integer less than or
equal to a number.
log() Returns the natural logarithm (base E) of a
number.
max() Returns the largest of zero or more
numbers.
min() Returns the smallest of zero or more
numbers.
pow() Returns base to the exponent power, that is
base exponent.
34
UNIT-2 JAVA SCRIPT
Java Script Built-in Objects
Date Object
• Date is a data type.
• Date object manipulates date and time.
• Date() constructor takes no arguments.
• Date object allows you to get and set the year, month, day, hour, minute, second
and millisecond fields.
35
UNIT-2 JAVA SCRIPT
Methods Description
36
UNIT-2 JAVA SCRIPT
Java Script Built-in Objects
String Object
• String objects are used to work with text.It works with a series of characters.
Methods Description
charAt() It returns the character at the specified index.
37
UNIT-2 JAVA SCRIPT
X M L
1
What is xml ?
UNIT-3 XML 2
Difference between xml and html
• Html tags are predefined, whereas xml tags are not.
• Html is used to display data, taking care of how data is being presented. xml is
used to carry data. It takes care of how data works.
• Opening and closing tags of an xml document must be of same case. html does
not have any such restriction.
• In xml, end tags are required for well-formed (i.e. valid) document. But not in
html.
• Quotes are required around attributes values in xml, in html it is not required.
• Slash (/) required in empty tags as far as xml is concerned, html does not need
that.
XML Example
XML documents create a hierarchical structure looks like a tree so it is known as
XML Tree that starts at "the root" and branches to "the leaves".
<root>
<child>
<subchild>.....</subchild>
</child>
</root>
UNIT-3 XML 3
Example of XML Document PROLOG
• The first line is the XML declaration or XML Prolog. It defines the XML
version (1.0) and the encoding used (ISO-8859-1 = Latin-1/West
European character set). UTF-8 is the default character encoding for XML
documents.
• The next line describes the root element of the document.
• The next 4 lines describe 4 child elements of the root (to, from, heading,
and body).
• And finally the last line defines the end of the root element.
UNIT-3 XML 4
Example of XML Document
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore> UNIT-3 XML 5
Well Formed XML (Valid XML)
There are two different document type definitions that can be used with XML:
UNIT-3 XML 7
Types of DTD
• Internal DTD : a DTD is declared within the file it is called Internal DTD
• External DTD : a DTD is declared in a separate file it is called External DTD.
Internal DTD
A DTD is referred to as an internal DTD if elements are declared within the XML
files. To reference it as internal DTD, standalone attribute in XML declaration must
be set to yes. This means the declaration works independent of external source.
address.xml
<?xml version = "1.0" encoding = "UTF-8" standalone = "yes" ?>
<!DOCTYPE address [
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
]>
<address>
<name>Mr.K.Ravi Kumar</name>
<company>Usharama</company>
<phone>9848209419</phone>
</address>
UNIT-3 XML 8
External DTD
• In external DTD elements are declared outside the XML file.
• They are accessed by specifying the system attributes which may be either the
legal .dtd file
• To reference it as external DTD, standalone attribute in the XML declaration
must be set as no. Declaration includes information from the external source.
address.xml
<?xml version = "1.0" encoding = "UTF-8" standalone = "no" ?>
<!DOCTYPE address SYSTEM "address.dtd">
<address>
<name>Mr.K.Ravi Kumar</name>
<company>Usharama</company>
<phone>9848209419</phone>
</address>
address.dtd
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
UNIT-3 XML 9
Defining Elements in XML
• XML elements can be defined as building blocks of an XML document.
Elements can behave as a container to hold text, elements, attributes, media
objects or mix of all.
• A DTD element is declared with an ELEMENT declaration. When an XML file
is validated by DTD, parser initially checks for the root element and then the
child elements are validated.
Syntax
All DTD element declarations have this general form −
<!ELEMENT elementname (content)>
• ELEMENT declaration is used to indicate the parser that you are about to define
an element.
• elementname is the element name (also called the generic identifier) that you are
defining.
• content defines what content (if any) can go within the element.
child1, child2.. are the elements and each element must have its own definition
within the DTD.
UNIT-3 XML 10
Defining the Order of Child Elements in XML
When there are no.of child elements you must specify the order of occurance.There
are two ways to specify the order of occurrence.
1. Using the comma between child element name and the next element child
element name that indicates the child elements will occur in the given order.
2. Using a vertical line means that either one or the other child element will occur.
• The DTD attributes start with <!ATTLIST keyword if the element contains the
attribute.
• element-name specifies the name of the element to which the attribute applies.
• attribute-name specifies the name of the attribute which is included with the
element-name.
• attribute-type defines the type of attributes.
• attribute-value takes a fixed value that the attributes must define.
UNIT-3 XML 12
Attribute Values
Within each attribute declaration, you must specify how the value will appear in the
document. You can specify if an attribute −
• can have a default value
<!ATTLIST element-name attribute-name attribute-type "default-value">
<!ELEMENT name ( #PCDATA )>
<!ATTLIST name id CDATA "0">
• is required
<!ATTLIST element-name attribute-name attribute-type #REQUIRED>
<!ELEMENT name ( #PCDATA )>
<!ATTLIST name id CDATA #REQUIRED>
• is implied
<!ATTLIST element-name attribute-name attribute-type #IMPLIED>
<!ELEMENT name ( #PCDATA )>
<!ATTLIST name id CDATA #IMPLIED>
UNIT-3 XML 13
Limitations of DTD
UNIT-3 XML 14
XML Schema
• XML Schema is commonly known as XML Schema Definition (XSD).
• It is used to describe and validate the structure and the content of XML data.
• XML schema defines the elements, attributes and data types.
• Schema element supports Namespaces.
• It is similar to a database schema that describes the data in a database.
Elements
An element can be defined within an XSD
<xs:element name=“data”>
<xs:simpleType>
<xs:element name=“firstname” type=“xs:string” />
<xs:element name=“phone” type=“xs:integer”/>
</xs:simpleType>
</xs:element>
<data>
<firstname>Ravi</firstname>
<phone>9848209419</phone>
</data>
UNIT-3 XML 16
Defining a Complex Type Element
A complex type element can be defined with <xs:complexType>
<xs:element name="shipto">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="address" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
<xs:element name="country" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
UNIT-3 XML 17
Defining Compositors
Compositors provide rules that determine how and in what order there children can
appear within XML document.
There are three types of compositors \
<xs:sequence>
The child elements in the XML document MUST appear in the order they are
declared in the XSD schema.
<xs:choice>
Only one of the child elements described in the XSD schema can appear in the XML
document.
<xs:all>
The child elements described in the XSD schema can appear in the XML document
in any order
UNIT-3 XML 18
<xs:choice>
<xs:element name=“course”>
<xs:complexType>
<xs:choice>
<xs:element name=“course1” type=”xs:string”/>
<xs:element name=“course2” type=”xs:string”/>
</xs:choice>
</xs:complexType>
</xs:element>
<xs:all>
<xs:element name=“course”>
<xs:complexType>
<xs:all>
<xs:element name=“course1” type=”xs:string”/>
<xs:element name=“course2” type=”xs:string”/>
</xs:all>
</xs:complexType>
</xs:element>
UNIT-3 XML 19
Occurrence Indicators
• It is possible to constraint the number of occurrences of an XML element that
appear in an XML document.
• The occurrence is specified using the minOccurs and maxOccurs attributes,
and allows an element to be specified as mandatory, optional, or can appear up to
a set number of times.
• The default values for minOccurs and maxOccurs is 1. Therefore, if both the
minOccurs and maxOccurs attributes are absent, the element must appear once
and once only.
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="full_name" type="xs:string"/>
<xs:element name="child_name" type="xs:string" minOccurs="0"
maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
UNIT-3 XML 20
XSD Restrictions
Restrictions are used to define acceptable values for XML elements or attributes.
UNIT-3 XML 21
S.No. Restriction & Description
1 enumeration
Defines a list of values which are acceptable.
2 fractionDigits
Defines the maximum number of decimal places allowed(zero or more).
4 maxExclusive
Defines upper bounds for numeric values excluding this number.
5 maxInclusive
Defines upper bounds for numeric values including this number.
6 maxLength
Defines maximum length in terms of characters of string or items in a list(zero or more).
7 minExclusive
Defines lower bounds for numeric values excluding this number.
8 minInclusive
Defines lower bounds for numeric values including this number.
9 minLength
Defines minimum length in terms of characters of string or items in a list(zero or more).
10 pattern
Defines the exact sequence of characters identified by the pattern that are acceptable
11 totalDigits
Defines the exact number of digits allowed in the number(always greater than zero)
UNIT-3 XML 22
Attributes in XSD
An attribute provides extra information within an element. Attributes have name and
type properties
where x is the name of the attribute and y specifies the data type of the attribute
UNIT-3 XML 23
A fixed value is also automatically assigned to the attribute, and you cannot
specify another value.
Attributes are optional by default. To specify that the attribute is required, use the
"use" attribute:
UNIT-3 XML 24
XML Parsing
• The purpose of parsing an XML document is to make some interfaces
available to an application that needs to make use of the document ; using
those interfaces , the application can inspect, retrieve, and modify the
document’s contents .
• Parsing is the dissection of a block of text into discernible words (also known
as tokens).
• The XML parser sits in the middle between an XML document and an
application that uses it.
UNIT-3 XML 25
What is the DOM?
• DOM is an acronym for Document Object Model.
• DOM parser loads the complete XML file into memory and creates a tree
structure where each node in the tree represents a component of XML file.
• With DOM parser you can create nodes, remove nodes, change their contents
and traverse the node hierarchy.
• DOM provides maximum flexibility while working with XML files but it comes
with a cost of potentially large memory footprint and significant processor
requirements in case of large XML files
UNIT-3 XML
Dom Standards
The DOM has steadily evolved by increasing the detail of the representation, the
scope of the representation, and adding new manipulation methods.
There are currently three DOM levels:
DOM Level 1:
This set of classes represents XML 1.0 and HTML 4.0 documents.
DOM Level 2:
This extends Level 1 to add support for namespaces; cascading style
sheets, level 2 (CSS2); alternate views; user interface events; and
enhanced tree manipulation via interfaces for traversal and ranges.
DOM Level 3:
This extends Level 2 by adding support for mixed vocabularies (different
namespaces), XPath expressions, load and save methods, and a
representation of abstract schemas (includes both DTD and XML
Schema).
UNIT-3 XML
Document Object Model
Generic Form:
UNIT-3 XML
Document Object Model
Programming interface:
UNIT-3 XML
DOM Example
<?xml version=“1.0”?>
<name>Jane Doe</name>
Node Name=“John Doe”
<email>[email protected]</email>
Node [email protected]”
</person>
</addressbook>
UNIT-3 XML
Common DOM Methods
UNIT-3 XML
Common DOM methods
Node.getNodeValue()- value of this node, depending on its type, e.g. value of an
attribute but null in case of an element node.
UNIT-3 XML
Common DOM methods
UNIT-3 XML
Simple API for XML (SAX)
SAX Parser parses the XML file line by line and triggers events when it
encounters opening tag, closing tag or character data in XML file.
SAX parser does not create any objects at all, it simply delivers events.
UNIT-3 XML
SAX features
SAX API acts like a data stream.
Stateless.
UNIT-3 XML
Basic SAX events
startElement – gives the name of the tag and any attributes it might have.
characters – parser will call this method to report each chunk of character
data.
UNIT-3 XML
Additional SAX events
warning – reports conditions that are not errors or fatal errors as defined by the
XML 1.0 recommendation, e.g. if an element is defined twice in a DTD.
UNIT-3 XML
SAX events in a simple example
UNIT-3 XML
How Does SAX work?
UNIT-3 XML
DOM vs SAX
UNIT-3 XML
XSLT
XSL
Before learning XSLT, we should first understand XSL which stands for
EXtensible Stylesheet Language. It is similar to XML as CSS is to HTML.
In case of HTML document, tags are predefined such as table, div, and span; and
the browser knows how to add style to them and display those using CSS styles.
But in case of XML documents, tags are not predefined. In order to understand
and style an XML document, World Wide Web Consortium (W3C) developed
XSL which can act as XML based Stylesheet Language.
An XSL document specifies how a browser should render an XML document.
UNIT-3 XML
How XSLT Works
An XSLT stylesheet is used to define the transformation rules to be applied on
the target XML document. XSLT stylesheet is written in XML format.
XSLT Processor takes the XSLT stylesheet and applies the transformation rules
on the target XML document and then it generates a formatted document in the
form of XML, HTML, or text format.
This formatted document is then utilized by XSLT formatter to generate the
actual output which is to be displayed to the end-user.
UNIT-3 XML
XSLT ELEMENTS
1. <xsl:stylesheet>
Every XSLT code must start with the root element either <xsl:stylesheet> or
<xsl:transform>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
version="2.0">
UNIT-3 XML
2. <xsl:template>
This declaration defines a set of rules applied to process or transform the selected
input element of the source document to the defined target element rules of the
output documents.
Basically two types of templates are available as per their attributes:
(i) Named Template: When the xsl: template element contains @name attribute
then this is called Named Template.
<xsl:template name="book">
Named templates are called by xsl:call-template element.
<xsl:call-template name="book">
(ii) Match Template: The xsl:template element contains @match attribute that
contains a matching pattern or XPath applied at the input nodes.
<xsl:template match="/">
<xsl:template match=“//book”>
Match templates are called by xsl:apply-template element.
<xsl:apply-templates select="book"/>
UNIT-3 XML
3. <xsl:value-of>
◦ The <xsl:value-of> element extracts the value of a selected node.
◦ The <xsl:value-of> element can be used to select the value of an XML element
and add it to the output.
<xsl:value-of select="expression“>
select : an attribute
expression : An XPath expression that specifies which node/attribute to extract the
value from.
<xsl:value-of select="catalog/cd/title" />
4. <xsl:if>
To put a conditional if test against the content of the XML file, add an <xsl:if>
element to the XSL document.
<xsl:if test="expression">
...some output if the expression is true...
</xsl:if>
UNIT-3 XML
<xsl:for-each>
The XSL <xsl:for-each> element can be used to select every XML element of a
specified node-set:
<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>
UNIT-3 XML
<xs:sort>
The <xsl:sort> element is used to sort the output.
<xsl:for-each select="catalog/cd">
<xsl:sort select="artist"/>
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:for-each>
UNIT-3 XML
PHP
UNIT - 4 PHP 1
The Internet is the global system of interconnected computer networks that
uses the Internet protocol suite (TCP/IP) to communicate between networks
and devices. ...
W W W – World Wide Web. It is the collections of Networks that make up
the internet
URL – Uniform Resource Locator. The internet uses url to identify
resources available on the internet
protocol://domainname:port/websitename/webpagename
http://10.1.1.30:80/ecap/default.aspx
HTTP – Hyper Text Transfer Protocol .The communications protocol used to
connect to Web servers on the Internet or on a local network (intranet).
Its primary function is to establish a connection with the server and send
HTML pages back to the user's browser.
It allows your web browser (i.e. Google Chrome, Mozilla Firefox, Apple
Safari or Internet Explorer) to communicate with the server where any given
website is hosted.
UNIT-4 PHP 2
UNIT-4 PHP 3
Web Application
A web application (or web app) is an application software that runs on
a web server, unlike computer-based software programs that are stored locally on
the Operating System (OS) of the device. Web applications are accessed by the
user through a web browser with an active internet connection.
Common web applications include email, online retail sales, online auctions,
wikis, instant messaging services and more.
Web Server
A web server is a computer that runs websites. It's a computer program that
distributes web pages as they are requisitioned. The basic objective of the web
server is to store, process and deliver web pages to the users. This
intercommunication is done using Hypertext Transfer Protocol (HTTP).
UNIT-4 PHP 5
What is PHP?
• PHP stands for Hypertext Preprocessor.
• PHP is a very popular and widely-used open source server-side
scripting language to write dynamically generated web pages.
• PHP was originally created by Rasmus Lerdorf in 1994.
• It was initially known as Personal Home Page.
• PHP scripts are executed on the server and the result is sent to the
web browser as plain HTML.
• PHP can be integrated with the number of popular databases,
including MySQL, PostgreSQL, Oracle, Microsoft SQL Server,
Sybase, and so on.
• The current major version of PHP is 7
UNIT - 4 PHP 6
What You Can Do with PHP
• You can generate pages and files dynamically.
• You can create, open, read, write and close files on the server.
• You can collect data from a web form such as user information,
email, phone no, etc.
• You can send emails to the users of your website.
• You can send and receive cookies to track the visitor of your
website.
• You can store, delete, and modify information in your database.
• You can restrict unauthorized access to your website.
• You can encrypt and decrypt data for safe transmission over
internet.
UNIT - 4 PHP 7
Setting Up a Local Web Server
PHP script execute on a web server running PHP. So before you start writing any
PHP program you need the following program installed on your computer.
You can either install them individually or choose a pre-configured package for
your operating system like Linux and Windows.
Popular pre-configured package are XAMPP and WampServer.
UNIT - 4 PHP 8
XAMPP Web Server
UNIT - 4 PHP 9
PHP File
UNIT - 4 PHP 10
PHP Comments
UNIT - 4 PHP 11
PHP output statements
The PHP echo Statement
• The echo statement can output one or more strings.
• The echo statement can display anything that can be displayed to the browser,
such as string, numbers, variables values, the results of expressions etc.
• you can use it without parentheses e.g. echo or echo().
• If you want to pass more than one parameter to echo, the parameters must not
be enclosed within parentheses.
<?php
// Displaying HTML code
echo "<h4>This is a simple heading.</h4>";
echo "<h4 style='color: red;'>This is heading with style.</h4>";
?>
The PHP print Statement
• You can also use the print statement (an alternative to echo) to display output to
the browser.
• You can also use it without parentheses like: print or print().
• Both echo and print statement works exactly the same way except that the print
statement can only output one string, and always returns 1.
<?php
// Displaying HTML code
print "<h4>This is a simple heading.</h4>";
print "<h4 style='color: red;'>This is heading with style.</h4>";
?> UNIT - 4 PHP 12
PHP processor modes
• copy
• interpret.
• The processor starts off in copy mode; text from the file, typically HTML, is
copied to the network connection and sent to the client browser.
• When a <?php processing instruction is encountered the processor switches to
interpret mode. The PHP statements are interpreted, and their output, if any, is
sent to the browser. The processor remains in interpret mode until a ?> is
encountered.
• which switches it back to copy mode.
UNIT - 4 PHP 13
PHP Variables
• Variables are used to store data, like string of text, numbers, etc. Variable
values can change over the course of a script.
• In PHP, a variable does not need to be declared before adding a value to it.
• PHP automatically converts the variable to the correct data type, depending on
its value.
Naming Conventions for PHP Variables
• All variables in PHP start with a $ sign, followed by the name of the variable.
• A variable name must start with a letter or the underscore character _.
• A variable name cannot start with a number.
• A variable name in PHP can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _).
• A variable name cannot contain spaces.
UNIT - 4 PHP 14
PHP Constants
• A constant is a name or an identifier for a fixed value. Constant are like
variables, except that once they are defined, they cannot be undefined or
changed
• Constants are very useful for storing data that doesn't change while the script is
running.
• Common examples of such data include configuration settings such as database
username and password, website's base URL, company name, etc.
• Constants are defined using PHP's define() function, which accepts two
arguments: the name of the constant, and its value. Once defined the constant
value can be accessed at any time just by referring to its name
<?php
//Defining constant
define("SITE_URL", "https://www.tutorialrepublic.com/");
// Using constant
echo ‘ Thank you for visiting - ' . SITE_URL;
?>
UNIT - 4 PHP 15
Data Types in PHP
The values assigned to a PHP variable may be of different data types including
simple string and numeric types to more complex data types like arrays and
objects.
•Integer
•Float
•String
•Boolean
• Array
•Object
• resource
•NULL
UNIT - 4 PHP 16
PHP Operators
Operators are symbols that tell the PHP processor to perform certain actions.
Arithmetic Operators
+ - Addition
- - Subtraction
* - multiplication
/ - Division
% - Modulus
Assignment Operators
= - Assign
+= - Add and Assign
-= - Subtract and Assign
*= - Multiply and Assign
/= - Division and Assign
%= - Modulus and Assign
Comparison Operators
< - less than
> - greater than
<= - less than or equal to
>= - greater than or euqal to
== - equals
!= - not equals UNIT - 4 PHP 17
PHP Operators
Logical Operators
and - And
or - or
xor - Xor
&& - And
|| - Or
! - Not
String Operators
. - concatenation
.= - concatenation assignment
UNIT - 4 PHP 18
PHP Data type Conversion
The mechanism of converting one type data into another type is called data
type conversion
UNIT - 4 PHP 19
PHP Data type Conversion
Explicit type conversion
Type casting refers to changing an variable of one data type into another
explicitly.
By placing the type name in parentheses in front of a variable, PHP converts
the value to the desired type:
UNIT - 4 PHP 20
PHP GET and POST
Methods of Sending Information to Server
A web browser communicates with the server typically using one of the two HTTP
(Hypertext Transfer Protocol) methods — GET and POST
The GET Method
In GET method the data is sent as URL parameters that are usually strings of name
and value pairs separated by ampersands (&). In general, a URL with GET data
will look like this:
http://www.example.com/action.php?name=john&age=24
Advantages and Disadvantages of Using the GET Method
• Since the data sent by the GET method are displayed in the URL, it is possible
to bookmark the page with specific query string values.
• The GET method is not suitable for passing sensitive information such as the
username and password, because these are fully visible in the URL query string
as well as potentially stored in the client browser's memory as a visited page.
• Because the GET method assigns data to a server environment variable, the
length of the URL is limited. So, there is a limitation for the total data to be
sent.
• PHP provides the super global variable $_GET to access all the information
sent either through the URL or submitted through an HTML form using the
method="get".
UNIT - 4 PHP 21
PHP GET and POST
The POST Method
UNIT - 4 PHP 22
PHP GET and POST
The $_REQUEST Variable
PHP provides another superglobal variable $_REQUEST that contains the values
of both the $_GET and $_POST variables as well as the values of the $_COOKIE
superglobal variable.
$name = $_GET[‘uname’]
$name = $_POST[‘uname’]
$name = $_REQUEST[‘uname’]
UNIT - 4 PHP 23
PHP Conditional Statements
PHP also allows you to write code that perform different actions based on the
results of a logical or comparative test conditions at run time.
• The if statement
• The if...else statement
• The if...else if....else statement
• The switch...case statement
The if Statement
The if statement is used to execute a block of code only if the specified condition
evaluates to true.
if(condition){
// Code to be executed
}
The if...else Statement
The if...else statement allows you to execute one block of code if the specified
condition is evaluates to true and another block of code if it is evaluates to false.
if(condition){
// Code to be executed if condition is true
} else{
// Code to be executed if condition is false
}
UNIT - 4 PHP 24
PHP Conditional Statements
The if...else if...else Statement
The if...else if...else a special statement that is used to combine multiple if...else
statements.
if(condition1){
// Code to be executed if condition1 is true
} else if(condition2){
// Code to be executed if the condition1 is false and condition2 is true
} else{
// Code to be executed if both condition1 and condition2 are false
}
Switch…Case Statements
The switch-case statement is an alternative to the if-else if-else statement, which
does almost the same thing. The switch-case statement tests a variable against a
series of values until it finds a match, and then executes the block of code
corresponding to that match.
switch(n){
case label1:
// Code to be executed if n=label1
break;
case label2:
// Code to be executed if n=label2
break;
...
default:
// Code to be executed if n is different from all labels} UNIT - 4 PHP 25
PHP Loops
• Loops are used to execute the same block of code again and again, as long as a
certain condition is met.
• The basic idea behind a loop is to automate the repetitive tasks within a program
to save the time and effort
• while
• do-while
• for
• foreach
while Loop
The while statement will loops through a block of code as long as the condition
specified in the while statement evaluate to true.
while(condition){
// Code to be executed
}
do…while Loop
With a do-while loop the block of code executed once, and then the condition is
evaluated, if the condition is true, the statement is repeated as long as the specified
condition evaluated to is true.
do{
// Code to be executed
}while(condition);
UNIT - 4 PHP 26
PHP Loops
for Loop
The for loop repeats a block of code as long as a certain condition is met. It is
typically used to execute a block of code for certain number of times.
foreach Loop
The foreach loop is used to iterate over arrays.
foreach($array as $value){
// Code to be executed
}
UNIT - 4 PHP 27
PHP Arrays
Arrays are complex variables that allow us to store more than one value or a
group of values under a single variable name.
$salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" => 500);
echo "Salary of mohammad is ". $salaries['mohammad']
Multidimensional Arrays
The multidimensional array is an array in which each element can also be an array
and each element in the sub-array can be an array or further contain array within
itself and so on. $contacts = array(
array(
"name" => "Peter Parker",
"email" => "[email protected]",
),
array(
"name" => "Clark Kent",
"email" => "[email protected]",
);
echo "Peter Parker's Email-id is: " .
$contacts[0]["email"];
# [email protected]
29
UNIT - 4 PHP
PHP Functions
Advantages of using functions:
function functionName() {
code to be executed;
}
<?php
function writeMsg() {
echo "Hello world!";
}
To call the function, just write its name followed by brackets ():
writeMsg(); // call the function
UNIT - 4 PHP 30
PHP Functions
Functions with Parameters
• You can specify parameters when you define your function to accept input
values at run time.
• The parameters work like placeholder variables within a function; they're
replaced at run time by the values (known as argument) provided to the
function at the time of invocation.
function myFunc($oneParameter, $anotherParameter){
// Code to be executed
}
Functions with Optional Parameters and Default Values
You can also create functions with optional parameters — just insert the parameter
name, followed by an equals (=) sign, followed by a default value
function customFont($font, $size=1.5){
echo "<p style=\"font-family: $font; font-size: {$size}em;\">Hello,
world!</p>";
}
customFont("Arial", 2);
customFont("Times", 3);
customFont("Courier");
UNIT - 4 PHP 31
PHP Functions
Returning Values from a Function
A function can return a value back to the script that called the function using the
return statement. The value may be of any type, including arrays and objects.
A function can not return multiple values. However, you can obtain similar results
by returning an array
UNIT - 4 PHP 32
PHP Functions
Passing Arguments to a Function by Reference
• In PHP there are two ways you can pass arguments to a function: by value
and by reference.
• By default, function arguments are passed by value so that if the value of the
argument within the function is changed, it does not get affected outside of
the function.
• To allow a function to modify its arguments, they must be passed by
reference.
• Passing an argument by reference is done by prepending an ampersand (&) to
the argument name in the function definition
function selfMultiply(&$number){
$number *= $number;
return $number;
}
UNIT - 4 PHP 33
PHP Functions
Understanding the Variable Scope
• you can declare the variables anywhere in a PHP script.
• The location of the declaration determines the extent of a variable's visibility
within the PHP program i.e. where the variable can be used or accessed. This
accessibility is known as variable scope.
• By default, variables declared within a function are local and they cannot be
viewed or manipulated from outside of that function
UNIT - 4 PHP 34
PHP Cookies
What is a Cookie
A cookie is a small text file that lets you store a small amount of data (nearly
4KB) on the user's computer. They are typically used to keeping track of
information such as username that the site can retrieve to personalize the page
when user visit the website next time
The setcookie() function is used to set a cookie in PHP. Make sure you call the
setcookie() function before any output generated by your script otherwise cookie
will not set
setcookie(name, value, expire, path, domain, secure);
UNIT - 4 PHP 35
PHP Cookies
Accessing Cookies Values
The PHP $_COOKIE superglobal variable is used to retrieve a cookie value. It
typically an associative array that contains a list of all the cookies values sent by
the browser in the current request, keyed by cookie name. The individual cookie
value can be accessed using standard array notation
echo $_COOKIE["username"];
it's a good practice to check whether a cookie is set or not before accessing its
value. To do this you can use the PHP isset() function
if(isset($_COOKIE["username"])){
echo "Hi " . $_COOKIE["username"];
} else{
echo "Welcome Guest!";
}
Removing 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
setcookie("username", "", time()-3600);
UNIT - 4 PHP 36
PHP Sessions
• Although you can store data using cookies but it has some security issues.
Since cookies are stored on user's computer it is possible for an attacker to
easily modify a cookie content to insert potentially harmful data in your
application that might break your application.
• Also every time the browser requests a URL to the server, all the cookie data
for a website is automatically sent to the server within the request. It means if
you have stored 5 cookies on user's system, each having 4KB in size, the
browser needs to upload 20KB of data each time the user views a page, which
can affect your site's performance.
• You can solve both of these issues by using the PHP session.
• A PHP session stores data on the server rather than user's computer.
• In a session based environment, every user is identified through a unique
number called session identifier or SID.
• This unique session ID is used to link each user with their own
information on the server like emails, posts, etc.
UNIT - 4 PHP 37
PHP Sessions
Starting a PHP Session
Before you can store any information in session variables, you must first start up
the session. To begin a new session, simply call the PHP session_start() function.
It will create a new session and generate a unique session ID for the user.
session_start();
The session_start() function first checks to see if a session already exists by
looking for the presence of a session ID. If it finds one, i.e. if the session is already
started, it sets up the session variables and if doesn't, it starts a new session by
creating a new session ID.
Storing and Accessing Session Data
You can store all your session data as key-value pairs in the $_SESSION[]
superglobal array. The stored data can be accessed during lifetime of a session.
Consider the following script, which creates a new session and registers two
session variables.
session_start();
// Storing session data
$_SESSION["firstname"] = "Peter";
$_SESSION["lastname"] = "Parker";
echo 'Hi, ' . $_SESSION["firstname"] . ' ' . $_SESSION["lastname"];
UNIT - 4 PHP 38
MYSQL DATABASE
• It is open-source database software, which is supported by Oracle Company.
• It is fast, scalable, and easy to use database management system in comparison
with Microsoft SQL Server and Oracle Database.
• It is developed, marketed, and supported by MySQL AB, a Swedish company,
and written in C programming language and C++ programming language.
• The hostname parameter specify the host name (e.g. localhost), or IP address of
the MySQL server,
• whereas the username and password parameters specifies the credentials to
access MySQL server,
• The database parameter, if provided will specify the default MySQL database
to be used when performing queries.
UNIT - 4 PHP 39
Inserting Data into a MySQL Database Table
• The mysqli_query() function to insert data in table
connection : required
query : required
resultmode : optional
mysqli_fetch_row(result)
mysqli_fetch_array(result,resulttype)
UNIT - 4 PHP 40
AJAX
• AJAX stands for Asynchronous Javascript And XML.It is a technique for
better, faster and more interactive Web Applications with the help and Java
Script
• Synchronous Model : A Synchronous request blocks the client until operation
completes.
• Asynchronous Model : An Asynchronous request does not block the client
operation, at that time user can perform another operation also.
AJAX Benefits
• Reduce the server traffic in both side request. Also reducing the time
consuming on both side response.
• AJAX is much responsive.
• AJAX make asynchronous calls to a web server. This means client browsers
are avoid waiting for all data arrive before start the rendering.
• Form are common element in web page. Validation should be instant and
properly, AJAX gives you all of that, and more.
• No require to completely reload page again. AJAX is improve the speed and
performance. Fetching data from database and storing data into database
perform background without reloading page.
UNIT - 4 PHP 41
HOW AJAX WORKS?
UNIT - 4 PHP 42
AJAX
• User sends a request from the UI and a javascript call goes to
XMLHttpRequest object.
• HTTP Request is sent to the server by XMLHttpRequest object.
• Server interacts with the database using JSP, PHP, Servlet, ASP.net etc.
• Data is retrieved.
• Server sends XML data or JSON data to the XMLHttpRequest callback
function.
• HTML and CSS data is displayed on the browser.
Processing steps
To write an AJAX based application a programmer should follow the below steps
1. Create an XMLHttpRequest
It provides a set of properties and methods that are used to send httprequest and to
retrieve data from the server.
2. Specify handels
We must specify a function to be called when the http response from the server
comes back. We call this function as response handler. This function will receive
information returned by the server, extract the data and perform a specific task.
UNIT - 4 PHP 43
AJAX
Processing steps
3. AJAX readystate property
The process of communicating with the server for sending HttpRequest to getting
a response involves 5 states.
Property Description
UNIT - 4 PHP 44
AJAX
• Sending a request consists of two steps
1. Open a connection
2. Sending an HttpRequest.
open(method,URL)
open(method,URL,boolean)
Sending an HttpRequest.:
Once the TCP connection is established We can send the HttpRequest through the
server with this connection using send() method.
void send()
Retrieving Information :
We can retrieve the server’s response by using responseText or responseXML
properties. The response may be a simple string or a complete XML.
UNIT - 4 PHP 45
UNIT-5 PERL 1
• Perl is the Practical Extraction and Report Language
• Perl is a general-purpose programming language originally developed
for text manipulation and now used for a wide range of tasks including
system administration, web development, network programming, GUI
development, and more.
• Perl was created by Larry Wall.
• Perl is a stable, cross platform programming language.
• Perl is a portable, command line driven, interpreted
Programming/scripting language.
• It is used for mission critical projects in the public and private sectors.
• Perl is Open Source software, licensed under the GNU General
Public License(GPL).
UNIT-5 PERL 2
Perl Features
• It has a very simple Object-oriented programming syntax.
• It is easily extendible as it supports 25,000 open source modules.
• It supports Unicode.
• It includes powerful tools to process text to make it compatible with mark-up
languages like HTML, XML.
• It supports third party database including Oracle, MySQL and many others.
• It is embeddable in other systems such as web servers and database servers.
• It is open source software licensed under GNU.
• Many frameworks are written in Perl.
• It can handle encrypted web data including e-commerce transactions.
• It is a cross platform language.
• It offers a regular expression engine which is able to transform any type of
text. UNIT-5 PERL 3
Perl Syntax
• A Perl program consists of a sequence of declarations and statements, which
run from the top to the bottom.
• Loops, subroutines, and other control structures allow you to jump around
within the code.
• Every simple statement must end with a semicolon (;).
• Perl is case-sensitive.
First Perl Program
Interactive Mode Programming
• You can use Perl interpreter with -e option at command line, which lets you
execute Perl statements from the command line.
UNIT-5 PERL 4
Perl Variables
Variables are the reserved memory locations to store values. This means that
when you create a variable you reserve some space in memory.
$integer = 200;
$negative = -300;
$floating = 200.340;
UNIT-5 PERL 5
Perl Variables
Variables are the reserved memory locations to store values. This means that
when you create a variable you reserve some space in memory.
String Scalars
$var = "This is string scalar!";
$quote = 'I m inside single quote - $var'; UNIT-5 PERL 6
Perl Arrays
An array is a variable that stores an ordered list of scalar values. Array variables
are preceded by an "at" (@) sign.
Array Creation
Array variables are prefixed with the @ sign and are populated using either
parentheses or the qw operator.
print $array[0];
Perl returns element referred to by a negative index from the end of the array.
print $array[-1];
UNIT-5 PERL 7
Perl Arrays
Sequential Number Arrays
Perl offers a shortcut for sequential numbers and letters. Rather than typing out
each element
@var_10 = (1..10);
@var_20 = (10..20);
@var_abc = (a..z);
Array Size
The size of an array can be determined using the scalar context on the array - the
returned value will be the number of elements in the array −
$count = @days;
%capitals = (
"India" => "New Delhi",
"South Korea" => "Seoul",
"USA" => "Washington, D.C.",
"Australia" => "Canberra"
);
print"$capitals{'India'}\n";
print"$capitals{'South Korea'}\n";
print"$capitals{'USA'}\n";
print"$capitals{'Australia'}\n";
UNIT-5 PERL 9
Perl Hashes
Add a new element
To add a new element to hash, you use a new key-pair value.
$langs{'Italy'} = 'Italian';
delete $langs{'China'};
UNIT-5 PERL 10
Perl Operators
Perl language supports many operator types but following is a list of most
frequently used operators:
•Arithmetic Operators
•Relational Operators
•Logical Operators
•Assignment Operators
•Bitwise Operators
UNIT-5 PERL 11
if statement
An if statement consists of a Boolean expression followed by one or
more statements.
if...else statement
An if statement can be followed by an optional else statement.
if...elsif...else statement
An if statement can be followed by an optional elsif statement and then
by an optional else statement.
UNIT-5 PERL 12
unless statement
An unless statement consists of a Boolean expression followed by one
or more statements. If the boolean expression evaluates to false, then the
block of code inside the unless statement will be executed
unless...else statement
An unless statement can be followed by an optional else statement.
unless...elsif..else statement
An unless statement can be followed by an optional elsif statement and
then by an optional else statement.
switch statement
With latest versions of Perl, We can make use of switch statement
which allows a simple way of comparing a variable value against various
conditions.
UNIT-5 PERL 13
Control Structures
A loop statement allows us to execute a statement or group of statements multiple times.
Perl programming language provides following four types of loops to handle looping
requirements
while
Repeats a statement or group of statements while a given condition is
true. It tests the condition before executing the loop body.
do..while
Like a while statement, except that it tests the condition at the end of the
loop body
for
Execute a sequence of statements multiple times and abbreviates the code
that manages the loop variable.
foreach
The foreach loop iterates over a normal list value and sets the variable
VAR to be each element of the list in turn.
UNIT-5 PERL 14
Control Structures
A loop statement allows us to execute a statement or group of statements
multiple times. Perl programming language provides following four types
of loops to handle looping requirements
until
Repeats a statement or group of statements until a given condition becomes true. It tests the
condition before executing the loop body.
nested loops
We can use one or more loop inside any another while, for or do..while
loop.
next
next operator in Perl skips the current loop execution and transfers the
iterator to the value specified by the next.
last
The last keyword is a loop-control statement that immediately causes the
current iteration of a loop to become the last. No further statements are
executed, and the loop ends.
UNIT-5 PERL 15
Perl Functions/Subroutines
A Perl subroutine or function is a group of statements that together perform a
task. We can divide up the code into separate subroutines. Perl uses the terms
subroutine, method and function interchangeably.
You define functions with the sub keyword.
A function can be placed anywhere in your Perl source code file.
functionname();functioname
functionname();
UNIT-5 PERL 16
Example
# Function definition
sub Hello
{
print "Hello, World!\n";
}
# Function call
Hello();
sub Average
{
# get total number of arguments passed.
$n = @_;
$sum = 0;
foreach $item (@_)
{
$sum += $item;
}
$average = $sum / $n;
return $average;
}
# Function call
$num = Average(10, 20, 30);
print "Average for the given numbers : $num\n";
UNIT-5 PERL 18
Perl I/O
Standard I/O
In Perl, the file handles STDIN, STDOUT, and STDERR stand for the standard
input (from keyboard), standard output (to screen), and standard error output (to
screen, no buffering) respectively. The notation
<input-source> is handy to read lines from an input source.
For example,
$line = <STDIN>; /* or simply $line = <> */
Reads one line from standard input. Repeated execution of this statement will let
you read line by line. The value of $line has the line termination character at the
end.
A handy function to remove any line terminator is the Perl built-in function
chomp:
$str = chomp($line);
UNIT-5 PERL 19
File I/O
Opening and Closing Files
There are following two functions with multiple forms which can be used to open any new
or existing file in Perl.
Here FILEHANDLE is the file handle returned by open function and EXPR is the
expression having file name and mode of opening the file.
Open Function
Following is the syntax to open file.txt in read-only mode. Here less than < sign
indicates that file has to be opened in read-only mode.
open(IN, "<file.txt");
Here IN is the file handle which will be used to read the file. Here is the example which
will open a file and will print its content over the screen.
UNIT-5 PERL 20
creating or writing mode.
Here greater than ( > ) sign indicates that file has to be opened in writing mode
If we want to open a file for reading and writing, we can put a plus sign (+)
before the > or < characters.
For example, to open a file for updating without truncating it:
We can open a file in append mode. In this mode writing point will be set to the
end of the file.
A double >> opens the file for appending, placing the file pointer at the end, so
that we can immediately start appending information.
UNIT-5 PERL 21
Following is the table which gives possible values of different modes
Close Function
To close a filehandle, and therefore disassociate the file handle from the corresponding file,
we use the close
function. This flushes the file handle’s buffers and closes the system's file descriptor.
UNIT-5 PERL 22
seek
This function moves to a specified position in a file.
You can move relative to
seek FILEHANDLE,POSITION,WHENCE
the beginning of the file (WHENCE = 0),
the current position (WHENCE = 1),
or the end of the file (WHENCE = 2).
This function is mainly used with fixed length records to randomly access specific records of
the file.
tell
Returns the current position in bytes for FILEHANDLE
tell(FILEHANDLE)
UNIT-5 PERL 23
PERL – CGI
Common Gateway Interface (CGI)
The Common Gateway Interface (CGI) provides the middleware between
WWW servers and external databases and information sources. The World
Wide Web Consortium (W3C) defined the Common Gateway Interface (CGI)
and also defined how a program interacts with a Hyper Text Transfer Protocol
(HTTP) server. The Web server typically passes the form information to a
small application program that processes the data and may send back a
confirmation message. This process or convention for passing data back and
forth between the server and the application is called the common gateway
interface (CGI).
Features of CGI:
It is a very well defined and supported standard.
CGI scripts are generally written in either Perl, C, or maybe just a simple
shell script.
CGI is a technology that interfaces with HTML.
CGI is the best method to create a counter because it is currently the
quickest
CGI standard is generally the most compatible with today’s browsers
UNIT-5 PERL 24
PERL – CGI
Advantages of CGI:
The advanced tasks are currently a lot easier to perform in CGI than in Java.
It is always easier to use the code already written than to write your own.
CGI specifies that the programs can be written in any language, and on any
platform, as long as they conform to the specification.
CGI-based counters and CGI code to perform simple tasks are available in
plenty.
Disadvantages of CGI:
There are some disadvantages of CGI which are given below:
In Common Gateway Interface each page load incurs overhead by having to
load the programs into memory.
Generally, data cannot be easily cached in memory between page loads.
There is a huge existing code base, much of it in Perl.
CGI uses up a lot of processing time.
UNIT-5 PERL 25
PERL – CGI
UNIT-5 PERL 26
CGI ARCHITECTURE
UNIT-5 PERL 27
Web Server Support & Configuration
Before you proceed with CGI Programming, make sure that your Web Server
supports CGI and it is configured to handle CGI Programs. All the CGI
Programs be executed by the HTTP server are kept in a pre-configured
directory. This directory is called CGI Directory and by convention it is named
as /cgi-bin. By convention PERL CGI files will have extention as .cgi.
Output :
Hello Word! This is my first CGI program
UNIT-5 PERL 28
Web Server Support & Configuration
Before you proceed with CGI Programming, make sure that your Web Server
supports CGI and it is configured to handle CGI Programs. All the CGI
Programs be executed by the HTTP server are kept in a pre-configured
directory. This directory is called CGI Directory and by convention it is named
as /cgi-bin. By convention PERL CGI files will have extention as .cgi.
Output :
Hello Word! This is my first CGI program
UNIT-5 PERL 29
CGI Environment Variables
All the CGI program will have access to the following environment
variables. These variables play an important role while writing any CGI
program.
CONTENT_TYPE
The data type of the content. Used when the client is sending attached content to the
server. For example file upload etc.
CONTENT_LENGTH
2 The length of the query information. It's available only for POST requests.
HTTP_COOKIE
Return the set cookies in the form of key & value pair.
HTTP_USER_AGENT
The User-Agent request-header field contains information about the user agent
originating the request. Its name of the web browser.
PATH_INFO
The path for the CGI script.
QUERY_STRING
The URL-encoded information that is sent with GET method request.
REMOTE_ADDR
The IP address of the remote host making the request. This can be useful for logging or
for authentication purpose.
UNIT-5 PERL 30
REMOTE_HOST
The fully qualified name of the host making the request. If this information is not
available then REMOTE_ADDR can be used to get IR address.
REQUEST_METHOD
The method used to make the request. The most common methods are GET and POST.
SCRIPT_FILENAME
The full path to the CGI script.
SCRIPT_NAME
The name of the CGI script.
SERVER_NAME
The server's hostname or IP Address.
SERVER_SOFTWARE
The name and version of the software the server is running.
UNIT-5 PERL 31
Pattern Matching or Regular Expressions in Perl
A regular expression is a string of characters that defines the pattern or patterns
you are viewing.
The syntax of regular expressions in Perl is very similar to what you will find
within other regular expression. Supporting programs, such as sed, grep, and
awk.
UNIT-5 PERL 32
The following are some simple matching examples involving the string $line:
If the pattern contains / then it is convenient to use a leading m which allows you to use any non-
alphanumeric character as the pattern delimiter:
Pattern Meaning
\n A newline
\t A tab
\w Any alphanumeric (word) character, same as [a-zA-Z0-9_]
\W Any non-word character, same as [^a-zA-Z0-9_]
\d Any digit. The same as [0-9]
\D Any non-digit. The same as [^0-9]
\s Any whitespace character: space, \t, \n, etc
\S Any non-whitespace character
UNIT-5 PERL 33
The Perl relational operators =~ (match) and !~ (non-match) are used for pattern matching. In Perl,
patterns are specified as extended regular expressions. Patterns are given inside /'s (the pattern delimiter).
Symbol
Meaning
/ / Represents a pattern
^At beginning of the string
$At the end of the string
I ignore case
G global search
UNIT-5 PERL 34
UNIT-6 RUBY 1
Ruby is "A Programmer's Best Friend".
Ruby is an object-oriented programming language. It was created in 1993 by
Yukihiro Matsumoto of Japan. Matsumoto is also known as ―Matz in the Ruby
community.
Features of ruby:
• Ruby is an open-source and is freely available on the Web, but it is
subject to a license.
• Ruby is a general-purpose, interpreted programming language.
• Ruby is an object-oriented programming language.
• Ruby is a server-side scripting language similar to Python and PERL.
• Ruby can be embedded into Hypertext Markup Language (HTML).
• Ruby is very much scalable and big programs written in Ruby are easily
maintainable.
• Ruby can be used for developing Internet and intranet applications.
• Ruby can be installed in Windows and POSIX environments.
• Ruby support many GUI tools such as Tcl/Tk, GTK, and OpenGL.
• Ruby can easily be connected to DB2, MySQL, Oracle, and Sybase.
• Ruby has a rich set of built-in functions, which can be used directly into
Ruby scripts.
UNIT-6 RUBY 2
Variables
Ruby variables are locations which hold data to be used in the programs. Each variable has
a different name. These variable names are based on some naming conventions. Unlike
other programming languages, there is no need to declare a variable in Ruby. A prefix is
needed to indicate it.
• Local variables
• Class variables
• Instance variables
• Global variables
Local Variables:
• A local variable name always starts with a lowercase letter(a-z) or underscore (_).
These variables are local to the code construct in which they are declared.
• A local variable is only accessible within the block of its initialization. Local variables
are not available outside the method. There is no need to initialize the local variables.
Example:
age = 10 _Age = 20
UNIT-6 RUBY 3
Class Variables:
• A class variable name starts with @@ sign. They need to be initialized before
use.
• A class variable belongs to the whole class and can be accessible from
anywhere inside the class. If the value will be changed at one instance, it will
be changed at every instance.
• A class variable is shared by all the descendents of the class. An uninitialized
class variable will result in an error.
class States
@@no_of_states=0
def initialize(name)
@states_name=name
@@no_of_states += 1
end
end
UNIT-6 RUBY 4
Instance Variables:
• An instance variable name always starts with a @ sign. They are similar to
Class variables but their values are local to specific instances of an object.
• Instance variables are available across methods for any specified instance or
object i.e. instance variables can change from object to object. There is no
need to initialize the instance variables and uninitialized instance variable
always contains a nil value.
Example:
class Customer
def initialize(id, name, addr)
# Instance Variables
@cust_id = id
@cust_name = name
@cust_addr = addr
end
end
UNIT-6 RUBY 5
Global Variables
• A global variable name always starts with $. Class variables are not available
across classes. If you want to have a single variable, which is available across
classes, you need to define a global variable.
• Its scope is global, means it can be accessed from anywhere in a program. By
default, an uninitialized global variable has a nil value and its use can cause
the programs to be cryptic and complex.
Example:
# global variable
$global_variable = 10
class Class1
def print_global
puts "Global variable in Class1 is #$global_variable"
end
end
UNIT-6 RUBY 6
SIMPLE I/O
All the I/O methods are derived from the class IO.
The class IO provides all the basic methods, such as read, write, gets, puts,
readline, getc, and print.
UNIT-6 RUBY 7
The putc Statement
Unlike the puts statement, which outputs the entire string onto the screen,
the putc statement can be used to output one character at a time.
The print statement is similar to the puts statement. The only difference is that
the puts statement goes to the next line after printing the contents, whereas with
the print statement the cursor is positioned on the same line.
UNIT-6 RUBY 8
Ruby – Operators
Operators are a symbol which is used to perform different operations.
Types of operators:
• Arithmetic operator : +, - , * , / , %, **
• Assignment operator : =, += , -= , *= , /= , %=, **=
• Comparison operator : < , > , <= , >= , == , !=
• Logical operator : &&, ||, !
• Bitwise operator : & , | , << , >> , ^ , ~
• Ternary operator : ?:
• Range operator : .. , …
UNIT-6 RUBY 9
Ruby Control Statements
• if statement
• if-else statement
• if-else-if (elsif) statement
if statement
Ruby if statement tests the condition. The if block statement is executed if
condition is true.
if (condition)
//code to be executed
end
a = gets.chomp.to_i
if a >= 18
puts "You are eligible to vote."
end
UNIT-6 RUBY 10
Ruby Control Statements
if -- else
Ruby if else statement tests the condition. The if block statement is executed if
condition is true otherwise else block statement is executed.
if(condition)
//code if condition is true
else
//code if condition is false
end
a = gets.chomp.to_i
if a >= 18
puts "You are eligible to vote."
else
puts "You are not eligible to vote."
end
UNIT-6 RUBY 11
if else if (elsif)
Ruby if else if statement tests the condition. The if block statement is executed if
condition is true otherwise else block statement is executed.
if(condition1)
//code to be executed if condition1is true
elsif (condition2)
//code to be executed if condition2 is true
else (condition3)
//code to be executed if condition3 is true
end
a = gets.chomp.to_i
if a > 0
puts “Positive:;
elsif a < 0
puts “Negative”;
else
puts “ZERO”;
UNIT-6 RUBY 12
Ruby while Loop
The Ruby while loop is used to iterate a program several times. If the number of
iterations is not fixed for a program, while loop is used.
Ruby while loop executes a condition while a condition is true. Once the
condition becomes false, while loop stops its execution.
UNIT-6 RUBY 13
do -- loop
The Ruby do while loop iterates a part of program several times. It is quite
similar to a while loop with the only difference that loop will execute at least
once.
loop do
#code to be executed
break if booleanExpression
end
loop do
puts "Checking for answer"
answer = gets.chomp
if answer != '5'
break
end
end
UNIT-6 RUBY 14
Until Loop
The Ruby until loop runs until the given condition evaluates to true. It exits the
loop when condition becomes true. It is just opposite of the while loop which runs
until the given condition evaluates to false.
The until loop allows you to write code which is more readable and logical.
until conditional
code
end
i=1
until i == 10
print i*10, "\n"
i += 1
end
UNIT-6 RUBY 15
Ruby for Loop
Ruby for loop iterates over a specific range of numbers. Hence, for loop is used if
a program has fixed number of iterations.
Ruby for loop will execute once for each element in expression.
a = gets.chomp.to_i
for i in 1..a do
puts i
end
UNIT-6 RUBY 16
Break Statement
The Ruby break statement is used to terminate a loop. It is mostly used in while
loop where value is printed till the condition is true, then break statement
terminates the loop.
break
i=1
while true
if i*5 >= 25
break
end
puts i*5
i += 1
end
UNIT-6 RUBY 17
Next Statement
The Ruby next statement is used to skip loop's next iteration. Once the next
statement is executed, no further iteration will be performed.
next
for i in 5...11
if i == 7 then
next
end
puts i
end
UNIT-6 RUBY 18
Ruby Arrays
Ruby arrays are ordered collections of objects. They can hold objects like integer, number,
hash, string, symbol or any other array.
Its indexing starts with 0. The negative index starts with -1 from the end of the array. For
example, -1 indicates last element of the array and 0 indicates first element of the array.
at method
To access a particular element, at method can also be used.
UNIT-6 RUBY 20
Adding Items to Array
Ruby array elements can be added in different ways.
• push or <<
• unshift
• insert
push or <<
Using push or <<, items can be added at the end of an array.
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
puts days.push("Today")
puts days << ("Tomorrow")
unshift
Using unshift, a new element can be added at the beginning of an array.
days = ["Fri", "Sat", "Sun"]
puts days.unshift("Today")
insert
Using insert, a new element can be added at any position in an array. Here, first we
need to mention the index number at which we want to position the element.
days = ["Fri", "Sat", "Sun"]
puts days.insert(2, "Thursday")
UNIT-6 RUBY 21
Removing Items from Array
Ruby array elements can be removed in different ways.
• pop
• shift
• delete
• uniq
pop
Using pop, items can be removed from the end of an array. It returns the removed item.
shift
Using shift, items can be removed from the start of an array. It returns the removed item.
delete
Using delete, items can be removed from anywhere in an array. It returns the removed item.
uniq
Using uniq, duplicate elements can be removed from an array. It returns the remaining array.
UNIT-6 RUBY 22
Ruby Hashes
A Ruby hash is a collection of unique keys and their values. They are similar to
arrays but array use integer as an index and hash use any object type. They are
also called associative arrays, dictionaries or maps.
If a hash is accessed with a key that does not exist, the method will return nil.
name = {"key1" => "value1", "key2" => "value2", "key3" => "value3"...}
OR
name = {key1: 'value1', key2: 'value2', key3: 'value3'...}
To fetch a hash value, write the required key within [] square bracket.
color = {
"Rose" => "red",
"Lily" => "purple",
}
puts color['Rose']
UNIT-6 RUBY 23
Ruby Hashes Methods
has_key?
The has_key? method allows you to check if a hash contains a specific key. It
returns a boolean value.
name_and_age.has_key?("Steve")
select
The select method allows you to pass a block and will return any key-value pairs
that evaluate to true when ran through the block.
fetch
The fetch method allows you to pass a given key and it will return the value for that
key if it exists. You can also specify an option for return if that key is not present.
UNIT-6 RUBY 24
Ruby Hashes Methods
to_a
The to_a method returns an array version of your hash when called. Let's see it in
action. It doesn't modify the hash permanently though.
name_and_age.to_a;
UNIT-6 RUBY 25
Ruby - Methods
Ruby methods are very similar to functions in any other programming language.
Ruby methods are used to bundle one or more repeatable statements into a single
unit.
Method names should begin with a lowercase letter. If you begin a method name
with an uppercase letter, Ruby might think that it is a constant and hence can
parse the call incorrectly.
Whenever you call the simple method, you write only the method name as
follows −
method_name
method_name 25, 30
UNIT-6 RUBY 26
Default Arguments
def test
i = 100
j = 200
k = 300
return i, j, k
end
var = test
puts var
UNIT-6 RUBY 27
Variable Number of Parameters
UNIT-6 RUBY 28
Ruby - Iterators
Iterators are nothing but methods supported by collections. Objects that store a
group of data members are called collections. In Ruby, arrays and hashes can be
termed collections.
Ruby each Iterator
The each iterator returns all the elements of an array or a hash.
collection.each do |variable|
code
end
ary = [1,2,3,4,5]
ary.each do |i|
puts i
end
x.times do |variable|
code...
end
5.times do |n|
puts n
end
x.upto(y) do |variable|
code
end
1.upto(5) do |n|
puts n
end
UNIT-6 RUBY 30
Ruby - Classes and Objects
A class definition starts with the keyword class followed by the class name and is
delimited with an end.
class Box
code
End
UNIT-6 RUBY 31
Define Ruby Objects
A class provides the blueprints for objects, so basically an object is created from a
class. We declare objects of a class using new keyword.
box1 = Box.new
box2 = Box.new
class Box
def initialize(w,h)
@width, @height = w, h
end
end
UNIT-6 RUBY 32
The accessor & setter Methods
To make the variables available from outside the class, they must be defined within
accessor methods, these accessor methods are also known as a getter methods
class Box
# constructor method
def initialize(w,h)
@width, @height = w, h
end
# accessor methods
def printWidth
@width
end
def printHeight
@height
end
end
# create an object
box = Box.new(10, 20)
# use accessor methods
x = box.printWidth()
y = box.printHeight()
puts "Width of the box is : #{x}"
puts "Height of the box is : #{y}"
UNIT-6 RUBY 33
Similar to accessor methods, which are used to access the value of the variables,
Ruby provides a way to set the values of those variables from outside of the class
using setter methods.
class Box
def initialize(w,h)
@width, @height = w, h
end
# accessor or getter methods
def getWidth
@width
end
def getHeight
@height
end
# setter methods
def setWidth=(value)
@width = value
end
def setHeight=(value)
@height = value
end
End
UNIT-6 RUBY 34
# create an object
box = Box.new(10, 20)
UNIT-6 RUBY 35
Access Control
Ruby gives you three levels of protection at instance methods level, which
may be public, private, or protected.
Ruby does not apply any access control over instance and class variables.
Public Methods − Public methods can be called by anyone. Methods are public
by default except for initialize, which is always private.
UNIT-6 RUBY 36
Inheriatnce
UNIT-6 RUBY 37
Method Overriding
In method overriding, subclass and superclass contain the same method’s
name, but performing different tasks or we can say that one method overrides
another method.
If superclass contains a method and subclass also contain same method name
then subclass method will get executed.
super
A super method is defined by super keyword. Whenever you want to call parent
class method of the same name so you can simply write super or super().
Freezing Objects
The freeze method in Object allows us to turning an object into a constant.
Any object can be frozen by invoking Object.freeze.
A frozen object may not be modified: you can't change its instance variables.
box.freeze
box
box = Box.new(10,
= Bo x.new(10, 20)20)
box.freeze
UNIT-6 RUBY 38
RUBY – Regular Expressions
UNIT-6 RUBY 39
=∽ and #match operators
=∽
If a match is found, the operator returns index of first match otherwise nil.
#match
UNIT-6 RUBY 40