Professional Documents
Culture Documents
Excellence
Computer Science Department
Web Technology Handout
Chapter One
Wide Area Networks (WAN):- these types of networks cover a very wide range of geographical distance. It is
collection of LAN.
b. What is Internet?
The Internet is “The Network of Networks”. It is a global system of interconnected computer networks that use
the standard Internet protocol suite (TCP/IP) to serve billions of users worldwide.
Internet is just a large number of computers connected together in such a way that communication between
them is both reliable and fast. It also uses to communicate and to share information, even to build relation ships
and communities. It's a culture that has grown within a virtual space, and that has permeated many aspects of
our everyday lives.
Now days, the Internet has become an industry in its own respect. Currently, the Internet, as a “network of
networks”, consists of many computers, called servers or hosts, which are linked by communication lines.
These hosts are located in different part of the world and connect millions of people as of now. The
administrators of these hosts may make information or software stored on them publically available, so that
others can view, download or use the data. Figure1 can clearly depict the growth of the Internet in terms of
growth in host/ server computers.
Another important thing that has contributed for growth of Internet is ownership. The Internet has backbone:
servers and Internet Service Providers (ISP) are owned by private as well government organizations.
The Internet has, in a short space of time, become fundamental to the global economy. More than a billion
people worldwide use it, both at work and in their social lives. Over the past three decades it has grown from
an experimental research network and now underpins a range of new economic activities: E-commerce, E-
business as well as activities and infrastructures that support our economies. In addition, Internet has
revolutionized the entertainment, education, and other spheres of business.
Hence, internet used for the following applications:-
o Communication through email , Chatting
o News groups
o Files transfer
o Documents, data(multimedia )sharing etc
o Electronic main (e-mail)
o File Transfer Protocol (FTP)
o Remote login: telnet, etc.
o World Wide Web
Internet connects ( almost anywhere in the world) for:-
-Exchanges information
-Acts as Global link between regional networks
-Allows unrestricted access
The Internet was the result of some visionary thinking by people in the early 1960s that saw great potential
value in allowing computers to share information on research and development in scientific and military fields.
J.C.R. Licklider of MIT (Massachusetts Institute of Technology), first proposed a global network of
computers in 1962, and moved over to the Defense Advanced Research Projects Agency (DARPA) in late
1962 to head the work to develop it. Leonard Kleinrock of MIT and later UCLA (University of California, Los
Angeles) developed the theory of packet switching, which was to form the basis of Internet connections.
Lawrence Roberts of MIT connected a Massachusetts computer with a California computer in 1965 over dial-
up telephone lines. It showed the feasibility of wide area networking, but also showed that the telephone line's
circuit switching was inadequate. Kleinrock's packet switching theory was confirmed. Roberts moved over to
DARPA in 1966 and developed his plan for ARPANET (Advanced Research Projects Agency\1Network).
These visionaries and many more left unnamed here are the real founders of the Internet.
The term "internet" was adopted as an abbreviation of the term internetworking and the two terms were used
interchangeably.
Internet: An Illustration
Generally, the functionalities of the Internet in many business areas is manifested through its services listed
below:
World Wide Web (WWW), Usenet (News Group),
Electronic mail, Internet Chat,
File Transfer Search Services
Discussion Groups
It is a global interactive, dynamic, cross platform, graphical hypertext information system that runs on the
Internet. It is also known as the web, www or w3. WWW allows to combine text, a video, graphics, and even
animation to make a document viewed easily and WWW is a set of web sites that uses to go for information.
Hence, WWW provides services that can be accessed from any computer connected to internet. It is the subset
of the internet.
The Web consists of many millions of internet-connected computers, each with information on them that their
owner has decided to share. These documents can be formed of anything from plain text to multimedia or even
3D objects. These computers, called servers, deliver this information over the Internet to client computers
(such as PC at office or home) using a protocol. The protocol just provides a mechanism that allows a client to
request a document, and a server to send that document.
As the web has become more and more popular, its capabilities have increased to include such things as
graphics, animations, scripts and even complete computer programs, all embedded into the pages of the
documents. Essentially, the web is the easiest to use from the entire internet toolkit: this is partly why it has
become so popular. Various mechanisms allow the viewer to move around (navigate) the document easily.
The web has become the most predominant of the new digital media, and has provided the mechanism for
many new forms of publishing. There are many reasons why this is so;
As the accessing of information stored on computers has become more widely accepted and used, the number
of methods, and hence the number of computer applications needed, has multiplied.
The web provides a way of integrating these methods and applications, using a common interface to allow easy
access to any information stored on any computer.
The language of the web, was specifically designed to be easy to learn, and was based around the concept of
marking text functionally, to ensure a wide authorship. As it has grown, the web has moved away from this
concept, becoming more complex and more graphical than originally envisioned. Though, the core functions
still lie beneath all the complexity, and allow more or less anyone to write their own web pages quickly and
easily, with a minimal set of software tools.
One of the most powerful features of the web is the ability to link documents together using hyperlinks. On
clicking a hyperlink (usually underlined), the browser tries to access the linked document, providing an almost
instantaneous cross-referencing system. This creates a non-linear form of text, known as hypertext. Web
pages can also contain multimedia content that can also be hyperlinked, termed hypermedia.
6|Page Lecture note
Productivity improvement and center of excellence
The goal of a web server is to serve information to anyone who requests it; the web pages stored on the server
are made publically available. It's possible to restrict access to certain parts of the Internet, or to those who
have usernames and passwords, but it's not usual: most web sites are open for all to read their contents. The use
of the web as a public space to provoke discussion or to provide otherwise difficult-to-publish information has
been instrumental in its popularity.
With the rise of commerce on the Web, and the recognition of the market value that certain types of
information can command, parts of the Web have been locked away, hidden behind corporate intranets and
firewalls, sites with passwords, and subscription services. A high proportion of this Deep or Invisible Web is
hidden from view, whether from you and I, or from search engines. Estimates of the size of this deep Web
vary, but most agree that it is many times the size of the Surface Web, i.e. the web that is open and accessible
to the public.
The backbone of the web is the network of web servers across the world. These are really just computers that
have a particular type of software running on them: software: web browser, which knows how to speak the
protocol and knows which information stored on the computer, should be made accessible through the web. It's
possible to turn almost any computer into a web server by downloading and installing server software
(Example: Apache)
The web browser is also particularly clever in the way it displays what it retrieves. Web pages are written in a
certain language, and the browser knows how to display these correctly, whether you have a huge flat screen or
a tiny screen on a handheld device or phone. The language the page has been built gives the browser hints on
how to display things, and the browser decides the final layout itself.
W3C (World Wide Web Consortium) makes the rules and standards for the web. W3C standards define
an Open Web Platform for application development that has the unprecedented
Web standards are not fixed sets of rules, but are a constantly evolving set of finalized technical
specifications of web technologies. Web standards are developed by standards organizations—
groups of interested and often competing parties chartered with the task of standardization—not
technologies developed and declared to be a standard by a single individual or company.
1.4.1. HTML
HTML stands for Hyper Text Markup Language, which is the most widely used language on Web to develop web
pages. In HTML, all web browsers interpret it in exactly the same way. It is a language that uses to develop/
display webpage. The original definition of HTML was written in a language called SGML (Standard
Generalized Markup Language), designed to allow computers to read language definitions easily. If a web page
is written in such a way that it conforms to the SGML definition, then it should be readable by all browsers
conforming to that definition.
The next generation of HTML, called XHTML, is defined in a cut down version of SGML called XML
(eXtensible Markup Language). XHTML is stricter in its definition of tags (has strict syntax rules), but it is
much more flexible, in that it is much easier for computers to interpret.
One of the reasons that the web is so widely used is that the standardization of HTML has allowed many
developers to produce browser software, for many types of computer.
Html use browser for web displaying. The browser does not display the HTML tags, but uses them to
interpret the content of the page. HTML describes the structure of a website semantically along with
cues for presentation, making it a markup language rather than a programming language.
HTML elements form the building blocks of all websites. HTML allows images and objects to be embedded
and can be used to create interactive forms. It provides a means to create structured documents by denoting
structural semantics for text such as headings, paragraphs, lists, links, quotes and other items. It can
embed scripts written in languages such as JavaScript which affect the behavior of HTML web pages.
When a computer reads any kind of document, it must follow a strict pattern or syntax, and the stricter this is,
the easier the computer finds the interpretation, even though we as humans may find it difficult to write so
accurately. Tools such as Dreamweaver and dedicated XML editors make writing this stricter form of HTML
much easier.
1.4.2. Web Browser:- is special software such as Netscape, Mosaic or Internet Explorer. These browsers
allow a user to view Web pages delivered from a client server (Web Site) situated at a particular URL
on the World Wide Web. It uses to locate and download documents.
Uses for :-
Compression decompression
Handles multimedia
Manages plug-ins
Interprets scripts
Maintain cache, history
Manipulate cookies
1.4.3. Web Page: - is a single document written in HTML that includes the text of the document, its structure,
any links to other documents and graphic images and other media. It is a single page that the browser
views at a time. It may include the text of the document, its structure, any links to other documents and
graphic images and other media. There are the following types of web pages:
i. Static Webpage: this type of webpage is not changed before being displayed in a web browser. Static web
pages are designed using HTML tags. A static site is a website that is written entirely using HTML.
Each web page is a separate document and there are no databases or external files that are drawn upon.
This means that the only way to edit this type of website is to go into each page and edit the HTML. So,
it would be done using a web page editor such as FrontPage or Dreamweaver, or by paying web
developer to make updates.
1.4.3.1. Dynamic web pages: in such types of webpage, the original web pages are changed before it is
displayed in web browsers.
In dynamic web page structure, we cannot see the contents which made the web page
Dynamic pages are designed using script programs such as PHP and C-Sharpe.
Dynamic pages can be turned in to static pages .
A dynamic website is written using more complex code — such as PHP or ASP — and has a greater degree of
functionality. For instance, many dynamic websites can be controlled by a content management system. This
means that it is possible for potentially be able to make updates without needing any knowledge of HTML or
any website software. The owners will not be required to pay Web professionals every time a change in the
Web content is needed. A dynamic website design will become necessary for online databases, e-businesses
and online shopping sites. A dynamic web design page has the facility to change content by a program.
1.4.4. Homepage: - is a Hypertext document a server will serve as default. It is the first page of the website. It
uses as index of the site.
HTML
10 | P a g e Lecture note
Productivity improvement and center of excellence
1.4.5. Internet Protocol:- In networking and Communications, the formal specification that defines the
procedures to be followed when transmitting and receiving data. Protocols define the format, timing,
sequence and error checking used on the network. It is a language of computer.
The Internet protocols are the world’s most popular open-system (nonproprietary) protocol suite because they
can be used to communicate across any set of interconnected networks and are equally well suited for LAN
and WAN communications. The Internet protocols consist of a suite of communication protocols, of which the
two best known are the Transmission Control Protocol (TCP) and the Internet Protocol (IP). The Internet
protocol suite not only includes lower layer protocols (such as TCP and IP), but it also specifies common
applications such as electronic mail, terminal emulation, and file transfer. In addition, it includes different
application level protocols like Small Mail Transfer Protocol (SMTP), Network News Transfer Protocol
(NNTP), File Transfer Protocol (FTP), Dynamic Host Configuration Protocol (DHCP) and Hypertext Transfer
Protocol (HTTP)
HTTP- Hypertext Transfer Protocol is the stateless protocol used for data transfer within WWW. The
Hypertext Transfer Protocol (HTTP) is an application level protocol for distributed, collaborative, hypermedia
information systems. HTTP has been in use by the World Wide Web global information initiative since 1990.
The HTTP protocol is a request/response protocol. A client sends a request to the server in the form of a
request method, URI, and protocol version, followed by possible body content over a connection with a server.
The server responds with a status line, including the message’s protocol version and a success or error code.
Most HTTP communication is initiated by a user agent and consists of a request to be applied to a resource on
some origin server. In the simplest case, this may be accomplished via a single connection (v) between the user
agent (UA) and the origin server (O).
WWW Elements
Servers and Clients URL
Web browsers DNS
Web Sites
Web documents / Web Pages
11 | P a g e Lecture note
Productivity improvement and center of excellence
i. Server
Provides information and services to clients
It is a place where web documents are stored
Hardware + Software ( Web Server)
Web Server - is an application that processes the request sent by client. E.g. apache
Clients: Use the services provided by the Server.
ii. Web Browser
Fetch:-
URL:- is the term used to identify an internet resource, and can be specified in a single line
of text.
URN:- is the term used to identify an internet resource, without the use of a scheme, and can
be specified in a single line of text.
URI:- is used by a browser to identify a single document, and it too can be specified in a
single line of text.
URL- is (tell about) HOW and WHERE. It is location based. Written as:-
<protols>://<host>[:<port>][<path>] [?<query>]
Client/Server describes the relationship between two computer programs where one program the
client makes request from another program the sever which fulfils the request. Each web server
has a daemon that continually waits for requests to come in from Web clients and their users. In
client/server architectures, Remote Procedure Calls (RPCs) or standard query language (SQL)
statements are typically used to communicate between the client and server.
Client Server Architectures are commonly compose of various tiers.
1. A Single-Tier:
A tier is a physical structuring mechanism for the system infrastructure. Single tier architecture
has both the system interface or client/server database management server is coupled© and
database highly coupled. Any change made to one program requires changes being made to all
others. It lacks flexibility.
2. Two-Tier Architecture:
Two-tier architecture is used to describe client/server systems where the client requests resources
and the server responds directly to the request, using its own resources. This means that the
server does not call on another application in order to provide part of the service
With two tier client/server architectures the user system interface or Client or presentation layer
is usually located in the user's desktop environment and the database management services are
usually in a server that is a more powerful machine that services many clients. Processing
management is split between the user system interface environment and the database
management server environment.
3. Three-tier architecture
3. The data server, which provides the application server with the data it require three-tier‘
is a client-server architecture in which the user interface, functional process logic
("business rules"), computer data storage and data access are developed and maintained
as independent modules, most often on separate platforms.
4. N- Tier Architecture
N-tier application architecture provides a model for developers to create a flexible and
reusable application. By breaking up an application into tiers, developers only have to
modify or add a specific layer, rather than have to rewrite the entire application over. There
should be a presentation tier, a business or data access tier, and a data tier. The most
widespread use of "multi-tier architecture" refers to three-tier architecture.
Http request:
A request message from a client to a server includes, within the first line of that message, the
method to be applied to the resource, the identifier of the resource, and the protocol version
in use.
Request-Line:- The request-line begins with a method token, followed by the request-URI and
the protocol version (http versions), and ending with CRLF.
4|Page Lecture Note
Productivity improvement and center of excellence
Response line: it includes HTTP version information, Status code and status description. The
response from the server contains 3 digit number/ IP address and description of the number.
If a client and server interact several times, each interaction is a unique encounter with no
knowledge of any previous interactions. This is in contrast to a continuous based protocol such
as telnet.
When a client and server interact using the telnet protocol, a connection is maintained between
and the client and server during the entire interaction and state information is maintained and
passed back and forth between client and server. There are a number of devices which have been
used to overcome this problem: for example, in the case of HTTP, one solution is to embed a
COOKIE on a client machine which holds data to keep track of the interactions.
One advantage of Http’s stateless protocol is that once a document has been downloaded, the
document can be read or used off-line at the client’s convenience without maintaining a
connection to the server.
However, this also has a drawback, in that each time the client wants another document from the
server, a connection must be re-established with the server – a process that occasionally takes
longer than downloading the document itself.
Internet programming includes broad variety of technologies spanning such diverse areas such as
protocols for communication.
The word HTML, stands for Hypertext Markup Language, is the predominant markup
language for web pages. A markup language is a set of markup tags, and HTML uses markup
tags to describe web pages. HTML is written in the form of HTML elements consisting of
HTML tags surrounded by angle brackets (e.g. <html>) within the web page content.
HTML was invented in 1990 by a scientist called Tim Berners-Lee. An HTML file is a text file
containing small markup tags. The markup tags tell the Web browser how to display the page.
HTML tags usually come in pairs like <b> and </b>, but not always. The first tag in a pair is
the start tag, the second tag is the end tag; which are refer for opening tags and closing tags. But,
it doesn’t mean all tags has both open and close tags because there are empty tags (self close tag)
which has only open tag like <br> and <img> tags.
HTML elements form the building blocks of all websites, it allows images and objects to be
embedded and can be used to create interactive forms. It provides a means to create structured
documents by denoting structural semantics for text such as headings, paragraphs, lists, links,
quotes and other items. It can also embed scripts in languages such as JavaScript which affect the
behavior of HTML webpage. HTML can also be used to include Cascading Style Sheets (CSS)
to define the appearance and layout of text.
HTML tags are used to create the web page, and interpreted by any browser types such as
internet explorer, nets cap, Mozilla, safari, etc. The purposes of these web browser types are to
read HTML documents and display them as web pages. The browser does not display the HTML
tags, but uses the tags to interpret the content of the page.
A very good quality associated with all the browsers is that they would not give any error if we
have not put any HTML tag or attribute properly. They will just ignore the wrong tag or attribute
and will apply only correct tags and attributes before displaying the result.
HTML document can be created using a simple text editor like Notepad, WordPad, Notepade++,
or any other text editors.
For example: using Notepad, we can edit HTML program as follows:-:-
Step 1: Open Notepad.
Step 2: Writing the HTML tags in the new Notepad file, then save using a file extension of html
Step 3: Double-click on the HTML file to run
HTML is a language, which makes it possible to present information (e.g. scientific research) on
the Internet.
Note that:- To see the HTML code of a page on the Internet, simply click "View" in the top
menu of the browser and choose "Source, or right click on html file iconopen withnotepad
2.2. HTML Tags and Blocks/ skeleton of HTML codes
HTML Tags
HTML elements are defined using HTML tags
HTML tags are used to mark-up HTML elements
HTML tags are surrounded by the two characters < and >, i.e using angle brackets
The text between the start and end tags is the element content
There are two types of tags:-
Empty tag:- type of html tag which has not any close tags such as <br> and <img>
tags
Container tag:- tag types which have both open and close tags. For instance <body>
and <html> tags.
6|Page Lecture Note
Productivity improvement and center of excellence
N.B:- HTML tags are not case sensitive; <b> means the same as <B>. both upper and
lowercases of tags in html interpreted similarly. But, the latest web standards follow lowercase
tags.
The following code is block of html code that uses to display blank page. This is because there is
no any document or text between body tags.
<html>
<head>
<title>Page title here </title>
</head>
<body>
</body>
</html>
HTML, HEAD, TITLE and BODY Tags are html main tags that are used to construct an html
skeleton / structure. To develop the webpage, it is possible to use different webpage editors/
plain text editor or any advance editor. Whatever the use of the text editor the structure of basic
HTML code/ tags is similar as shown above.
The total code is divided into two parts and both the parts are kept inside <html> tags. The first part is
header part, which is optional, and the second one is body part which is the main part.
Any html code should start with <html> and should end with </html>. The header part should starts with
<head> and ends with </head>, after this the body part starts with <body> and ends with </body> tag.
Inside the body tag, we keep all our content which we want to display to webpage users. Whatever we
place in this part of the page will be displayed by the browser to the web users.
The text or tags what goes inside the head tags will not be displayed in the browser window. Inside this
tag we keep all the meta keyword tags used for search engines. One of the important tags is title tage and
written as <title> title of the webpage</title> tag. Title tags are displayed at the top left side of the
browser window. Title tags are also important for our search engine point of view. It is possible to keep
most important keywords inside the title tag.
Html developers place web contents in between open and close body tags to display for visitors. So go on
filling this place with content to show to the web user. Hence, t he purpose of the <body> tag is to
define the HTML element that contains the body of the HTML document.
The font of documents in between body tags could be changes using Font tags. It u ses to change
the way text looks by changing its font, size, colour and emphasis. Written as <font> </font>. It
use different key words such as size, color, face, etc.
HTML common Elements and their Descriptions:- There are some Common html tags because
some text may be more important than others.
Tag Description
<h1> to <h6> Defines header 1 to header 6
<p> Defines a paragraph
<br> Inserts a single line break
<hr> Defines a horizontal rule
<!--> Defines a comment
HTML HEADING:- HTML provides six headers, called header elements, for specifying
the relative importance of information
– <h1> … </h1>, <h2> … </h2> to <h6> … </h6>
It is assumed the text in <h1> is more important than that in <h2>, <h2> is more important than
<h3> and so on so forth based on the size of the text by taking the more important is bigger text.
See the following example:-
<html>
<head>
7|Page Lecture Note
Productivity improvement and center of excellence
As seen above Starting with <h1> which displays the most prominent font size and ending with
<h6> the least prominent font size.
PARAGRAPH TAG:- Paragraphs are defined with the <p> tag to separate paragraphs
i.e adds an extra blank line before and after a paragraph tags
Example: <p> This is the start of a very small paragraph. p>
It may use attributes like align (values can be left, right, center, justify) .
for example; <p align="left">This is a paragraph</p>
LINE BREAK TAG:-
The <br> tag forces a line break wherever we place it. It uses to start new line.
The <br> tag is an empty tag. It has no closing tag.
COMMENT IN HTML:-
Used to enter a comment in HTML source code.
The comment will be ignored by the browser.
Horizontal tag:-
Used to delimit the parts by display a horizontal line.
Written as <hr>…………..</hr>
In html, horizontal tag may have attribute with not value as exceptional. But other attributes
should have values. Example:- <hr noshade> or <hr noshade="noshade" /> indicates that there should
be no shading applied to this horizontal rule. Example:- write an html code that enables to display the
following sample webpage:
Character tags like <strong> and <em> produce the same physical display as <b> and <i> but are
more uniformly supported across different browsers.
2.3. HTML ATTRIBUTES
An attribute is used to define the characteristics of an element and is placed inside the element's
opening tag. The <tag> tells the browser to do something, while the attribute tells the browser
9|Page Lecture Note
Productivity improvement and center of excellence
how to do it. For instance, if we add the bgcolor attribute, we can tell the browser that the
background color of the page should be blue, like this: <body bgcolor="blue">.
All attributes are made up of two parts: a name and a value.
The name is the property that wanted to be set. For example, the <font> element in the
example carries an attribute whose name is face , which we can use to indicate which
typeface one want the text to appear in.
The value is what we want the value of the property to be. The first example was
supposed to use the Arial typeface, so the value of the face attribute is Arial
<font face="arial" color="green">
Many HTML tags have a unique set of their own attributes. Right now we want to focus on a set
of generic attributes that can be used with just about every HTML Tag in existence.
Core Attributes: The four core attributes that can be used on the majority of HTML elements
(although not all)
are: id, title, class and style.
I. The id Attribute: The id attribute can be used to uniquely identify any element
within a page ( or style sheet ).
There are two primary reasons that we might want to use an id attribute on an element:
If an element carries an id attribute as a unique identifier it is possible to identify
just that element and its content.
If there are two elements of the same name within a Web page (or style sheet),
the id attribute uses to distinguish between elements that have the same name.
<p id="html">This para explains what is HTML</p>
<p id="css">This para explains what is Casecading Style Sheet</p>
II. Title Attributes:- The title attribute gives a suggested title for the element. They
syntax for the title attribute is similar as explained for id attribute. The behavior of
this attribute will depend upon the element that carries it, although it is often
displayed as a tooltip or while the element is loading.
<h4 title="Hello HTML!">Titled Heading Tag Example</h4>
III. The class Attribute: The class attribute is used to associate an element with a style
sheet, and specifies the class of element. For example: class="className1
className2 className3"
IV. The style Attribute: The style attribute allows to specify CSS/ casecade style sheet,
we discussed in chapter 3, rules within the element. For example: <p style="font-
family:arial; color:#FF0000;">Some text...</p>
Note that:-
Attributes provide additional information about an element
Attributes are always specified in the start tag
Attributes and attribute values are case-insensitive.
Attributes come in name/value pairs like: name="value“, but not always
Attribute values better be enclosed in double quotes.
Example:- From <body bgcolor=”green”> sample example, bgcolor is the name of attrbuite, green is the
value of the attribute.
V. Body attributes:- The <body> tag has two attributes where you can specify backgrounds.
The background can be a color or an image.
Bgcolor :- The bgcolor attribute specifies a background-color for an HTML page. The
value of this attribute can be a hexadecimal number, an RGB value, or a color name:
10 | P a g e Lecture Note
Productivity improvement and center of excellence
Tag Description
<b> Defines bold text
<big> Defines big text
<em> Defines emphasized text
<i> Defines italic text
<small> Defines small text
<strong> Defines strong text
<sub> Defines subscripted text
<sup> Defines superscripted text
<ins> Defines inserted text
<del> Defines deleted text
<s> Deprecated. Use <del> instead
<abbr> Defines an abbreviation
<acronym> Defines an acronym
<address> Defines an address element
<bdo> Defines the text direction
<q> Defines a short quotation
<cite> Defines a citation
<dfn> Defines a definition term
VI. Text direction attribute:- use <bdo dir=value>. It uses to demonstrate how to
change the text direction. The value of dir attribute can be rtl or ltr.
11 | P a g e Lecture Note
Productivity improvement and center of excellence
<html><body>
<p> If your browser supports bi-directional override (bdo), the next line will be written
from the right to the left (rtl):</p>
<bdo dir="rtl">Here is some Hebrew text</bdo>
</body>
</html>
VII. Quotations:- This example demonstrates how to handle quotations
<html>
<body>
<q> This is a long quotation</q>
<body>
</html>
VIII. Deleted and inserted text:- These are tags that are used to mark a text that is
deleted or inserted to a document. See the following example:
<html><body>
<p>a dozen is <del>twenty</del>
<ins>twelve</ins> pieces</p>
<p> Most browsers will overstrike deleted text and underline inserted text.</p>
<p>Some older browsers will display deleted or inserted text as plain text.</p>
</body></html>
IX. Abbreviations and acronyms:- These tags use for handle an abbreviation or an
acronym as written below.
<html><body>
<abbr title="United Nations">UN</abbr><br>
<acronym title="World Wide Web">WWW</acronym>
</body></html>
X. HTML Character Entities:- Some characters like the < character, have a special
meaning in HTML, and therefore cannot be used in the text. To display a less than
sign (<) in HTML, we have to use a character entity.
A character entity has three parts: an ampersand (&), an entity name or a # and an
entity number, and finally a semicolon (;).
To display a less than sign in an HTML document we must write: < or <
Advantage of using a name: name is easier to remember.
Disadvantage: not all browsers support the newest entity names, while the support for
entity numbers is very good in almost all browsers.
Note That:- The entities are case sensitive
XI. Non-breaking Space :- The most common character entity in HTML is the non-
breaking space. Normally HTML will truncate spaces in the text. If we write 10
spaces in the text, HTML will remove 9 of them. To add spaces to text, use the
character entity. The following shows the description of lists of entity and
non-breaking spaces
12 | P a g e Lecture Note
Productivity improvement and center of excellence
The <a> tag is used to create an anchor or link to link from, the href attribute is used to tell the
address of the document or page we are linking to, and the words between the open and close of
the anchor tag will be displayed as a hyperlink. When we click on the displayed linker word(s),
the browser will jump to the actual documents, URL. As shown from above hyperlink syntax,
href: Means Hypertext REFerence. The href part is the attribute, with the location of the
other page as its value.
The href attribute specifies the destination of a link.
The href or the name attribute must be present in the <a> tag.
The href attribute is supported in all major browsers.
The name attribute is used to create a named anchor. When using named anchors we can create
links that can jump directly to a specific section on a page, instead of letting the user scroll
around to find what he/she is looking for. Unlike an anchor that uses href, a named anchor
13 | P a g e Lecture Note
Productivity improvement and center of excellence
doesn't change the appearance of the text (unless we set styles for that anchor) or indicate in any
way that there is anything special about the text. For example vlink and alink attributes.
To link directly to the top section, add a # sign and the name of the anchor to the end of a URL
as:-
In addition to href attribute, there are <a> tag attributes such as name and target attributes. An
attribute called TARGET has values like "_blank" | "_parent" | "_self" | "_top" | window name
TARGET:- Controls where the new document will be displayed when the user follows a link.
TARGET, the new document open in a new window, or if we are using frames, in another frame.
TARGET = "_blank"
o Used to opens the new document in a new window.
o < A HREF="newwindow.html" TARGET="_blank">a new window</A>
o This value does not require the use of any frames.
TARGET = "_parent"
o Used in the situation where a frameset file is nested inside another frameset file.
o A link in one of the inner frameset documents which uses "_parent" will load
the new document where the inner frameset file had been.
o For example, this anchor <A HREF="bigframe.html" TARGET="_parent"> bigframe
</A>
TARGET = "_self"
o "_self" puts the new document in the same window and frame as the current
document.
o "_self" works the same as if not used TARGET at all.
o For example <A HREF="selftarget.html" TARGET="_self">next</A> page
TARGET = "_top"
o "_top" loads the linked document in the topmost frame... that is, the new page fills
the entire window.
o For example,<A HREF="selftarget.html" TARGET="_top">top</A>
N.B:- We can create an image hyperlink as follows:-
<a href=“page1.html”>
<img src=“image.gif” />
</a>
2.5. HTML Images
In HTML, images are defined with the <img> tag, to display the image on a page/ webpage. We
use “src” attribute which stands for "source". The value of the src attribute is the URL of the
image we want to display. Syntax for defining an image is <img src="url" alt="some_text"/>
14 | P a g e Lecture Note
Productivity improvement and center of excellence
The required alt attribute specifies an alternate text for an image, if the image cannot be
displayed. The value of the alt attribute is an author-defined text: <img src="pulpit.jpg"
alt="Pulpit rock" width="304" height="228" >. The height and width attributes are used to
specify the height and width of an image.
Example:-
<html>
<body>
<h1 align="center">My First Web page</h1>
<p>Welcome to my first webpage.</p>
<p>By learning html, I'll be able to create web pages<br>
which I am of course.</p>
<!-- Who would have guessed how easy this would be -->
<p>
<img src="graphics/chef.gif" width="130" height="101" alt="Smiling Happy Chef"
align="center">
</p>
<p align="center">This is my Chef</p>
</body>
</html>
The most common options are:
SRC="FILENAME" - Specifies the SOURCE of the image; if the image file is in the same
directory as the source document, all that is needed is the filename itself. Note: Don't link to
another page for an image - copy the image to the filespace and link to it from there.
HEIGHT="NUMBER" - Specifies that the height of the image should be NUMBER pixels
WIDTH="NUMBER" - Specifies that the width of the image should be NUMBER pixels.
If no dimensions are specified for the image, the browser will insert the image exactly as is,
at the same size as developers would view it in a picture editor on computer. The picture will
load slightly faster if you specify the height and width so that the browser does not have to
determine it.
ALT="DESCRIPTION" - Specifies a description of the image. The ALT option for the
IMG tag is useful for those whose browsers cannot support in-line images, or have their
images turned off in their browsers; instead of seeing the image, they'll see the description of
the image that we gave them in the ALT tag.
BORDER="NUMBER" - Specifies the width of the image's border, in pixels.
Hspace and vspace also used to assign the horizontal and vertical spacing between images
Example:- An image tag could look like: <img src = "filename" height = "number" width =
"number" alt = "description" border = "number"> like <img vspace="10" hspace="30"
src="freenetlogo.gif" WIDTH="281" HEIGHT="108">
2.6. VIDEO/ Audio TAGS:-
To insert video, use a <video> tag and set its src attribute to a local or remote URL containing a
playable movie. The play black can be displayed using controls by including the “controls”
attribute, as well as set the dimensions of the movie to its natural size:-
<video src=http://htmlref.com/ch2/html_5.mp4 width="640" height="360"
controls>
<strong>HTML5 video element not supported</strong>
</video>
HTML’s audio element is quite similar to the video element. The element should support
common sound formats such as WAV files:
15 | P a g e Lecture Note
Productivity improvement and center of excellence
<frame src="frameb.htm">
<frame src="framec.htm">
</frameset></html>
Frames can divide the screen into separate windows. Each of these windows can contain an
HTML document. A file that specifies how the screen is divided into frames is called a frameset.
The content model says that the <frameset> tag contains one or more <frame> tags, which are
used to indicate the framed contents. A <frameset> tag also might contain a <noframes> tag,
whose contents will be displayed by browsers that do not support frames
There are few drawbacks of frames:-
Some browsers do not print well from framesets.
Some smaller devices cannot cope with frames, often because their screen is not big
enough to be divided up.
Some time the page will be displayed differently on different computers due to different
screen resolution.
The browser's back button might not work as the user hopes.
There are still few browsers who do not support frame technology.
If needed to make a homepage that uses frames, we should use the followings:
Make an HTML document with the frameset
Make the normal HTML documents that should be loaded into each of these frames.
When a frameset page is loaded, the browser automatically loads each of the pages associated
with the frames. Each HTML document is called a frame, and each frame is independent of the
others.
The frameset element holds two or more frame elements. Each frame element holds a separate
document. The frameset element states only HOW MANY columns or rows there will be in the
frameset and it uses <frameset> tag. The <frame> tag defines one particular window (frame)
within a frameset. In the example below we have a frameset with two columns. The first column
is set to 25% of the width of the browser window. The second column is set to 75% of the width
of the browser window. The document "framea.htm" is put into the first column, and the
document "frameb.htm" is put into the second column:
<frameset cols="25%,75%">
<frame src="framea.htm" />
<frame src="frameb.htm" />
</frameset>
Note:
The frameset column size can also be set in pixels (cols="200,500"), and one of the
columns can be set to use the remaining space, with an asterisk (cols="25%,*").
No use the body element together with the frameset element. However, if <noframes> tag
is added containing some text for browsers that do not support frames, it is possible to to
enclose the text in a body element.
Attributes of frame
Attribute Value Description
frameborder 0 or 1 Specifies whether or not to display a border around a frame
marginheight Pixels Specifies the top and bottom margins of a frame
marginwidth Pixels Specifies the left and right margins of a frame
17 | P a g e Lecture Note
Productivity improvement and center of excellence
Attributes of frameset
Attribute Value Description
cols Pixels, % or Specifies the number and size of columns in a frameset
*
rows Pixels, % or Specifies the number and size of rows in a frameset
*
Nested Frames
Framesets may be nested to any level. In the following example, the outer FRAMESET divides the
available space into three equal columns. The inner FRAMESET then divides the second area into two
rows of unequal height.
Example:1
<FRAMESET cols="33%, 33%, 34%">
<frame src=”one.html”>
<FRAMESET rows="40%, 50%">
<frame src=”two.html”>
<frame src=”three.html”>
</FRAMESET>
<frame src=”four.html”>
</FRAMESET>
Example 2:-
<HTML>
<HEAD>
<TITLE>A simple frameset document</TITLE>
</HEAD>
<FRAMESET cols="20%, 80%">
<FRAMESET rows="100, 200">
<FRAME src="contents_of_frame1.html">
<FRAME src="contents_of_frame2.gif">
</FRAMESET>
<FRAME src="contents_of_frame3.html">
<NOFRAMES>
<P>This frameset document contains:
<UL>
<LI><A href="contents_of_frame1.html">Some neat contents</A>
<LI><IMG src="contents_of_frame2.gif" alt="A neat image">
<LI><A href="contents_of_frame3.html">Some other neat contents</A>
</UL>
</NOFRAMES>
</FRAMESET>
</HTML>
Note: the more frames are nested; it will make it complicated hence difficult manageable.
NOFRAMES:-
The NOFRAMES element specifies content that should be displayed only by user agents that do not
support frames or are configured not to display frames. User agents that support frames must only display
the contents of a NOFRAMES declaration when configured not to display frames. User agents that do not
18 | P a g e Lecture Note
Productivity improvement and center of excellence
support frames must display the contents of NOFRAMES in any case. NOFRAMES may be used at the
end of the FRAMESET section of the document.
a <body> tag should be found for browsers that do not support frames. A visual representation of this idea is shown here:
Example1:- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"
"http://www.w3.org/TR/html4/frameset.dtd">
<HTML>
<HEAD>
<TITLE>A frameset document with NOFRAMES</TITLE>
</HEAD>
<FRAMESET cols="50%, 50%">
<FRAME src="main.html">
<FRAME src="table_of_contents.html">
<NOFRAMES>
<P>Here is the <A href="main-noframes.html">
non-frame based version of the document.</A>
</NOFRAMES>
</FRAMESET>
</HTML>
Example 2:-
Noframes compatibility
19 | P a g e Lecture Note
Productivity improvement and center of excellence
both allow to insert an HTML document in the middle of another, they may both be aligned with
surrounding text, etc.
The information to be inserted inline is designated by the src attribute of this element. The
contents of the IFRAME element, on the other hand, should only be displayed by user agents
that do not support frames or are configured not to display frames.
The <iframe> tag is not used within a <frameset> tag. Instead, it appears anywhere in the document. The
<iframe> tag defines a rectangular region within the document in which the browser displays a separate
document, including scrollbars and borders.
<body>
...other document content...
<iframe src="/html/menu.htm" width="75" height="200" align="right">
Your browser does not support inline frames. To view this
<a href="/html/menu.htm">document</a> correctly, you'll need
a copy of Internet Explorer or the latest Netscape Navigator.
</iframe>
...subsequent document content...
</body>
For user agents that support frames, the following example will place an inline frame surrounded
by a border in the middle of the text.
<IFRAME src="foo.html" width="400" height="500"
scrolling="auto" frameborder="1">
[Your user agent does not support frames or is currently configured
not to display frames. However, you may visit
<A href="foo.html">the related document.</A>]
</IFRAME>
2.8. HTML Tables
Tables are defined with the <table> tag. A table is divided into rows (with the <tr> tag), and each row is
divided into data cells (with the <td> tag). td stands for "table data," and holds the content of a data cell.
A <td> tag can contain text, links, images, lists, forms, other tables, etc. Header information in a table is
defined with the <th> tag. The text in a th element will be bold and centered.
Tags Description
<table> Defines a table
<th> Defines a table header
<tr> Defines a table row
<td> Defines a table cell
<caption> Defines a table caption
<colgroup> Defines groups of table columns
<col> Defines the attribute values for one or more columns in a table
Example:
<table border="1">
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td bgcolor=green>row 1, cell 1</td>
<td bgcolor=red>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
20 | P a g e Lecture Note
Productivity improvement and center of excellence
Attributes of table: the attributes of a table will be applied on the whole table element which include one
or more rows (<tr>), header cells (<th>) or data cells (<td>)
Attribute Value Description
align left
center Specifies the alignment of a table according to
right surrounding text
bgcolor rgb(x,x,x) Specifies the background color for a table
#xxxxxx
colorname
border Pixels Specifies the width of the borders around a table
cellpadding Pixels Specifies the space between the cell wall and the cell
content
cellspacing Pixels Specifies the space between cells
21 | P a g e Lecture Note
Productivity improvement and center of excellence
Attributes of rows and cells: this attributes will be applicable only to the header cell or the data cell if it
is used with <th> or <td> tag while it will affect the whole content of the row if it is used by the <tr> tag.
22 | P a g e Lecture Note
Productivity improvement and center of excellence
Nesting Tables
Tables may be nested to produce interesting effects, such as the following example: Because the
TABLE element must have an end tag, no particular tricks exist for nesting tables. we may
include a table within another table’s cell or another table’s row
Table nest example:
<TABLE border=”1” cellspacing=”2”
cellpadding=”2”>
<TR>
<TD colspan=”3”>A1
<TR>
<TD>B1
<TD>B2
<TD rowspan=”2”>B3
<TR>
<TD colspan=”2”>C1
</TABLE>
To add a title to a table, place the caption text between <caption> and </caption> tags just after
the <table> tag. The align="bottom" attribute in the <caption> can be added. Table tag may
have width attribute with value in persent or inch as <table width="75%">…</table> or
<table width="5.5in">...</table>
<html>
<body>
<TABLE border=”5” cellspacing=”2”
cellpadding=”5” bgcolor=red>
<caption>Ethiopian table</caption>
<tr>
<th colspan="3" align="center">Lifespan</th>
<th>top</th>
</tr>
<tr>
23 | P a g e Lecture Note
Productivity improvement and center of excellence
<td>Name
<td>Born
<td>hhhh
<td>Died
</tr>
<tr><td>25
<td>1900
<td>
<td>1971
</tr>
</table>
</body>
</html>
2.9. HTML Lists
It uses to list down sets of documents with sequence of numbers of bullets of combination of the
two. The followings are html List Tags
Tag Description
<ol> Defines an ordered list
<ul> Defines an unordered list
<li> Defines a list item
<dl> Defines a definition list
<dt> Defines a definition term
<dd> Defines a definition description
<dir> Deprecated. Use <ul> instead
<menu> Deprecated. Use <ul> instead
Order List:- An orderlist use <ol> tag type with attribute of “1”, “a”, “i” etc which are
grouped under number types.
<html>
<body>
<h4>Numbered list:</h4>
<ol type=A>
<li>Apples</li>
24 | P a g e Lecture Note
Productivity improvement and center of excellence
<li>Bananas</li>
<li>Lemons</li>
<li>Oranges</li> </ol>
Each list item starts with the <li> tag to lists down with sequences
Definition Lists :- A definition list is not a list of items. This is a list of terms and
explanation of the terms. A definition list starts with the <dl> tag. Each definition-list
term starts with the <dt> tag. Each definition-list definition starts with the <dd> tag.
<dl>
<dt>Coffee</dt>
<dd>Black hot drink</dd>
<dt>Milk</dt>
<dd>White cold drink</dd>
</dl>
Here is how it looks in a browser: Coffee Black hot drink Milk White cold drink Inside a
definition-list definition (the <dd> tag) you can put paragraphs, line breaks, images, links, other
2.10. HTML FORM
The <form> tag is used to create an HTML form for user input. A form can contain input
elements like text fields, checkboxes, radio-buttons, submit buttons and more. A form can also
contain select menus, textarea, fieldset, legend, and label elements.
HTML forms are used to pass data to a server. An HTML form is a section of a document
containing normal content, markup, special elements called controls (checkboxes, radio buttons,
menus, etc.), and labels on those controls. Users generally "complete" a form by modifying its
controls (entering text, selecting menu items, etc.), before submitting the form for further
processing (e.g., to a Web server, to a mail server, etc.). Forms are a vital tool for the webmaster
to receive information from the web server, such as: their name, email address, credit card, etc. A
form will take input from the viewer and depending on needs; we may store that data into a file,
place an order, gather user statistics, register the person to our web forum, or maybe subscribe
them to our weekly newsletter.
The <form> tag is used to create an HTML form:
<form>
input elements
</form>
25 | P a g e Lecture Note
Productivity improvement and center of excellence
The most important form element is the input element. The input element is used to select user
information. An input element can vary in many ways, depending on the type attribute. An input
element can be of type text field, checkbox, password, radio button, submit button, and more.
Elements inside a form are introduced by the <input> tag.
The <input> tag may use the following attributes as values:-
– type=“hidden” name=“variable name” value=“value that sends to the server”
– type =“text” name=“” value =“” size=“25”
– type =“submit” value =“”
– type =“reset” value =“”
– type =“checkbox” value =“” name=“”
Working with Text Fields and Passwords
Text Field
Declared as <input type="text" /> defines a one-line input field that a user can enter text into. See
example:-
<form>
First name: <input type="text" name="firstname" /><br />
Last name: <input type="text" name="lastname" />
</form>
The output will look as:
First name:
Last name:
Note: The form itself is not visible. Also note that the default width of a text field is 20
characters.
Password
Written as <input type="password" /> defines a password field. See example as
<form>
Password: <input type="password" name="pwd" />
</form>
The output looks as:
*********
Password:
Note: the characters entered in to the password field are masked.
26 | P a g e Lecture Note
Productivity improvement and center of excellence
</form>
Checkboxes
Check boxes allow for multiple items to be selected for a certain group of choices. The check
box's name and value attributes behave the same as a radio button.
Written as <input type="checkbox" /> defines a checkbox. Checkboxes let a user select ONE
or MORE options of a limited number of choices.
<form>
<input type="checkbox" name="vehicle" value="Bike" /> I have a bike<br />
<input type="checkbox" name="vehicle" value="Car" /> I have a car
</form>
Example:-
Selection lists
Drop down menus are created with the <select> and <option> tags. <select> is the list itself
and each <option> is an available choice for the user.
<select name="degree">
<option>Choose One</option>
<option>Some High School</option>
<option>High School Degree</option>
<option>Some College</option>
<option>Bachelor's Degree</option>
<option>Doctorate</option>
<input type="submit" value="Email Yourself">
</select>
Example 2:-
Favorite language:
<SELECT NAME="language">
<OPTION VALUE="c">C
27 | P a g e Lecture Note
Productivity improvement and center of excellence
<OPTION VALUE="c++">C++
<OPTION VALUE="java" SELECTED>Java
<OPTION VALUE="lisp">Lisp
<OPTION VALUE="perl">Perl
<OPTION VALUE="smalltalk">Smalltalk
</SELECT>
Example:-
<p>please comment the document what I sent before:-<br>
<textarea name=”selfdescribition” rows=”10” cols=”80” wrap=”wrap”>
</textarea>
</p>
Example:-
<html>
<body>
<textarea name=”abstract” rows=”100” cols=”170” wrap=”wrap”>
</textarea>
<input type="text" value="enteryour comment"/>
28 | P a g e Lecture Note
Productivity improvement and center of excellence
</body>
</html>
Example:-
<CENTER>
<P>
Enter some HTML:<BR>
<TEXTAREA NAME="HTML" ROWS=5 COLS=30>
Delete this text and replace
with some HTML to validate.
</TEXTAREA>
<CENTER>
Reset button
The reset buton clears the form and returns all the settings to their defalt values. The attribute
value is the text that will appear in the button
Written as <input type=”reset” value =”reset the form”/>
2.11. Linking HTML Forms with PHP Scripts
To create a link between PHP scripts and HTML forms, we need to use the functionalities of buttons, and
the attribute of the <form tag>, specifically “action” and “method”.
Buttons:
Submit buttons: When activated, a submit button submits a form. A form may contain more
than one submit button.
Reset buttons: When activated, a reset button resets all controls to their initial values.
<input type="submit" /> defines a submit button.
A submit button is used to send form data to a server. The data is sent to the page specified in the
form's action attribute (how to write scripts will be discussed in the coming chapters).
Action and method:
The file defined in the action attribute usually does something with the received input:
<form name="input" action="action.php" method="get">
Username: <input type="text" name="user" />
<input type="submit" value="Submit" />
Automating Processing: Info Forms and Emails
If we would like to provide our web site visitors with a simple way to contact us from our web
site, but really don't want to display our email address, this HTML form code may be what we're
looking for. We can create a simple form, as displayed below, to enable our visitors to send us
comments, questions, product support requests, or whatever we'd like:-
<form action=mailto:dummy1@yahoo.com, method="POST", enctype="text/plain">
Your Name: <input type="text" size="20" name="VisitorName"><br><br>
Your Comment: <textarea name="VisitorComment" rows="4" cols="20">
</textarea><br><br>
<input type="submit" value="Email This Form">
</form>
Example:-
<input type="hidden" name=“title" value="Feedback" />
<p><label>Name:
<input type= "text" name= "name" size="25" maxlength="30"/>
</label>
29 | P a g e Lecture Note
Productivity improvement and center of excellence
</p>
<input type= "submit" value="Submit your entries"/>
<input type= "reset" value="Clear Your Entries"/>
Example
2.12. Creating File upload
HTML Element: <INPUT TYPE="FILE" ...> (No End Tag). Attributes: NAME (required),
VALUE (ignored), SIZE, MAXLENGTH, ACCEPT, ONCHANGE, ONSELECT, ONFOCUS,
ONBLUR (nonstandard).
This element results in a filename textfield next to a Browse button. Users can enter a path
directly in the textfield or click on the button to bring up a file selection dialog that lets them
interactively choose the path to a file. When the form is submitted, the contents of the file are
transmitted as long as an ENCTYPE of multipart/form data was specified in the initial FORM
declaration.
For multipart data, you also need to specify POST as the method type. This element provides a
convenient way to make user-support pages, with which the user sends a description of a
problem along with any associated data or configuration files.
</FORM>
It uses to upload different files such as word and pdf formats
See the following example:-
<html>
<body>
<form method="post" action="cgi-bin/upload.cgi" enctype="multipart/form-data">
<p><strong> file upload area</strong></p>
<p>please select the file to upload:<br/>
<input type="file" name="title" size="50"/>
30 | P a g e Lecture Note
Productivity improvement and center of excellence
2.
<html>
<head>
<title>Personal INFO</title>
</head>
<body>
<form method="post" action=”a.php" > // assume you have a.php in the folder
First Name:<input type="text" size="12" maxlength="12" name="Fname"><br />
Last Name:<input type="text" size="12" maxlength="36" name="Lname"><br />
Gender:<br />
Male:<input type="radio" value="M" name="gender"><br />
Female:<input type="radio" value="F" name="gender"><br />
Please choose type of residence:<br />
Steak:<input type="checkbox" value="Steak" name="food"/><br />
Pizza:<input type="checkbox" value="Pizza" name="food"/><br />
Chicken:<input type="checkbox" value="Chicken" name="food"/><br />
<textarea rows="5" cols="20" name="quote" wrap="physical">Enter your
favorite quote!</textarea><br />
Select a Level of Education:<br />
<select name="education">
<option value="Jr.High">Jr.school</option>
<option value="HighSchool">HighSchool</option>
<option value="College">College</option>
<option value="College">university</option>
</select><br />
Select your favorite time of day:<br />
<select name="TofD">
<option value="Morning">Morning</option>
31 | P a g e Lecture Note
Productivity improvement and center of excellence
<option value="Day">Day</option>
<option value="Night">Night</option>
</select><br />
<input type="radio" name="likeit" value="Yes" checked="checked" /> Yes
<input type="radio" name="likeit" value="No" /> No
<input type="radio" name="likeit" value="Not sure" /> Not sure</p>
<select name="crew">
<option value="xebrax">Xebrax</option>
<option value="snertal">Snertal</option>
<option value="gosny">Gosny</option>
</select><br>
<input type="submit" value="submit" name="submit">
</form>
</body>
</html>
32 | P a g e Lecture Note
Productivity improvement and center of excellence
Chapter 3
Cascading Style Sheets
4.1 Introduction to CSS
CSS stands for Cascading Style Sheet, and it allows us to separate our web sites HTML content
from its style. As always we use HTML file to arrange the content, but all of the
presentation/formatting (fonts, colors, background, borders, text formatting, link effects & so
on...) are accomplished within a CSS.
CSS is a web page layout method that has been added to HTML to give web developers more
control over their design and content layout. Using CSS allows a designer to create a standard set
of commands (either embedded inside the web page or from an external page) that controls the
style of all subsequent pages.
CSS separates the layout and the styles of a web page. This is often difficult to comprehend for
web designers that are used to compiling their creative and HTML coding in a single web page
document. Styles such as fonts, font sizes, margins, can be specified in one place, and then the
Web pages feed off this one master list, with the styles cascading throughout the page or an
entire site.
Styles solve a common Problem. HTML tags were originally designed to define the content of a
document. They were supposed to say "This is a header", "This is a paragraph", "This is a table",
by using tags like <h1>, <p>, <table>, and so on. it became more and more difficult to create Web
sites where the content of HTML documents was clearly separated from the document's presentation
layout. The layout of the document was supposed to be taken care of by the browser, without
using any formatting tags.
Styles sheets define HOW HTML elements are to be displayed, just like the font tag and the
color attribute in HTML. Styles are normally saved in external .cssfiles. External style sheets
enable us to change the appearance and layout of all the pages in the Web, just by editing one
single CSS document.
CSS is a breakthrough in web design because it allows developers to control the style and layout
of multiple web pages all at once. As a web developer, it is possible to define a style for each
HTML element and apply it to as many web pages as we want. To make a global change, simply
change the style, and all elements in the Web are updated automatically.
Style sheets allow style information to be specified in many ways. Styles can be specified inside
a single HTML element, inside the <head> element of an HTML page, or in an external CSS
file. Even multiple external style sheets can be referenced inside a single HTML document.
33 | P a g e Lecture Note
Productivity improvement and center of excellence
font-family:arial;
}
4.4 Linking CSS to HTML
When a browser reads a style sheet, it will format the document according to it . Hence, it is possible to
link CSS with html in three different ways: embedded style, inline style, and external style.
Creating an Inline Style:-Inline styles have the structure like
<tag style=”property: value”>
Example:-<img src=a.jpg style=background-image:blue;>
Creating Internal Styles:-An internal style sheet should be used when a single document has a
unique style. An internal styles is definedwithin the <head></head> tags of each HTML file we
want to style with the CSS using the <style> tag, like this:
<head>
<title>Out first CSS Example</title>
<style type="text/css">
hr {color: sienna}
p {margin-left: 20px}
body {background-image: url("images/back40.gif"),{color=”blue”}}
h1,h2,h3,h4,h5,h6
{
color: green
}
</style>
</head>
<body>……</body></html>
With this method each HTML file contains the CSS code needed to style the page. Meaning that
any changes we want to make to one page, will have to be made to all. This method can be good
if we need to style only one page, or if we want different pages to have varying styles.
Creating an External Style Sheet:-. It is used when the style is applied to many pages. With an
external style sheet, we can change the look of an entire Web site by changing one file. Each
page must link to the style sheet using the <link> tag, which goes inside the head section:
<link rel=”stylesheet” type=”text/css” href=”filename.css”/>
Example:-<link rel=”stylesheet” type=”text/css” href=”D://main.css”/>
The browser will read the style definitions from the file filename.css, and format the document
according to it. An external style sheet can be written in any text editor. The file should not
contain any html tags. The style sheet should be saved with a .css extension. An example of a
style sheet file is shown below:
hr {color: sienna}
p {margin-left: 20px}
body {background-image: url("images/back40.gif")}
Example 1
35 | P a g e Lecture Note
Productivity improvement and center of excellence
<html><head>
<link rel= “stylesheet”
Type=”text/css” href=”ex1.css” />
</head>
<body>
<h1>This header is 36 pt</h1>
<h2>This header is blue</h2>
<p>This paragraph has a left margin of 50 pixels</p>
</body>
</html>
Example 2
<html><head><link rel=”stylesheet”
Type=”text/cssŗhref=”ex2.css” />
</head>
<body>
<h1>This is a header 1</h1><hr />
<p>We can see that the stylesheet formats the text</p>
<p><a href=”http://www.w3schools.com” target=”_blank”>This is a
link</a></p></body></html>
Multiple Style Sheets
If some properties have been set for the same selector in different style sheets, the values will be
inherited from the more specific style sheet. For example, an external style sheet has these
properties for the h3 selector:
h3
{ color: red;
text-align: left;
font-size: 8pt }
And an internal style sheet has these properties for the h3 selector:
h3
{ text-align: right;
font-size: 20pt }
If the page with the internal style sheet also links to the external style sheet the properties for h3
will be:
color: red;
text-align: right;
font-size: 20pt
The color is inherited from the external style sheet and the text-alignment and the font-size is
replaced by the internal style sheet.
36 | P a g e Lecture Note
Productivity improvement and center of excellence
The CSS background properties define the background effects of an element. We can style the
background of an element in one declaration with the background property.
background: #ffffffurl(path_to_image) top left no-repeat fixed;
Values:
attachment
color
image
position
repeat
Background Attachment
If we are using an image as a background, it is possible to set whether the background scrolls with the
page or is fixed when the user scrolls down the page with the background-attachment
propertybackground-attachment: value;
Values:
fixed
scroll
Background Color
we can specifically declare a color for the background of an element using the background-color property.
background-color: value;
examplebackground:yellow;
Values:
color name
hexadecimal number
RGB color code
transparent
Background Image
we can set an image for the background of an element using the background-image property.
background-image: url(path_to_image);
see the example bellow
background-image:url(“D:/a.jpg”)
Background Position
We can position an image used for the background of an element using the background-position
property.background-position: value;
Values:
top left center center bottom right
top center center right x-% y-%
top right bottom left x-pos y-pos
center left bottom center
Example:-
<html><head><style type="text/css">body
37 | P a g e Lecture Note
Productivity improvement and center of excellence
39 | P a g e Lecture Note
Productivity improvement and center of excellence
line through
blink
Examples:
<html>
<head>
<style type="text/css">h1 {text-decoration: overline}
h2 {text-decoration: line-through}h3 {text-decoration: underline}a {text-decoration:
none}
</style></head>
<body><h1>This is header 1</h1><h2>This is header 2</h2><h3>
This is header 3</h3><p><a href="http://www.w3schools.com/default.asp">
This is a link</a></p></body></html>
Text Indent
We can indent the first line of text in an (X)HTML element with the following:
text-indent: value;
Possible values are
length
percentage
Example:
<html>
<head>
<style type="text/css">p {text-indent: 1cm}
</style></head><body>
<p>This is some text in a paragraph This is some text in a paragraph This is some text
in a paragraph This is some text in a paragraph This is some text in a paragraph This is
some text in a paragraph </p>
</body></html>
This example demonstrates how to control the letters in a text.
<html>
<head>
<style type="text/css">
p.uppercase {text-transform: uppercase}
p.lowercase {text-transform: lowercase}
p.capitalize {text-transform: capitalize}
</style></head><body>
<p class="uppercase">This is some text in a paragraph</p><p
class="lowercase">This is some text in a paragraph</p>
<p class="capitalize">This is some text in a paragraph</p>
</body></html>
40 | P a g e Lecture Note
Productivity improvement and center of excellence
Example :-
<html>
<head>
<style type="text/css">p.small {line-height: 90%}p.big {line-height: 200%}
</style></head><body><p>This is a paragraph with a standard line-height. The default
line height in most browsers is about 110% to 120%. This is a paragraph with a standard
line-height.This is a paragraph with a standard line-height.
</p><p class="small">
This is a paragraph with a smaller line-height.This is a paragraph with a smaller line-
height. This is a paragraph with a smaller line-height.This is a paragraph with a smaller
line-height.
</p><p class="big">
This is a paragraph with a bigger line-height.This is a paragraph with a bigger line-height.
This is a paragraph with a bigger line-height.This is a paragraph with a bigger line-
height.</p></body></html>
Set the background-color of the text This example demonstrates how to set the background-color
of a part of the text.
<html>
<head>
<style type="text/css">span.highlight
{background-color:yellow}</style></head>
<body><p>
<span class="highlight">This is a text.</span> This is a text. This is a text. This is a text.
This is a text. This is a text. This is a text. This is a text. This is a text. <span
class="highlight">This is a text.</span></p></body></html>
4.7 Styling Fonts
Font:-The font property can set the style, weight, variant, size, line height and font:
font: italic bold normal small/1.4em Verdana, sans-serif;
<html>
<head>
<style type="text/css">h3 {font-family: times}p {font-family: courier}
p.sansserif {font-family: sans-serif}
</style></head> 109
<body><h3>This is header 3</h3><p>This is a paragraph</p><p class="sansserif">This
is a paragraph</p>
</body></html>
Font –Family:-To set what font will be displayed in an element with the font-family property,
there are 2 choices for values:
family-name
42 | P a g e Lecture Note
Productivity improvement and center of excellence
generic family
If we set a family name it is best to also add the generic family at the end. As this is a prioritized
list. So if the user does not have the specified font name it will use the same generic family.
font-family: Verdana, sans-serif;
Font Size:-In order to set the size of the text used in an element by using the font-size property.
font-size: value;
There are a lot of choices for values:
xx-large medium xx-small
x-large small length
larger smaller % (percent)
large x-small
Font Style:- Used to set the style of text in a element with the font-style property as :- font-style:
value;
Possible values are
normal
itailc
oblique
Font Variant:-used to set the variant of text within an element with the font-variant property:
font-variant: value;
Possible values are
normal
small-caps
Font Weight:- helps to control the weight of text in an element with the font-weight property:
font-weight: value;
Possible values are
lighter 300 700 bolder
normal 400 800
100 500 900
200 600 bold
Example:-
<html>
<head>
<style type="text/css">h3 {font-family: times}p {font-family: courier}
p.sansserif {font-family: sans-serif}h1 {font-size: 150%}h2 {font-size: 130%}
p {font-size: 100%}<style type="text/css">p.normal {font-variant: normal}
p.small {font-variant: small-caps}
</style></head>
<html><head>
</style></head>
43 | P a g e Lecture Note
Productivity improvement and center of excellence
Values
none decimal lower-alpha
disc decimal-leading-zero upper-alpha
circle lower-roman lower-greek
square upper-roman lower-latin
44 | P a g e Lecture Note
Productivity improvement and center of excellence
45 | P a g e Lecture Note
Productivity improvement and center of excellence
To control the space between the border and content in a table, use the padding property on td
and th elements:
td{
padding:15px;
}
Table Color
The color of the borders, and the text and background color of th elements can be specified:
table, td, th{
border:1px solid green;
}
th{
background-color:green;
color:white;
}
4.11 CSS Class and ID
CSS Class
Controlling the way all HTML elements look can be useful, but also limiting. It's excellent to be able to
change every paragraph, table cell or image with one line of CSS code, but sometimes we may want to
change only few paragraphs or images, not all of them. We can add CSS code through the style attribute
of each element, but for more elements that method gets too complicated.
For example, paragraph can be defined in CSS file as follows:
p{
font-size: small;
color: #333333
}
However, let’s say we want to change the word "sentence" in the paragraph formatted by the above CSS
to green bold text, while leaving the rest of the sentence untouched. This can be done by using class.
There are two types of classes – generic classes that can be applied to any element, and classes that can be
applied only to a certain type of HTML element. Their selector starts with a dot ("."), which states that it
is a class. We can name it anything as we want:
.important { background-color: #FFFFDE; }
.emphasis { font-family: Verdana; }
.boooring{ color: Gray; }
To apply a class to a certain HTML element, use its class attribute where we state the class name without
the dot.
<div class="emphasis">The big match today …</div>
<i class="boooring">This sentence looks boring</i>
We can also use classes which can be applied only to certain HTML elements. Selectors of these classes
start with the HTML element name, followed with the dot and the class name:
div.big{ font-weight: bold; font-size: 16pt; }
These classes can be applied only to a specified HTML element, in this case a DIV element.
46 | P a g e Lecture Note
Productivity improvement and center of excellence
CSS ID
IDs are similar to classes, except once a specific ID has been declared it cannot be used again within the
same (X)HTML file. The syntax of ID selectors is very similar to classes, but instead of a dot we must
use a hash sign (#).
The HTML content is:
<div id="container"> I was asleep, but my heart was awake. </div>
The CSS that formats the HTML content:
#container{
width: 80%;
padding: 20px;
margin: auto;
47 | P a g e Lecture Note
Productivity improvement and center of excellence
48 | P a g e Lecture Note
Productivity improvement and center of excellence
Border Color:-We can set the color of a border independently with the border-color property.
border-color: value;
Values:
color name
hexadecimal number
RGB color code
transparent
Border Style:-set the style of a border independently with the border-style property.
border-style: value;
Values:
dashed hidden ridge
dotted inset solid
double none
groove outset
Border Width:-helps to set the width of a border independently with the border-width property.
border-width: value;
Values:
Length
Thin
Medium
Thick
Or canset the elements for each borders side individually
Border Bottom:-helps to set the color, style and width of the bottom border around an element in one
declaration with the border-bottom property a shown below:-
border-bottom: 1px solid #333333;
Values:
color
style
width
49 | P a g e Lecture Note
Productivity improvement and center of excellence
Border Bottom Color:-used to set the color of the bottom border around an element with the border-
bottom-color property.
border-bottom-color: value;
wecan set the style of the bottom border around an element with the border-bottom-style property:
border-bottom-style: value;
Border Bottom Width:-Helps to set the width of the bottom border around an element with the border-
bottom-width property.
border-bottom-width: value;
Border Left
Used to set the color, style and width of the left border around an element with the border-left property.
border-left: 1px solid #333333;
Border Left Color:-It can set the color of the left border around an element with the border-left-color
property.border-left-color: value;
Border Left Style:-It could set the style
50 | P a g e Lecture Note
Productivity improvement and center of excellence
of the left border around an element with the border-left-style property.border-left-style: value;
Border Left Width:-This uses to set the width of the left border around an element with the border-left-
width property.border-left-width: value;
Border Right:-This css part uses to set the color, style and width of the right border around an element in
one declaration with the border-right property.border-right: 1px solid #333333;Values:colorstylewidth
Or we can set each value individually
4.14 CSS Margin
The margin clears an area around an element (outside the border). The margin does not have a
background color, and is completely transparent.
The top, right, bottom, and left margin can be changed independently using separate properties. A
shorthand margin property can also be used, to change all margins at once.
The top, right, bottom, and left padding can be changed independently using separate properties. A
shorthand padding property can also be used, to change all paddings at once.
Chapter 4
JavaScript Programming
4.1. Introduction
JavaScript is used in millions of Web pages to improve the design, validate forms,
detect browsers, and much more. JavaScript is the most popular scripting language
on the internet, and works in all major browsers, such as Internet Explorer, Firefox,
and Opera.
Scripting languages are usually interpreted rather than compiled. That means that a
software routine called an interpreter translate a program’s statements into machine
code, code understandable by a particular type of computer, before executing them
every time the program is run. Compiled languages, on the other hand, are
translated into machine code and stored for later execution. When the compiled
program is run, it executes immediately without further need of interpretation; it
was interpreted into machine code when it was compiled. Because programs
written in interpreted languages must be translated into machine code every time
they are run, they are typically slower than compiled programs. However, this does
not usually present a problem for the small applications for which scripting
languages are generally used.
Being interpreted does have its advantages. One is platform independence.
Because an interpreter performs the translation, we can write the program once and
run it on a variety of platforms. In the case of JavaScript, the interpreter is built
into Web browsers. Browsers are available for a variety of platforms and operating
systems. Another advantage is that scripting languages are often loosely typed and
more forgiving than compiled languages.
4.2. Purposes of Java script :-
JavaScript gives HTML designers a programming tool - JavaScript is a
scripting language with a very simple syntax!
<SCRIPT type=”text/JavaScript”>
//your script here
</SCRIPT>
As shown above, the attribute name called LANGUAGE & TYPE can be used
interchangeably. But, commonly we use type attribute.
Here are some tips to remember when writing JavaScript commands:
JavaScript code is case sensitive (e.g. age and Age are different variables)
White space between words and tabs are ignored
Line breaks are ignored except within a statement
JavaScript statements end with a semi colon (;) but not always
This is useful if we have a lot of code or we want to run it from several pages,
because any number of pages can call the same external JavaScript file. The
text file itself contains no HTML tags. It is called by the following tag:
<SCRIPT type = "JavaScript" SRC = " url of javascript file">
</SCRIPT>
If we want to run the same JavaScript on several pages, without having to write
the same script on every page, we can write a JavaScript in an external file.
Save the external JavaScript file with a .js file extension. The external script
cannot contain the <script> </script> tags. To use the external script, point to
the .js file in the "src" attribute of the <script> tag.
JavaScripts is put in a page where it will be executed immediately while the
page loads into the browser. Sometimes we want to execute a script when a
page loads, or at a later event, such as when a user clicks a button.
Script between <head>…..</head>
If we need to place our script in header of the html document like the following.
<html>
<head>
<script language="javascript">
document.write(“Welcome to Java script”);
</script>
</head>
<body>
</body>
</html>
Scripts in <body>…..</body> tags
If we don't want our script to be placed inside a function, or if our script should
write page content, it should be placed in the body section.
<html>
<head> </head>
<body>
Page 55 Lecture Note
Productivity improvement and center of excellence
<script language="javascript">
document.write("This message is written by JavaScript");
</script>
</body>
</html>
<body onload="message()">
<br><br><br><br><br><br>
<h1>I THANK YOU FOR EVERY THING YOU MADE!!!</H1>
</body>
</html>
Prompt box:- is used to allow a user to enter something according to the
promotion. It is written as window.prompt("please enter your name") or
simply write as prompt(“some text”)
Example:-
<script>
var y=window.prompt("please enter your name")
window.alert(y)
</script>
Confirm Box:- A confirm box is often used if we want the user to verify or
accept something. When a confirm box pops up, the user will have to click
either "OK" or "Cancel" to proceed. If the user clicks "OK", the box returns
true. If the user clicks "Cancel", the box returns false. It has the following
Syntax window.confirm("sometext"); or simply write confirm(“some text”)
Example :-
<script type=”text/javascript”>
var x=window. confirm("Are you sure you want to quit");
if (x)
{
window.alert("Thank you.")
x="You pressed OK!";
}
else
{
window.alert("Good choice.")
x="You pressed Cancel!";
}
document.write (x);
</script>
var age=5;
iv. Re-declaring JavaScript Variables
If we redeclare a JavaScript variable, it will not lose its original value.
var age=5;
var age;
After the execution of the statements above, the variable age will still have
the value of 5. The value of age is not reset (or cleared) when we redeclare
it.
v. Comments JavaScript supports two types of comments:
Comments on a single line are preceded by a double-slash (//).
Comments that span multiple lines are preceded by /* and followed by */
4.6. Operators and Expressions
An operator performs some kind of calculation (operation) or comparison with two
values to reach a third value. Generally, operators can be broadly categorized into
two: mathematical operators, and comparison and logical operators.
i. Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations between variables
or values. +, -, *, /, %, ++, --
ii. JavaScript Assignment Operators
Assignment operators are used to perform arithmetic operation and then assign the
result to variables. Includes:- =, +=, -=, *=, /= and %=
iii. Comparison Operators
Comparison operators help to compare two or more values — whether two values
are equal, for example. These kinds of comparisons return a value of the Boolean
type — true or false. Includes:- >, >=, <, <=, = =, and !=
iv. Logical Operators
Logical operators are used to determine the logic between variables or values:-
&&, ||
</script>
ii. Switch Statement:- A switch statement allows a program to evaluate an
expression and attempt to match the expression's value to a case label. If a match
is found, the program executes the associated statement. A switch statement
looks as follows:
switch (expression) {
case label1:
statements1
[break;]
case label2:
statements2
[break;]
...
default:
statementsdefault
[break;]
}
The program first looks for a case clause with a label matching the value of
expression. If found, it then transfers control to that clause, executing the
associated statements. If no matching label is found, the program looks for the
optional default clause. If no default clause is found, the program continues
execution at the statement following the end of switch. By convention, the default
clause is the last clause.
If break is omitted, the program continues execution at the next statement in the
switch statement when there is a matched statement.
Example:-
<script type="text/javascript">
var grade='A';
document.write("Entering switch block<br />");
switch (grade)
{
<script type="text/javascript">
var i=0;
while (i<=10)
{
document.write ("The number is " + i);
i=i+1;
}
</script>
<i>Thank you being understand me</i>
</body>
</html>
iv. Break and continue statements: -
These are used to come out of a loop without reaching at its bottom or to skip a
part of the code block and want to start next iteration of the look when needed by
users or programmers.
To handle all such situations, JavaScript provides break and continue statements.
These statements are used to immediately come out of any loop or to start the next
iteration of any loop.
Example1: the following example loops until the value of loop counter is 5:
for (i = 0; i < 100; i++) {
if (i= = 5)
break;
}
The continue statement can be used to restart a while, do-while or for statement.
When we use continue, it terminates the current iteration and continues execution
of the loop with the next iteration. In contrast to the break statement, continue does
not terminate the execution of the loop entirely. In a while loop, it jumps back to
the condition check, and in for loop, it jumps to the increment-expression. But,
break statement is used to terminate loop.
Example 2: a program that adds numbers between 0 and 100 with the exception of
60, 70, and 80
<script type=”text/javascript”>
Page 65 Lecture Note
Productivity improvement and center of excellence
C. Using Arrays
An array is an ordered collection of data. In JavaScript, arrays are limited to a table
holding one column of data, with as many rows as needed to hold data.
A JavaScript-enabled browser creates a number of internal arrays for the objects in
HTML documents and browser properties. For example, if our document contains
five links, the browser maintains a table of those links. To access them by number
(with 0 being the first link) in the array syntax as in document.links[0], which
represents the first link in the document.
To initialize an array for script, use the new keyword to construct the object for
assigning the array object to a variable of our choice like:
var myArray = new Array(n) where n is the number of entries anticipated
for the array. This initialization does not make any array entries or create
any placeholders.
Example: an array that stores the names of planets
planet = new Array(9); //an array with 9 entries
planet[0] = “Mercury” planet[5] = “Saturn”
planet[1] = “Venus” planet[6] = “Uranus”
planet[2] = “Earth” planet[7] = “Neptune”
planet[3] = “Mars” planet[8] = “Pluto”
planet[4] = “Jupiter”
The index number starts at 0 and end at n-1 for array of n entries to access
them. For example, to access the fifth planet in the planets array, we use:
planet[4]; //Jupiter
Page 66 Lecture Note
Productivity improvement and center of excellence
To deleting array entries, we can always set the value of an array entry to null
or an empty string to wipe out any data that used to occupy that space. But with
the delete operator, we could not completely remove the element. Deleting an
array element eliminates the index from the list of accessible index values but
does not reduce the array’s length.
planet.length; // result: 9
delete planet[2];
planet.length; //result: 9
planet[2]; //result: undefined
o array.concat(array2):- The array.concat() method allows to join two array
objects into a new array object. The action of concatenating the arrays does not
alter the contents or behavior of the two original arrays.
For example:
var array1 = new Array(1,2,3)
var array2 = new Array(“a”,”b”,”c”)
var array3 = array1.concat(array2) // result: array with values
1,2,3,”a”,”b”,”c”
If an array element is a string or number value (not a string or number object), the
values are copied from the original arrays into the new one. All connection with
the original arrays ceases for those items.
Example 4:- on push
<html> var length = numbers.push(10);
<head> document.write("new numbers is : " +
<title>JavaScript Array push numbers );
Method</title> length = numbers.push(20);
</head> document.write("<br />new numbers is : "
<body> + numbers );
<script type="text/javascript"> </script>
var numbers = new Array(1, 4, 9); </body>
Page 67 Lecture Note
Productivity improvement and center of excellence
</html>
definition and call to the function have only empty sets of parentheses.
When a function receives parameters, it assigns the incoming values to the
variable names specified in the function definition’s parentheses. Consider
the following script segment:
function sayHiToFirst(first, second, third) {
alert(“Say hello, “ + first)
}
sayHiToFirst(“Gracie”, “George”, “Harry”)
After the function is defined in the script, the next statement calls function, passing
three strings as parameters. The function definition automatically assigns the
strings to variables first, second, and third. Therefore, before the alert() statement
inside the function ever runs, first evaluates to “Gracie,” second evaluates to
“George,” and third evaluates to “Harry.” In the alert() statement, only the first
value is used and the alert reads
Say hello, Gracie
So, functions that are going to return a value must use the return statement. The
example below returns the product of two numbers (a and b):
<html>
<head>
<script type="text/javascript">
function product(op1, op2){
return op1*op2;
}
</script>
</head>
<body>
<script type="text/javascript">
document.write(product(4,3));
</script>
</body>
</html>
</body>
</html>
E-mail Validation The function below checks if the content has the general
syntax of an email. For example, the input data must contain at least an @ sign
and a dot (.). Also, the @ must not be the first character of the email address,
and the last dot must at least be one character after the @ sign. The entire script,
with the HTML form could look like:
will then add an onMouseOver event and an onMouseOut event that will run two
JavaScript functions that will change between the images.
Examples:- Button animation
<html> <head>
<script type="text/javascript">
function mouseOver() { document.b1.src ="b_blue.gif"; }
function mouseOut() { document.b1.src ="b_pink.gif"; } </script> </head>
<body>
<a href="http://www.w3schools.com" target="_blank">
<img border="0" src="b_pink.gif" name="b1" width="26" height="26"
onmouseover = "mouseOver()" onmouseout="mouseOut()" />
</a> </body> </html>
Note that we have given the image a name to make it possible for JavaScript to
address it later. The onMouseOver event tells the browser that once a mouse is
rolled over the image, the browser should execute a function that will replace the
image with another image.
The onMouseOut event tells the browser that once a mouse is rolled away from the
image, another JavaScript function should be executed. This function will insert
the original image again.
We might be interested in existing JavaScript based animation library. JavaScript
can be used to move a number of DOM elements (<img />, <div> or any other
HTML element) around the page according to some sort of pattern determined by a
logical equation or function. JavaScript provides following two functions to be
frequently used in animation programs.
setTimeout( function, duration) - This function calls function after
duration milliseconds from now.
setInterval(function, duration) - This function calls function after every
duration milliseconds.
Manual Animation:
So let's implement one simple animation using DOM object properties and
JavaScript functions as follows:
<html> }
<head> window.onload =init;
<title>JavaScript Animation</title> //-->
<script type="text/javascript"> </script>
<!-- </head>
var imgObj = null; <body>
function init(){ <form>
imgObj = <img id="myImage"
document.getElementById('myImage src="/images/html.gif" />
'); <p>Click button below to move the
imgObj.style.position= 'relative'; image to right</p>
imgObj.style.left = '0px'; } <input type="button" value="Click
function moveRight(){ Me" onclick="moveRight();" />
imgObj.style.left = </form>
parseInt(imgObj.style.left) + 10 + </body>
'px'; </html>
<html> imgObj.style.left =
<head> parseInt(imgObj.style.left) + 10 +
<title>JavaScript Animation</title> 'px';
<script type="text/javascript"> animate =
<!-- setTimeout(moveRight,20); // call
var imgObj = null; moveRight in 20msec
var animate ; }
function init(){ function stop(){
imgObj = clearTimeout(animate);
document.getElementById('myImage' imgObj.style.left = '0px';
); }
imgObj.style.position= 'relative'; window.onload =init;
imgObj.style.left = '0px'; //-->
} </script>
function moveRight(){ </head>
<body>
<form>
<img id="myImage"
src="/images/html.gif" />
<p>Click the buttons below to handle
animation</p>
<input type="button" value="Start"
onclick="moveRight();" />
<input type="button" value="Stop"
onclick="stop();" />
</form>
</body>
</html>
Here we have add more spice. So let's see what is new here:
The moveRight() function is calling setTimeout() function to set the position
of imgObj.
We have added a new function stop() to clear the timer set by setTimeout()
function and to set the object at its initial position.
Chapter Five
1. Server Side Scripting Basics
Static web page means that what is displayed does not change until the underlying HTML or XML is
changed.
When the content that is displayed changes in response to actions taken by the user, then the web page
is said to be dynamic. This kind of web page is developed using scripting languages.
A scripting language is a programming language in a simple text format. Generally, code written in a
scripting language does not have to be compiled – unlike, for example, code written in C++ or Visual
Basic. Instead, it is interpreted at the time of execution. Web browsers can interpret certain scripting
languages.
Scripts can be written to run either server-side or client-side. A script must be interpreted at the time it
is requested from the web server. Each scripting language has its own script interpreter – called a script
engine.
A client-side script is executed on the client, by the browser. Client-scripting is often used to validate
data entered on a form by the user, before the form is submitted to the server e.g. check that an email
address has a @ sign in it. Some of client side scripts are java script, VB script etc. In client side script,
users may be able to see the source code by viewing a file that contains the script.
A server-side script is executed on the server, and generally produces HTML which is then output HTML
to the client.
In contrast, server-side scripts, written in languages such as PHP, ASP.NET, Java, ColdFusion,
Perl, Ruby, Go, Python, and server-side JavaScript, are executed by the web server when the user
requests a document. They produce output in a format understandable by web browsers (usually
HTML), which is then sent to the user's computer. The user cannot see the script's source code (unless
the author publishes the code separately), and may not even be aware that a script was executed.
Documents produced by server-side scripts may, in turn, contain client-side scripts.
Server-side Web scripting is mostly about connecting Web sites to back end servers, such as databases.
This enables two-way communication:
Dynamically edit, change or add any content to a Web page to make it more useful for
individual users
Respond to user queries or data submitted from HTML forms
Access any data or databases and return the result to a browser
Provide security since server side codes cannot be viewed from a browser
In server side script, since the scripts are executed on the server, the browser that displays the file does
not need to support scripting at all. The following are server-side scripting languages:
PHP (*.php)
Active Server Pages (ASP)
ANSI C scripts
Java via JavaServer Pages (*.jsp)
JavaScript using Server-side JavaScript (*.ssjs)
Lasso (*.lasso) etc
What is PHP?
PHP stands for Hypertext Preprocessor and is a server-side language. This means that the script is run on
your web server, not on the user's browser, so you do not need to worry about compatibility issues. PHP
supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, Microsoft
SQL Server etc.). PHP files can contain text, HTML tags and scripts. Like other files written in server side
language, PHP files are returned to the browser as plain HTML and it has a file extension of ".php",
".php3", or ".phtml".
Why PHP?
Allows easy storage and retrieval of information from supported database.
Accessibility: You can reach the internet from any browser, any device, anytime,
anywhere.
Page 79 of 160 Lecture Note
Productivity improvement and center of excellence
Manageability: It does not require distribution of application code and it is easy to change
code.
Security: The source code is not exposed. Once user is authenticated, can only allow
certain actions. It also allows encryption.
Scalability: Web-based 3-tier architecture can scale out
1) First of all you need a computer with a web server installed. PHP uses web servers such
as Apache, IIS etc. But for this course we will install WAMP server. WAMP server
refers to a software stack for the Microsoft Windows operating system, created by
Romain Bourdon and consisting of the Apache web server, OpenSSL for SSL (Secure
Sockets Layer) support, MySQL database and PHP programming language. WAMP sever
has a root directory called WWW. So all the files of a website must be stored under this
directory (C:\wamp\www\) to be executed by the server.
2) You need some sort of text editor such as Notepad, Notepad++, etc. to write the scripts.
3) You also need a web browser to display the web content. The web browser can be
Internet Explorer, Mozilla Firefox, Opera, and Google Chrome etc.
<?php
Your PHP code here
?>
If you use this style, you can be positive that your tags will always be correctly interpreted.
ii. Short-open (SGML-style) tags: Short or short-open tags look like this:
<?
Your PHP code
here
?>
Page 80 of 160 Lecture Note
Productivity improvement and center of excellence
Short tags are, as one might expect, the shortest option. We must do one of two things to enable PHP to
recognize the tags:
iv. HTML script tags: HTML script tags look like this :
PHP output Statement <script
language="PHP">
Your PHP code here
</script>
1.4.PHP Output Statement
As shown above PHP has different syntaxes but for maximum compatibility, it is recommended to use <?
php…?> .
Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to distinguish
one set of instructions from another.
There are two basic statements to output text with PHP: echo and print.
echo has no return value whereas print has a return value. The returned value represents
whether the print statement is succeeded or not. If the print statement succeeds, the
statement returns 1 otherwise 0. It is rare that a syntactically correct print statement will
fail, but in theory this return value provides a means to test, for example, if the user’s
browser has closed the connection and sometimes the returned value can be used in
expressions.
echo can take multiple parameters (although such usage is rare) but print can only take
one argument.
echo is marginally faster than print.
The echo or print statement can be used with or without parentheses: echo or echo().
The general format of the echo statement is as follows:
echo outputitem1,outputitem2,outputitem3, . . .;
echo (output statement);
The parameterized version of echo does not accept multiple arguments.
print outputstatement;
print(outputstatement);
Example: different ways of echo and print
echo 123; //output: 123
The first echo statement includes a space so the space is output. The second row has two echo
statements, but neither includes a space, so no space appears in the Web page. Each echo statement
output does not go to new line unless we insert \n. The third row shows a space on the Web page, even
though no space is included in the echo statement. The space is added by the browser when it reads the
PHP output as HTML. In HTML, a new line is not displayed as a new line; it is just interpreted as a single
space.
Multi-lines printing: use the key word END next to <<< symbol and before the statement terminating
symbol (;) or enclose the statements to be displayed using double quotes. Here are the examples to
print multiple lines in a single print statement:
<?php
# First Example
print <<<END
This uses the "here document" syntax to output multiple lines with $variable
interpolation. Note that the here document terminator must appear on a line with
just a semicolon no extra whitespace!
END;
# Second Example
print "This spans multiple lines. The newlines will be
output as well";
?>
Note: The file must have a .php extension. If the file has a .html extension, the PHP code will not be
executed.
1.5.PHP Comments
A comment is the portion of a program that exists only for the human reader and stripped out before
displaying the programs result. There are two commenting formats in PHP:
Single-line comments: They are generally used for short explanations or notes relevant
to the local code. Here are the examples of single line comments.
<?php
# This is a comment
// This is a comment too
print “An example with single line comment”;
?>
Multi-lines comments:
explanations when necessary. The multiline style of commenting is the same as in C.
Here is the example of multi lines comments.
<?php
/* This is a comment with multiline
Author : Abebe Kebede
Purpose: Multiline Comments Demo
Subject: PHP
*/
echo "An example with multi line
comments";
?>
When creating PHP variables, you must follow these four rules:
Variable names must start with a letter of the alphabet or the _ (underscore) character.
Variable names can contain only the characters: a-z, A-Z, 0-9, and _ (underscore).
Variable names may not contain spaces. If a variable must comprise more than one word
it should be separated with the _ (underscore) character. (e.g., $user_name).
Variable names are case-sensitive. The variable $High_Score is not the same as the variable
$high_score.
$Variable_Name=value;
PHP has a total of eight data types which we use to construct our variables: integers, doubles, Booleans,
null, strings, arrays, objects and resources. The first five are simple types, and the next two (arrays and
objects) are compound - the compound types can package up other arbitrary values of arbitrary type,
whereas the simple types cannot.
Integers:
Integers are whole numbers, without a decimal point, like 3214. They are the simplest type .they
correspond to simple whole numbers, both positive and negative. Integers can be assigned to variables,
or they can be used in expressions, like so:
Page 84 of 160 Lecture Note
Productivity improvement and center of excellence
$int_var = 12345;
$another_int = -12345 + 12345;
Doubles:
They are floating point numbers. By default, doubles print with the minimum number of decimal places
needed. For example, the code:
$pi= 3.14;
$version=1.12;
Boolean:
They have only two possible values either true or false. PHP provides a couple of constants
especially for use as Booleans: TRUE and FALSE, which can be used like so:
if (TRUE)
print("This will always print<br>");
else
print("This will never print<br>");
NULL:
NULL is a special type that only has one value: NULL. To give a variable the NULL value, simply assign it like this:
$my_var = NULL;
The special constant NULL is capitalized by convention, but actually it is case insensitive; you could just
as well have typed:
$my_var = null;
A variable that has been assigned NULL has the following properties:
Strings:
They are sequences of characters, like "PHP supports string operations". Following are valid examples of
string
<? php
$variable = "name";
$literally = 'My $variable will not print!\\n';
print($literally);
$literally = "My $variable will print!\\n";
print($literally);
?>
This will produce the following result:
Strings that are delimited by double quotes (as in "this") are preprocessed in both the following two
ways by PHP:
Certain character sequences beginning with backslash (\) are replaced with special
characters
Variable names (starting with $) are replaced with string representations of their values.
PHP provides a large number of predefined variables to all scripts. The variables represent everything
from external variables to built-in environment variables, last error messages to last retrieved headers.
Superglobals — Superglobals are built-in variables that are always available in all scopes
$GLOBALS — References all variables available in global scope
$_SERVER — Server and execution environment information
$_GET — HTTP GET variables
$_POST — HTTP POST variables
$_FILES — HTTP File Upload variables
$_REQUEST — HTTP Request variables, and can replace $_POST, $_GET and $_COOKIE variables
$_SESSION — Session variables
$_COOKIE — HTTP Cookies
$php_errormsg — The previous error message
$HTTP_RAW_POST_DATA — Raw POST data
$http_response_header — HTTP response headers
$argc — The number of arguments passed to script
$argv — Array of arguments passed to script
Many of these variables, however, cannot be fully documented as they are dependent upon which
server are running, the version and setup of the server, and other factors.
Removing Variables
We can uncreated the variable by using this statement: unset(VariableName);
After this statement, the variable $age no longer exists. If we try to echo it, you get an
“undefined variable” notice. It is possible to unset more than one variable at once, as follows:
unset($age, $name, $address);
Variable Scope:
Scope can be defined as the range of availability a variable has to the program in which it is declared.
PHP variables can be one of four scope types:
Local variables
Function parameters
Global variables
Static variables
<?
$x = 4;
function assignx () {
$x = 0;
print "\$x inside function is $x. ";
}
assignx();
print "\$x outside of function is $x. ";
?>
This will produce the following result.
$x inside function is 0.
$x outside of function is 4.
Function parameters are declared after the function name and inside parentheses. They are declared
much like a typical variable would be:
<?
// multiply a value by 10 and return it to the caller
function multiply ($value) {
$value = $value * 10;
return $value;
}
$retval = multiply (10);
Print "Return value is $retval\n";
?>
This will produce the following result.
<?
$somevar = 15;
function addit() {
GLOBAL $somevar;
$somevar++;
print "Somevar is $somevar";
}
addit();
?>
This will produce the following result.
Somevar is 16
You can declare a variable to be static simply by placing the keyword STATIC in front of the variable
name.
<?
function keep_track() {
STATIC $count = 0;
$count++;
print $count;
print " ";
}
keep_track();
keep_track();
keep_track();
?>
This will produce the following result.
1
2
3
Page 88 of 160 Lecture Note
Productivity improvement and center of excellence
To define a constant you have to use define() function and to retrieve the value of a constant, you have
to simply specifying its name. Unlike with variables, you do not need to have a constant with a $. You
can also use the function constant() to read a constant's value if you wish to obtain the constant's name
dynamically.
constant() function
As indicated by the name, this function will return the value of the constant.
This is useful when you want to retrieve value of a constant, but you do not know its name, i.e. It is
stored in a variable or returned by a function.
Example
<?php
define("MINSIZE", 50);
echo MINSIZE;
echo constant("MINSIZE"); // same thing as the previous line
?>
Only scalar data (boolean, integer, float and string) can be contained in constants.
There is no need to write a dollar sign ($) before a constant, where as in Variable one has
to write a dollar sign.
Constants cannot be defined by simple assignment, they may only be defined using the
define() function.
Constants may be defined and accessed anywhere without regard to variable scoping
rules.
Once the Constants have been set, may not be redefined or undefined.
1.8.Manipulate Numbers
In everyday life, numbers are easy to identify. They're 3:00 P.M., as in the current time, or 1.29 Birr, as in
the cost of an item. Maybe they're like, the ratio of the circumference to the diameter of a circle. In PHP,
numbers can be all these things.
However, PHP doesn't treat all these numbers as "numbers." Instead, it breaks them down into two
groups: integers and floating-point numbers. Integers are whole numbers, such as -4, 0, 5, and 1,975.
Floating-point numbers are decimal numbers, such as -1.23, 0.0, 3.14159, and 9.9999999999.
Conveniently, most of the time PHP doesn't make you worry about the differences between the two
because it automatically converts integers to floating-point numbers and floating-point numbers to
integers. This conveniently allows you to ignore the underlying details. It also means 3/2 is 1.5, not 1,
as it would be in some programming languages. PHP also automatically converts from strings to
numbers and back. For instance, 1+"1" is 2.
You want to ensure that a string contains a number. For example, you want to validate an age that the
user has typed into a form input field. Use is_numeric( ):
if (is_numeric('five')) { /* false */ }
if (is_numeric(5)) { /* true */ }
if (is_numeric('5')) { /* true */ }
if (is_numeric(-5)) { /* true */ }
if (is_numeric('-5')) { /* true */ }
Rounding Floating-Point Numbers:
Use the range( ) function, which returns an array populated with integers:
foreach(range($start,$end) as $i) {
echo “$i<br>”; }
Instead of using range(), it can be more efficient to use a for loop. Also, you can increment using
values other than 1. For example:
You have a number and you want to print it with thousands and decimals separators. For instance, you
want to display prices for items in a shopping cart.
$number = 1234.56;
print number_format($number); // 1,235 because number is rounded up
Specify a number of decimal places to format as a decimal:
1.9.Manipulate Strings
Strings in PHP are a sequence of characters, such as "We hold these truths to be self evident," or "Once
upon a time," or even "111211211". When you read data from a file or output it to a web browser, your
data is represented as strings. The following are string manipulation operations:-
String concatenation operation: - To concatenate two string variables together, use the dot (.)
operator like echo $string1 . " " . $string2;
Substr()-uses to copy strings.
The start argument is the position in string at which to begin copying, with 0 meaning the start of
the string. The length argument is the number of characters to copy (the default is to copy until the
end of the string).
For example:
$fluff = substr($name, 6, 4);// $fluff is "lint" i.e copy strings from 6th about 4 chars consecutively
$sound = substr($name, 11);// $sound is "tone" i.e copy from 11th character on wards and assign
to the variable $sound
substr_count():- uses to count how many times a smaller string occurs in a larger one.
For example:
Well, there's egg and bacon; egg sausage and bacon; egg and spam;
egg bacon and spam; egg bacon sausage and spam; spam bacon sausage
and spam; spam egg spam spam bacon and spam; spam sausage spam spam
End_of_Sketch;
Has syntax of $string = substr_replace(original string, new string, start [, length ]); where
start shows starting from where we need replace by new string/ start is the index of the first character
that we need to replace. The length parameter uses to indicate how many characters we need to
replace from original characters.
The function replaces the part of original indicated by the start (0 means the start of the string) and
length values with the string new. If no fourth argument is given, substr_replace( ) removes the
text from start to the end of the string.
For instance:
Here's how we can insert at the beginning of the string without deleting from original character:
A negative value for start indicates the number of characters from the end of the string from which to
start the replacement:
A negative length indicates the number of characters from the end of the string at which to stop
deleting:
strrev() function:- takes a string and returns a reversed copy of it. Has syntax:-
$string = strrev(string);
For example:
labac on si erehT
str_repeat() function:- takes a string and a count and returns a new string consisting of the
str_pad( ) function:- pads one string with another i.e left blank space. Optionally, we can say
what string to pad with, and whether to pad on the left, right, or both:
$padded = str_pad(to_pad, length [, with [, pad_type ]]);
echo "{$string}35";
Fred Flintstone. . . . . . . .35
The optional fourth argument can be either STR_PAD_RIGHT (the default), STR_PAD_LEFT, or
STR_PAD_BOTH (to center). For example:
strpos() function:- used to search for a string or character within a string. If a match is found in
the string, this function will return the position of the first match. If no match is found, it will
return FALSE.
Example: the following code used to show from where the word “world” started.
<?php
echo strpos("Hello world!","world");
?>
The output will be 6. As seen the position of the string "world" in our string is position 6. The reason that
it is 6, and not 7, is that the first position in the string is 0, and not 1.
Example:-
$long = "Today is the day we go on holiday to Florida";
$to_find = "day";
$pos = strpos(strrev ($long), strrev($to_find));
if ($pos === false) {
echo("Not found");
} else {
// $pos is offset into reversed strings
// Convert to offset into regular strings
$pos = strlen($long) - $pos - strlen($to_find);;
echo("Last occurrence starts at position $pos");
}
Last occurrence starts at position 30
String-Searching Functions
Several functions find a string or character within a larger string. They come in three families: strpos()
and strrpos(), which return a position; strstr() and strchr(), which return the string they find;
and strspn() and strcspn(), which return how much of the start of the string matches a mask.
The strstr() function finds the first occurrence of a small string in a larger string and returns from that
small string on. For instance:
$record = "Fred,Flintstone,35,Wilma";
$rest = strstr($record, ","); // $rest is ",Flintstone,35,Wilma"
As with strrpos(), strrchr() searches backward in the string, but only for a character, not for an
entire string.
<?php
echo strlen("Hello world!");
?>
Reading Assignment
You can use conditional statements in your code to make your decisions. PHP supports following
decision making statements:
The if Statement
Use the if statement to execute some code only if a specified condition is true.
Syntax
if (condition)
code to be executed if condition is true;
The following example will output "Have a nice weekend!" if the current day is Friday:
<?php
$d=date("D");
if ($d=="Fri") echo "Have a nice weekend!";
?>
Notice that there is no ..else.. in this syntax. The code is executed only if the specified condition
is true.
Syntax
if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
Note: If more than one line should be executed if a condition is true/false, the lines should be enclosed
within curly braces.
Example:
The following example will output "Have a nice weekend!" if the current day is Friday, otherwise it will
output "Have a nice day!”
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
else
echo "Have a nice day!";
?>
Syntax
if (condition)
code to be executed if condition is true;
else if(condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
Example:
The following example will output "Have a nice weekend!" if the current day is Friday, and "Have a nice
Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice day!"
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
elseif ($d=="Sun")
echo "Have a nice Sunday!";
else
echo "Have a nice day!";
?>
The switch statement is used to avoid long blocks of if..else if..else code.
Syntax:
switch (expression)
{
case label1:
code to be executed if expression = label1;
break;
case label2:
code to be executed if expression = label2;
break;
default:
code to be executed if expression is different from both label1 and label2; }
Example
The switch statement works in an unusual way. First it evaluates given expression then seeks a label to
match the resulting value. If a matching value is found, then the code associated with the matching label
will be executed. If none of the labels match, then the statement will execute any specified default code.
<?php
$d=date("D");
switch ($d)
{
case "Mon":
echo "Today is Monday";
break;
case "Tue":
echo "Today is Tuesday";
break;
case "Wed":
echo "Today is Wednesday";
break;
case "Thu":
echo "Today is Thursday";
break;
case "Fri":
echo "Today is Friday";
break;
case "Sat":
echo "Today is Saturday";
break;
case "Sun":
echo "Today is Sunday";
break;
default:
echo "Wonder which day is this ?";
}
?>
Syntax
for (initialization; condition; increment)
{
code to be executed;
}
Parameters:
initialization: Mostly used to set a counter (but can be any code to be executed once at
the beginning of the loop)
condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues.
If it evaluates to FALSE, the loop ends.
increment: Mostly used to increment a counter (but can be any code to be executed at the
end of the loop)
Note: Each of the parameters above can be empty, or have multiple expressions (separated by
commas).
Example
1. The example below defines a loop that starts with i=1. The loop will continue to run as long as i is less than, or equal to
5. i will increase by 1 each time the loop runs:
<?php
for ($i=1; $i<=5; $i++)
{
echo "The number is " . $i . "<br />";
}
?>
2. The following example displays a product table
<html><body>
<?php
echo "<h1>Multiplication table</h1>";
echo "<table border=2 width=50%";
for ($i = 1; $i <= 5; $i++ ) { //this is the outer loop
echo "<tr>";
echo "<td>".$i."</td>";
for ( $j = 2; $j <= 5; $j++ ) { // inner loop
echo "<td>".$i * $j."</td>";
}
echo "</tr>";
}
echo "</table>";
?>
</body>
</html>
Syntax
while (condition)
{
code to be executed;
}
Example: The following example shows how to insert years from 1970-2015 in a form list box and
display the selected year upon submit.
<html><body>
<form action="" method="post">
Year:<select name="year">
<?php
$year=1970;
while($year<=2015)
{ echo "<option value=$year>$year</option>";
$year++;
}
echo "</select>";
?>
<br><input type="submit" value="Display"></form>
<?php
$year=$_POST['year'];
if($year!=null)
echo "Year:$year";
?>
</body></html>
Syntax
do
{
code to be executed;
}
while (condition);
Example
The example below defines a loop that starts with i=1. It will then increment i with 1, and write some
output. Then the condition is checked, and the loop will continue to run as long as i is less than, or equal
to 5:
<html><body>
<?php
$i=1;
echo “The number is:”;
do
{
$i++;
echo "$i ";
}
while ($i<=5);
?>
</body></html>
The foreach statement is used to loop through arrays. For each pass the value of the current array
element is assigned to $value and the array pointer is moved by one and in the next pass next element
will be processed.
Syntax
Try out the following example to list out the values of an array.
<?php
$array = array( 1, 2, 3, 4, 5);
echo "Values of the array:”;
foreach( $array as $value )
{
echo “$value ";
}
?>
This will produce the following result:
Values of the array:1 2 3 4 5
The PHP break keyword is used to terminate the execution of a loop prematurely. The break statement
is situated inside the statement block. It gives you full control and whenever you want to exit from the
loop you can come out. After coming out of a loop immediate statement to the loop will be executed.
Example:
<?php
$i = 0;
while( $i < 10)
{
$i++;
if( $i == 3 ) break;
}
echo ("Loop stopped at i = $i" );
?>
The PHP continue keyword is used to halt the current iteration of a loop but it does not terminate the
loop. Just like the break statement the continue statement is situated inside the statement block
containing the code that the loop executes, preceded by a conditional test. For the pass encountering
continue statement, rest of the loop code is skipped and next pass starts.
Example
In the following example loop prints the value of array but for which condition becomes true it just skip
the code and next value is printed.
<?php
$array = array( 1, 2, 3, 4, 5);
echo “Values of the array:”;
foreach( $array as $value )
{
if( $value == 3 )continue;
echo "$value ";
}
?>
This will produce the following result:
Values of the array:1 2 4 5
2.3. Arrays
A variable is a storage area holding a number or text. The problem is, a variable will hold only one value.
An array is a special variable that stores one or more similar type of values in a single variable. For
example if you want to store 100 numbers then instead of defining 100 variables it’s easy to define an
array of 100 length.
An array can hold all your variable values under a single name. And you can access the values by
referring to the array name. Each element in the array has its own index so that it can be easily
accessed.
Numeric array - An array with a numeric index. Values are stored and accessed in linear
fashion
Associative array - An array where each ID key is associated with a value
Multidimensional array - An array containing one or more arrays and values are
accessed using multiple indices
Numeric Array
These arrays can store numbers, strings and any object but their index will be represented by numbers.
By default, the array index starts from zero.
Example
The following example demonstrates how to create and access numeric arrays. Here we have used
array() function to create array.
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
echo "Value of the array:”;
foreach( $numbers as $value )
{
echo "$value ";
}
/* Second method to create array. */
$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";
echo "Value of the array:”;
foreach( $numbers as $value )
{
echo "$value ";
}
?>
This will produce the following result:
Associative Arrays
The associative arrays are very similar to numeric arrays in terms of functionality but they are different
in terms of their index. When storing data about specific named values, a numerical array is not always
the best way to do it. Associative array will have their index as string so that you can establish a strong
association between key and values.
Example 1
$credit_hour[‘AIP’] = "3";
$credit_hour[‘AP’] = "3";
$credit_hour[‘DCN’] = "4";
$credit_hour[‘CMT’] = "4";
$credit_hour[‘EDP’] = "4";
<?php
$credit_hour = array("AIP"=>3, "AP"=>3, "DCN"=>4, "CMT"=>4, "EDP"=>4);
GPA: 2.94
NOTE: Don't keep associative array inside double quote while printing, otherwise it would not return
any value.
Multidimensional Arrays
A multi-dimensional array each element in the main array can also be an array. And each element in the
sub-array can be an array, and so on. Values in the multi-dimensional array are accessed using multiple
indexes.
Example:
<?php
$grade = array("Abebe"=>array("AIP"=>'A',"AP"=>'B'),"Ermias"=>array("AIP"=>'B',
"AP"=>'C'));
foreach($grade['Abebe'] as $key=>$value)
echo "<br>Abebe scored:".$value." in ".$key;
foreach($grade['Ermias'] as $key=>$value)
echo "<br>Ermias scored:".$value." in ".$key;
?>
This will produce the following result:
$grade['Abebe']['AP']="B";
$grade[‘Ermias’]['AIP']="B";
$grade[‘Ermias’]['AP']="C";
foreach($grade['Abebe'] as $key=>$value)
echo "<br>Abebe scored:".$value." in ".$key;
foreach($grade['Ermias'] as $key=>$value)
PHP comes with four functions that allow us to add or remove elements from the beginning or end of an
array: the array_unshift() function adds an element to the beginning of an array; the array_shift()
function removes the first element of an array; the array_push() function adds an element to the end of
an array; and the array_pop() function removes the last element of an array. The following listing
illustrates them all in action:
<?php
// define array
$movies = array('The Lion King', 'Cars', 'A Bug\'s Life');
// remove element from beginning of array
array_shift($movies);
// remove element from end of array
array_pop($movies);
// add element to end of array
array_push($movies, 'Ratatouille');
// add element to beginning of array
array_unshift($movies, 'The Incredibles');
// print array
// output: ('The Incredibles', 'Cars', 'Ratatouille')
print_r($movies);
?>
Notethat:- The array_unshift(), array_shift(), array_push(), and array_pop() functions should be used
only with numerically indexed arrays and not with associative arrays. Each of these functions
automatically re-indexes the array to account for the value(s).
Sorting Arrays
PHP comes with a number of built-in functions designed for sorting array elements in different ways.
The first of these is the sort() function, which lets to sort numerically indexed arrays alphabetically or
numerically, from lowest to highest value.
Some Sorting Functions of PHP which has different sorting orders are:-
asort($data);
print_r($data);// Array ( [4] => 2 [2] => 14 [0] => 15 [3] => 74 [1] => 81 )
echo "<br/>";
ksort($data);
print_r($data);// Array ( [0] => 15 [1] => 81 [2] => 14 [3] => 74 [4] => 2 )
echo "<br/>";
sort($data);
print_r($data);// Array ( [0] => 2 [1] => 14 [2] => 15 [3] => 74 [4] => 81 )
?>
PHP functions are similar to other programming languages. A function is a piece of code which takes one
or more input in the form of parameter and does some processing and returns a value.
Functions MUST be defined before they called. Functions can only be executed if they
are called. Function headers are of the format:- function functionName($arg_1, $arg_2,
…, $arg_n)
Unlike variables, function names are not case sensitive (foo(…) == Foo(…) == FoO(…))
Function statements do the actual work of the function and must be contained within
the function braces
<?php
function writeMessage()
{
echo "You are really a nice person, Have a nice time!";
}
writeMessage();
?>
ii. PHP Functions with Parameters:
PHP gives us option to pass our parameters inside a function. We can pass as many as parameters we
like. These parameters work like variables inside function. Following example takes two integer
parameters and add them together and then print them.
<?php
function addFunction($num1, $num2){
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
Any changes made to an argument in these cases will change the value of the original variable. You can
pass an argument by reference by adding an ampersand to the variable name in either the function call
or the function definition. The following example shows both the cases.
<html><body>
<?php
function addFive(&$num){
$num += 5;}
function addSix(&$num){
$num += 6;}
$orignum = 10;
addFive($orignum );
echo "Original Value is $orignum<br />";
addSix($orignum );
echo "Original Value is $orignum<br />";
?>
</body></html>
iv. PHP Functions returning value:
A function can return a value using the return statement in conjunction with a value or object. Return
stops the execution of the function and sends the value back to the calling code. It is possible to return
more than one value from a function using return array(1,2,3,4).
The following example takes two integer parameters and adds them together and then returns their
sum to the calling program. Note that return keyword is used to return a value from a function.
<html><body>
<?php
function addFunction($num1, $num2){
$sum = $num1 + $num2;
return $sum;}
$return_value = addFunction(10, 20);
echo "Returned value from the function : $return_value”;
?>
</body></html>
We can return multiple values from a function, by placing them all in an array and returning the array.
The next example illustrates, by accepting a sentence and returning the individual words, reversed, to
the caller as an array:
<?php
function add_sub($num1,$num2){
$add=$num1+$num2;
$sub=$num1-$num2;
return array($add,$sub);
}
$result_array=add_sub(15,20);
echo "Add:".$result_array[0]."<br>";
echo "Sub:".$result_array[1]."<br>";
//you can use list function to assign the returned value to variables
list($add_result,$sub_result)=add_sub(30,20);
echo "Add:".$add_result."<br>";
echo "Sub:".$sub_result;
?>
v. Setting Default Values for Function Parameters:
We can set a parameter to have a default value if the function's caller doesn't pass it.
<?php
function studinfo($department="IT",$year="3rd"){
return "You are $year year $department student<br>";
}
echo studinfo();
echo studinfo("Software Engineering","1st");
echo studinfo("Electrical",Null);
echo studinfo("2nd");
?>
Output
You are 3rd year IT student
You are 1st year Software Engineering student
You are year Electrical student
You are 3rd year 2nd student
vi. Dynamic Function Calls:
It is possible to assign function names as strings to variables and then treat these variables exactly as the
function name itself. Following example depicts this behavior. From the following code, Hello will be
displayed.
<html><body>
<?php
function sayHello(){
echo "Hello<br />";}
$function_holder = "sayHello";
$function_holder();
?>
</body></html>
vii. Using Recursive Function
Another, slightly more complex idea involving functions is recursion. A recursive function is a function
that calls itself repeatedly until a condition is satisfied. Such a function is typically used to solve complex,
iterative calculations, or to process deeply nested structures.
<?php
function printValues($arr) {
global $count;
global $out;
if (!is_array($arr)) {
die('ERROR: Input is not an array');
}
foreach ($arr as $a) {
if (is_array($a)) {
printValues($a);
} else {
$out[] = $a;
$count++;
}
}
return array('total' => $count, 'values' => $out);
}
$data = array(
'o' => array(
'orange',
'owl',
'one'),
't' => array(
'tea',
'ten',
'tag',
'twentythree' => array(
array('twenty', 'three'),
array('vingt', 'trois', array(
'red' => 'baron',
'blue' => 'blood'
)))));
// count and print values in nested array
$ret = printValues($data);
echo $ret['total'] . ' value(s) found: ';
echo "<br/>";
echo implode(', ', $ret['values']);
?>
Output:
12 value(s) found:
orange, owl, one, tea, ten, tag, twenty, three, vingt, trois, baron, blood
o Using die() function:: - While writing PHP program, we should check all possible
error condition before going ahead and take appropriate action when required.
<?php
if(!file_exists("/tmp/test.txt"))
{
die("File not found");
}
else
{
$file=fopen("/tmp/test.txt","r");
print "Opend file sucessfully";
Page 109 of 160 Lecture Note
Productivity improvement and center of excellence
}
// Test of the code here.
?>
Using above technique, we can stop a program whenever errors occur and display more meaningful and
user friendly message.
Syntax
error_function(error_level,error_message, error_file,error_line,error_context);
where
Parameter Description
error_level Required - Specifies the error report level for the user-defined error. Must be a
value number.
error_messag Required - Specifies the error message for the user-defined error
e
error_file Optional - Specifies the filename in which the error occurred
error_line Optional - Specifies the line number in which the error occurred
error_context Optional - Specifies an array containing every variable and their values in use
when the error occurred
The following example shows how we could define error handling functions
<?php
function handleError($errno, $errstr,$error_file,$error_line)
{
echo "<b>Error:</b> [$errno] $errstr - $error_file:$error_line";
echo "<br />";
echo "Terminating PHP Script";
die();
}
?>
Once you define your custom error handler you need to set it using PHP built-in library
set_error_handler function. Now let’s examine our example by calling a function which does not exist.
<?php
error_reporting( E_ERROR );
function handleError($errno, $errstr,$error_file,$error_line)
{
echo "<b>Error:</b> [$errno] $errstr - $error_file:$error_line";
echo "<br />";
echo "Terminating PHP Script";
die();
}
//set error handler
set_error_handler("handleError");
//trigger error
myFunction (1,"fatal error","c:\\",12);
?>
The form variables are available to PHP in the page to which they have been submitted. The variables
are available in three superglobal arrays created by PHP called $_POST, $_GET and $_REQUEST.
<?php
if( $_GET["name"] || $_GET["age"] )
{ echo "Welcome ". $_GET['name']. "<br />";
echo "You are ". $_GET['age']. " years old.";
exit();
}
?>
<html><body>
<form action="<?php $_PHP_SELF ?>" method="GET">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
The above code’s action attribute value can be represented as the filename itself like:-
The POST method does not have any restriction on data size to be sent.
Relatively secured and can be used in large data requesting and responding
The POST method can be used to send ASCII as well as binary data.
The data sent by POST method goes through HTTP header so it is secured enough on
HTTP protocol. The PHP provides $_POST associative array to access all the
information sent using POST method.
Example: - Take the above example and change the value of method attribute in the form from GET to
POST and the variable from $_GET to $_POST.
<?php
echo "Welcome to the homepage";
?>
Save the above file with a filename welcome.php.
<html><body>
<form action="" method="post">
Username:<input type="text" name="username"><br>
Password:<input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
</body>
</html>
<?php
$una="abc";
$pwd="abc1234";
$username=$_REQUEST['username'];
Page 112 of 160 Lecture Note
Productivity improvement and center of excellence
$password=$_REQUEST['password'];
if($username==$una&&$password==$pwd)
header("location:welcome.php");
else
echo "Please enter valid username/password";
?>
Save the above file with a filename login.php, run it and see the output.
The PHP header () function supplies raw HTTP headers to the browser and can be used to redirect it to
another location. The redirection script should be at the very top of the page to prevent any other part
of the page from loading.
The target is specified by the Location: header as the argument to the header () function. After calling
this function the exit () function can be used to halt parsing of rest of the code.
Form Validation
User input should be validated on the browser whenever possible (by client scripts). Browser validation
is faster and reduces the server load.
You should consider server validation if the user input will be inserted into a database. A good way to
validate a form on the server is to post the form to itself, instead of jumping to a different page. The
user will then get the error messages on the same page as the form. This makes it easier to discover the
error.
Common Validations
Presence Validation
String Length Validation
Type Validation
Inclusion in set Validation
Uniqueness Validation
Format Validation
Presence Validation: is used to check if there is something in a field or if a variable is not empty.
$value=“”;
if(!isset($value)||empty($value))
die("Validation failed");
String Length Validation: is used to check if a value is within a certain range.
$password=”itec1234”;
$min=6;
$max=10;
if(strlen($password)<$min&&strlen($password)>$max)
die("Password doesnot fulfill the requirement");
Type Validation: is checking whether the given value is number, string or of another type.
$value=5;
if(!is_numeric($value))
die("Validation failed not integer");
Inclusion in set Validation: Is used to validate whether the value is in the set
$value=$_POST['value'];
$set=array("M","F");
if(!in_array($value,$set))
die("Not in the list");
Uniqueness Validation: Is used to validate whether the value which is going to be submitted to a
database is unique or not
$username=$_POST['value'];
$usernamefromdb=array();
if(in_array($username,$usernamefromdb))
die("Not unique");
Format Validation: Is used to validate whether the value has the right format e.g. email with @ symbol,
currency with $ symbol, DateTime with AM or PM
if (!preg_match("/^[.0-9]*$/",$value))
die("Please enter numbers only for Age");
or
$age= htmlspecialchars($_POST['age']);
if (!preg_match("/\D/",$age))
die("Please enter numbers only for Age");
Letters a-z and A-Z only
if (!preg_match("/^[a-zA-Z ]*$/",$value)) {
die("Only letters and white space allowed");
Validate e-mail address: Used to check an email is valid, i.e to have valid forms. There is
a simple way to check if data entered into input field named "email" is an e-mail address
without any unnecessary complications and fancy regular expressions.
if (!filter_var($value, FILTER_VALIDATE_EMAIL))
die("Invalid email format");
Or
if(!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$value))
Page 114 of 160 Lecture Note
Productivity improvement and center of excellence
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?
=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$value)) {
die("Invalid URL");
Example: Using form validation. The validation rules here are:
Display “Welcome! Please fill the following fields if you wanna sign up!” message
while the page is opened for the first time.
Display “Please fill all the required fields!” message if all of the fields are empty upon
submission.
Display “First Name can contain only characters!” message if the user enters characters
other than a-z or A-Z in FirstName field.
Display “Last Name can contain only characters!” message if the user enters characters
other than a-z or A-Z in LastName field.
Display “Age can only be number!” message if the user enters characters other than 0-9
in FirstName field.
Display “Invalid Email!” message if the user enters an email which does not include @
and . symbols in it.
Display “Username already exist!” message if the user enter either of abc,12, xyz
usernames
Display “Password must be above 6 characters!” message if the user enters a password
which consists 6 or less characters.
Display “Invalid URL!” message if the user enters a website which does not contain
http/s,ftp,www,.domainname.
Otherwise display all the values submitted from the form.
Formvalidation.php
<html>
<head><link rel="stylesheet" type="text/css" href="formstyle.css"></head>
<body>
<div id="xx"><div id="xxx"><h1>User SignUp Form</h1></div>
<hr> <div id="xxx">
<form action="" method="post">
FirstName:<input type="text" name="fname"><font>*</font><br>
LastName:<input type="text" name="lname"><font>*</font><br>
Sex:<select name="sex"><option value="" selected>Choose Gender</option><option
value="M">Male</option><option value="F">Female</option></select><font>*</font></br>
Age:<input type="text" name="age"><font>*</font><br>
if($c==0) {
echo "<center><i>You have successfully signed up!</i></center>";
echo "<hr><b><center>Your Details</center></b><hr>";
echo "Full Name:$fname $lname<br>";
echo "Sex:$sex Age:$age<br>";
echo "Email:$email<br>Username:$username<br>";
}
}else{
echo "Please fill all the required fields!<br>";
}
if(!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i",$website)&&$c==0)
echo "";
else if($c>0)
echo "Invalid url";
else
echo "Website:$website<br><hr><br>";
}else{
echo "Welcome! Please fill the following fields if you wanna sign up!</div></div>";
}
?></body></html>
3. Connecting to Databases
3.1. Introduction
One of the reasons for PHP’s popularity as a Web scripting language is its support for a wide range of
relational database systems. This support makes it easy for Web developers to create data-driven Web
sites and to prototype new Web applications quickly and efficiently.
PHP supports more than fifteen different database engines, including Microsoft SQL Server, IBM DB2,
PostgreSQL, MySQL, and Oracle. Using database in applications helps us to: Read/write data, Store
more data, have better organized data, faster access to data, easier to manipulate and relate data to
other data.
Tables: is a set of rows and columns. It represents a single concept such as products, customers, orders
etc. We can create relationships among tables.
Columns: a set of data of single data type. Ex. FirstName, LastName, Email, Password etc. columns have
types such as strings, integers, float, date etc.
Foreign key: table columns whose values references rows in another table. It is the foundation of
relational table.
PHP allows developers to interact with databases in two ways: by using a customized database specific
extension, or by using the database-neutral PHP Data Objects (PDO) extension. While the PDO extension
is more portable, many developers still find it preferable to use the native database extension, especially
when the native extension offers better performance or more features than the PDO version.
Of the various database engines supported by PHP, the most popular one by far is MySQL. Both PHP and
MySQL are open-source.
PHP provides us different APIs to deal with MySQL server databases: mysql( Original MySQL),
mysqli( MySQL improved) and PDO( PHP Data Objects). The differences between these APIs are shown
on the table given below:
Before we enable do anything with MySQL in PHP, we should first connect to the MySQL server using
specific connection variables. Connection variables consist of the following common parameters, of
which the first one is required while others are optional:-
Host name: This is the name of the server. We can change to whatever host is acting as
MySQL server.
User name: The root user of the system.
User name’s password:- This is encrypted written with the form for security.
The common function in PHP that uses for server connection is mysql_connect( ) or mysqli_connect()
function. This function has the following syntax:- mysql_connect ("hostname", "user", "pass") to
connect with MySQL server. PHP provides mysql_connect function to open a database connection. This
function can take up to five parameters and returns a MySQL link identifier on success, or FALSE on
failure.
The five parameters are the three above and the two below options.
mysql_connect(server,username,passwd,new_link,client_flag);
There are also functions in PHP which have different purposes. For instance,
We issue this connection command with the PHP function called mysql_connect() or mysqli_connect().
As with all of our PHP/MySQL statements, you can either put the information into variables, or leave
them as text in MySQL query as shown below:-:
$host = “localhost”;
$user = “root”;
$pass = “”;
$connect = mysql_connect($host, $user, $pass); Or simply $connect = mysql_connect(“localhost”, “root”, “”);
Or you can also use
$connect=mysqli_connect($host, $user, $pass);
Choosing and Creating the working Database
After establishing a MySQL connection with the code above, you then need to choose which database
you will be using with this connection. This is done with the mysql_select_db(“database-name”) or
<?php <?php
If($connection) If($connection)
$sql=mysql_select_db("test"); }else{
}else{ mysqli_select_db($connection,"test")
?>
mysql_close();//closing connection
Output:
Connected to MySQL
Connected to Database
Closing Query
When you are finished working with query results retrieved with the mysql_query() function,
use the mysql_free_result() function to close the resultset
To close the resultset, pass to the mysql_free_result() function the
variable containing the result pointer from the mysql_query() function
Before you enter data (rows) into a table, you must first define what kinds of data will be stored
(columns).This can be done using Create sql statement.
Syntax:
We are now going to design a MySQL query to summon our table from database test.
<?php <?php
$server=”localhost”; $server=”localhost”;
$dbuser=”root”; $dbuser=”root”;
$dbpassword=””; $dbpassword=””;
$dbname=”test”; $dbname=”test”;
$connection=$mysql_connect($server,$dbuser, $connection=$mysqli_connect($server,$dbuser,
$dbpassword); $dbpassword,$dbname);
if($connection) if($connection)
{ // Create a MySQL table in the selected database name VARCHAR(30), age INT)";
$result=mysql_query($sql2,$connection); else
}else{ }
}else{ ?>
mysql_close();//closing connection
?>
When data is put into a MySQL table it is referred to as inserting data. When inserting data it is
important to remember the exact names and types of the table's columns. If you try to place a 500 word
essay into a column that only accepts integers of size three, you will end up with errors. Inserting data
into a table can be performed using Insert into sql statement.
Syntax:
<html><style>
#style{ display:block;
width:220px;
height:120px;
border:1px solid black;
line-height:30px;
}
#style p{
margin-left:20px;
margin-right:20px;
}</style><body>
<?php
if(isset($_POST['submit']))
{
//getting name and age from the user
$name=$_POST['name'];
$age=$_POST['age'];
// Make a MySQL Connection
$connection=mysql_connect("localhost",
"root", "");
If($connection){
$sql=mysql_select_db("test”);
If($sql){
// Insert a row of information into the table "example"
$sql2="INSERT INTO example(name, age) VALUES('$name', '$age') ";
$result=mysql_query($sql2,$connection) ;
If($result)
echo "Data Inserted!";
else
die(“Data not inserted:”.mysql_error());
} else
die(“Database not selected:”.mysql_error());
}else{
die(“Connection Failed:”.mysql_error());
}
mysql_close();//closing connection
?>
<div id="style"><p><form action="" method="post">
Name:<input type="text" name="name" required="" placeholder="name"><br>
Age:<input type="text" name="age" required="" placeholder="age"><br>
<input type="submit" value="Submit" name="submit"><input type="reset" value="Reset">
Page 124 of 160 Lecture Note
Productivity improvement and center of excellence
</form></p></div></body></html>
If you want to use mysqli, replace mysql connection and data insertion by the following code:
Usually most of the work done with MySQL involves pulling down data from a MySQL database. In
MySQL, data is retrieved with the "SELECT" keyword. Think of SELECT as working the same way as it
does on your computer. If you want to copy some information in a document, you would first select the
desired information, then copy and paste.
Before attempting to retrieve data, be sure that you have created a table that contains some data. In
this example, we will output the first entry of our MySQL "examples" table to the web browser.
Example:
<?php <?php
} else }else{
?>
Output:
When you select items from a database using mysql_query, the data is returned as a MySQL result. Since
we want to use this data in our table we need to store it in a variable. $result now holds the result from
our mysql_query.
The mysql_fetch_array function gets the next-in-line associative/numeric array from a MySQL result.
The mysql_fetch_row function gets the next-in-line numeric array from a MySQL result. The
mysqli_fetch_assoc function gets the next-in-line associative array from a MySQL result. By putting it in
a while loop it will continue to fetch the next array until there is no next array to fetch. This function can
be called as many times as you want, but it will return FALSE when the last associative array has already
been returned.
By placing this function within the conditional statement of the while loop,
We can retrieve the next associative array from our MySQL Resource, $result, so that we
can print out the id, name and age of that person.
We can tell the while loop to stop printing out information when the MySQL Resource
has returned the last array, as False is returned when it reaches the end and this will cause
the while loop to halt.
In our MySQL table "example" there are only three fields: id, name and age. These fields are the keys to
extracting the data from our associative array. To get the id, name and age we use $row[‘id’],
$row['name'] and $row['age'] respectively. The html table tag is used to let the output look better. The
above select statement retrieves everything from the example table. If you want to retrieve specific
record, you can use where clause in the select statement. For example: mysql_query(“select * from
example where id=1”);
Imagine that you have a MySQL table that holds the information of all the employees in your company.
One of the columns in this table is called "Seniority" and it holds an integer value of how many months
an employee has worked at your company. Unfortunately for you, your job is to update these numbers
every month.
You may be thinking that you'll have to open up your MySQL administration tool and edit each entry by
hand. That would take hours. On the other hand, you could master MySQL and have an automated
script that you run each month to get the job done for you.
Syntax
UPDATE table_name SET column1=value, column2=value2,... WHERE some_column=some_value
Example: In the example table we have 4 records. The person whose has an id number of 4 is turned to
17. So change the persons age accordingly.
<?php <?php
If($connection){ If($connection){
}else }else{
} else }
}else{ ?>
die("Connection Failed:".mysql_error());
?>
Output:
SET - The new values to be placed into the table follow SET
WHERE - Limits which rows are affected
Maintenance is a very common task that is necessary for keeping MySQL tables current. From time to
time, you may even need to delete items from your database. Some potential reasons for deleting a
record from MySQL include when: someone deletes a post from a forum.
The DELETE query is very similar to the UPDATE Query. We need to choose a table, tell MySQL to
perform the deletion, and provide the requirements that a record must have for it to be deleted.
Syntax:
<?php <?php
If($connection){ If($connection){
If($result){ }else
} else }
}else{ ?>
die("Connection Failed:".mysql_error());
?>
Output:
Records Deleted!
Nowadays, databases are cardinal components of any web based application by enabling websites to
provide varying dynamic content. Since very sensitive or secret information can be stored in a database,
you should strongly consider protecting your databases.
To retrieve or to store any information you need to connect to the database, send a legitimate query,
fetch the result, and close the connection.
Encryption in PHP
Once an attacker gains access to your database directly (bypassing the web server), stored sensitive data
may be exposed or misused, unless the information is protected by the database itself. Encrypting the
data is a good way to mitigate this threat, but very few databases offer this type of data encryption.
The easiest way to work around this problem is to first create your own encryption package, and then
use it from within your PHP scripts. PHP provides us with different types of encryptions such as: md5,
sha1, hash, crypt, hashed_password etc.
Example:
<?php
$pass="12345678";
echo "md5 encryption $pass=".md5($pass)."<br>";
echo "sha1 encryption $pass=".sha1($pass)."<br>";
echo "hash encryption $pass=".hash('sha1',$pass)."<br>";
echo "crypt encryption $pass=".crypt($pass,$salt);
?>
Output:
In the above example, the salt parameter is optional. However, crypt () creates a weak password
without the salt. Make sure to specify a strong enough salt for better security.
SQL Injection
SQL injection attacks are extremely simple to defend against, but many applications are still vulnerable.
Consider the following SQL statement:
<?php
$sql = "INSERT INTO users (reg_username,reg_password,reg_email) VALUES ('{$_POST['reg_username']}',
'$reg_password', '{$_POST['reg_email']}')";
?>
This query is constructed with $_POST, which should immediately look suspicious.
Assume that this query is creating a new account. The user provides a desired username and an email
address. The registration application generates a temporary password and emails it to the user to verify
the email address. Imagine that the user enters the following as a username:
This certainly doesn't look like a valid username, but with no data filtering in place, the application can't
tell. If a valid email address is given (shiflett@php.net, for example), and 1234 is what the
application generates for the password, the SQL statement becomes the following:
<?php
$sql = "INSERT INTO users (reg_username,reg_password,reg_email) VALUES ('bad_guy', 'mypass', ''),
('good_guy','1234',
'shiflett@php.net')";
?>
Rather than the intended action of creating a single account (good_guy) with a valid email address, the
application has been tricked into creating two accounts, and the user supplied every detail of the
bad_guy account.
While this particular example might not seem so harmful, it should be clear that worse things could
happen once an attacker can make modifications to your SQL statements.
For example, depending on the database you are using, it might be possible to send multiple queries to
the database server in a single call. Thus, a user can potentially terminate the existing query with a
semicolon and follow this with a query of the user's choosing.
MySQL, until recently, does not allow multiple queries, so this particular risk is mitigated. Newer
versions of MySQL allow multiple queries, but the corresponding PHP extension ( ext/mysqli) requires
that you use a separate function if you want to send multiple queries
(mysqli_multi_query() instead of mysqli_query()). Only allowing a single query is safer, because
it limits what an attacker can potentially do.
Filter your data: This cannot be overstressed. With good data filtering in place, most
security concerns are mitigated, and some are practically eliminated.
Quote your data: If your database allows it (MySQL does), put single quotes around all
values in your SQL statements, regardless of the data type.
Escape your data: Sometimes valid data can unintentionally interfere with the format of
the SQL statement itself. Use mysql_escape_string() or mysqli_real_escape_string() an
escaping function native to your particular database. If there isn't a specific
one, addslashes() is a good last resort.
Read (r)
Write (w)
Execute (x)
A stream is a channel used for accessing a resource that you can read from and write to. The input
stream reads data from a resource (such as a file) while the output stream writes data to a resource. In
file operation, we do have the following steps or procedures:-
while (!feof($handle)) {
echo fgets($handle, 1024);
echo '<br />';
} fclose($handle);
Files modes can be specified as one of the six options in this table.
Mode Purpose
r Opens the file for reading only. Places the file pointer at the beginning of the file.
r+ Opens the file for reading and writing. Places the file pointer at the beginning of the file.
Opens the file for writing only. Places the file pointer at the beginning of the file
w
and truncates the file to zero length. If files does not exist then it attempts to create a file.
w+ Opens the file for reading and writing only. Places the file pointer at the beginning of the
file and truncates the file to zero length. If file does not exist then it attempts to create a
file.
Opens the file for writing only. Places the file pointer at the end of the file. If files does not
a
exist then it attempts to create a file.
Opens the file for reading and writing only. Places the file pointer at the end of the file. If
a+
files does not exist then it attempts to create a file.
Once a file is opened using fopen() function it can be read with a function called fread(). This function
requires two arguments. These must be the file pointer and the length of the file expressed in bytes.
The files's length can be found using the filesize() function which takes the file name as its argument and
returns the size of the file expressed in bytes. So here are the steps required to read a file with PHP.
The following example assigns the content of a text file to a variable then displays those contents on the
web page.
$lines = file($filename) :Reads entire file into an array with each line a separate entry in
the array.
$str = file_get_contents($filename) :Reads entire file into a single string.
Page 134 of 160 Lecture Note
Productivity improvement and center of excellence
<?php
$filename = "/home/user/guest/newfile.txt";
$file = fopen( $filename, "w" );
if( $file == false )
{
echo ( "Error in opening new file" );
exit();
}
fwrite( $file, "This is a simple test\n" );
fclose( $file );
?>
<html><head><title>Writing a file using PHP</title></head><body>
<?php
if( file_exists( $filename ) )
{
$filesize = filesize( $filename );
$msg = "File created with name $filename ";
$msg .= "containing $filesize bytes";
echo ($msg );
}
else
echo ("File $filename does not exit" );
?>
</body></html>
If an attempt to open a file fails then fopen returns a value of false otherwise it returns a file pointer
which is used for further reading or writing to that file.
After making a changes to the opened file it is important to close it with the fclose() function. The
fclose() function requires a file pointer as its argument and then returns true when the closure succeeds
or false if it fails.
Note that:-
Page 135 of 160 Lecture Note
Productivity improvement and center of excellence
The file_put_contents() function can also writes or appends a text string to a file, doesn’t
need to use fopen or fclose. If no data was written to the file, the function returns a value
of 0 which can determine if data was successfully written to the file. The FILE_APPEND
constant appends data to any existing contents in the specified filename instead of
overwriting it
<html><body>
<h1>Coast sharing payment system</h1>
<?php
if (isset($_GET['first_name']) && isset($_GET['last_name'])) {
$First = $_GET['first_name'];
$Last = $_GET['last_name'];
$New= $Last . ", " . "$First" . "\n";
$x = "bowlers.txt";
if (file_put_contents($x, $New, FILE_APPEND) > 0)
echo "<p>{$_GET['first_name']} {$_GET['last_name']} has been registered for the payment!</p>";
else
echo "<p>Registration error!</p>";
}
else{
echo "<p>To sign up for the cost sharing system, enter your first
and last name and click the Register button.</p>";
if(!empty($_GET['first_name']))
echo $_GET['first_name'];
if(!$_GET['last_name'])
echo $_GET['last_name'];}
?>
<form action="<?php $_PHP_SELF ?>" method="get" enctype="application/x-www-form-urlencoded">
<p>First Name: <input type="text" name="first_name" size="30" /></p>
<p>Last Name: <input type="text" name="last_name" size="30" /></p>
<p><input type="submit" value="Register" /></p>
</form></body></html >
In general;
Example 3:
Locking Files
To prevent multiple users from modifying a file simultaneously use the flock() function
The syntax for the flock() function is:flock($handle, operation) where operations could be
LOCK_EX, LOCK_NB, etc. The followings are possible file lock functions and their
descriptions.
Copying Files
Use the copy() function to copy a file with PHP
The function returns a value of true if it is successful or false if it is not
The syntax for the copy() function is: copy(source, destination)
For the source and destination arguments:
o Include just the name of a file to make a copy in the current directory, or
o Specify the entire path for each argument
Example:-
if (file_exists(“a.txt”)) {
if(is_dir(“history”)) {
if (copy(“a.txt”,“history\\b.txt”))
echo “<p>File copied successfully.</p>”;
else
echo “<p>Unable to copy the file!</p>”; }
else
echo (“<p>The directory does not exist!</p>”);}
else
echo (“<p>The file does not exist!</p>”);
Example 1:- This is used to demonstrate how gare directory contents of files are displayed.
<?php
$Dir = "C:\\gare";
$DirOpen = opendir($Dir);
closedir($DirOpen);
?>
Example 2:- The following example shows how the content of the current directory opened
$handle = opendir('./');
closedir($handle);
There are also different functions which have different purposes. Some of them are listed below:-
To create directories:-
Use the mkdir() function to create a new directory. To create a new directory pass just the name of the
directory we want to create to the mkdir() function.
Example
mkdir(“bowlers”);
mkdir(“..\\tournament”);
mkdir(“C:\\PHP\\utilities”);
Warning will appear if directory already exists
Example:-
<?php
$Dir = "C:\\Wamp";
if(is_dir($Dir)) {
echo "<table border='1‘ width='100%'>";
echo "<tr><th>Filename</th><th>File Size</th>
<th>File Type</th></tr>";
$DirEntries = scandir($Dir);
foreach ($DirEntries as $Entry) {
echo "<tr><td>$Entry</td><td>" . filesize($Dir . "\\"
. $Entry) . "</td><td>" . filetype($Dir . "\\"
. $Entry) . "</td></tr>";
}
echo "</table>";
}
else echo "<p>The directory does not exist.</p>";
?>
Use the rename() function to rename a file or directory with PHP. This function returns a
value of true if it is successful or false if it is not
Use the unlink() function to delete files and the rmdir() function to delete directories
Pass the name of a file to the unlink() function and the name of a directory to the rmdir() function.
Both functions return a value of true if successful or false if not
o Use the file_exists() function to determine whether a file or directory name exists before we
attempt to delete it
Files are uploaded through an HTML form using the “post” method and enctype attribute with value of
“multipart/form-data,” which instructs the browser to post multiple sections – one for regular form
data and one for the file contents. The file input field creates a browser button for the user to navigate
to the appropriate file to upload
When the form is posted, information for the uploaded file is stored in the $_FILES auto global array.
$_FILES['picture_file']['size']
Example:-The following HTM code below creates an upload form. This form is having method
attribute set to post and enctype attribute is set to multipart/form-data
<html><body><h3>File Upload:</h3>
Select a file to upload: <br />
<form action="<?php $_PHP_SELF ?>" method="post" enctype="multipart/form-data">
<input type="file" name="photo" required=””/><br />
<input type="submit" value="Upload File" />
</form></body></html>
<?php
$filename=$_FILES['photo']['name'];
$filetmpname=$_FILES['photo']['tmp_name'];
$target="uploadedfiles/".$_FILES['photo']['name'];
if(!file_exists("uploadedfiles"))
mkdir("uploadedfiles");
if( copy($_FILES['photo']['tmp_name'], $target) or die( "Could not copy file!"))
echo "file uploded successfully";
else
die("unable to upload!");
?>
<h2>Uploaded File Info:</h2>
<ul><li>Sent file: <?php echo $_FILES['photo']['name']; ?>
<li>File size: <?php echo $_FILES['photo']['size']; ?> bytes
<li>File type: <?php echo $_FILES['photo']['type']; ?>
</ul><a href=<?php echo $target; ?>>Click here to open</a></body></html>
Example2: Inserting the above file to a database: First create a table with two columns such as id(int
auto increment) and file_path (varchar(50)).
<?php
$server="localhost";
$dbuser="root";
$dbpass="";
$dbname="sims";
$connection = mysql_connect($server, $dbuser, $dbpass) or die("Couldn't make connection.");
$db = mysql_select_db($dbname, $connection) or die("Couldn't select database");
?><html><body><h3>File Upload:</h3>
Select a file to upload: <br />
<form action="<?php $_PHP_SELF ?>" method="post" enctype="multipart/form-data">
<input type="file" name="photo" required=""/><br />
<input type="submit" value="Upload File" name="upload" />
Page 142 of 160 Lecture Note
Productivity improvement and center of excellence
</form></body></html>
<?php
if(isset($_POST['upload']))
{
$filename=$_FILES['photo']['name'];
$filetmpname=$_FILES['photo']['tmp_name'];
$target="uploadedfiles/".$_FILES['photo']['name'];
if(!file_exists("uploadedfiles"))
mkdir("uploadedfiles");
//uploading a file into uploadedfiles folder
if(copy($_FILES['photo']['tmp_name'], $target) or die( "Could not copy file!"))
{
//inserting a file to a file table in sims database
$result = mysql_query("INSERT INTO file(file_path) VALUE ('$target')");
if(!$result)
{
echo "File uploaded successfully";
}
//retrieving records from file table
$result = mysql_query("select * from file");
echo "<table border=1><tr><th>Id</th><th>File</th></tr>";
while($row=mysql_fetch_array($result))
{
echo "<tr><th>".$row['id']."</th><th><a href='".$row['file_path']."'>".$row['file_path']."</a></th></tr>";
}
echo "</table>";
}else
echo "Unable to uploaded files";
}
?>
</body></html>
5. Introduction to CMS
A content management system (CMS) is a software package that lets you build a website that can be
quickly and easily updated by your non-technical staff members. Or it is a software program that
makes building and maintaining websites faster and easier. Let’s say you’re using a site without a
CMS—if you want to post an event and have that event show up in five different places on the site,
you have to perform the same activity five separate times on five separate pages. With a CMS, you
only have to post the event once—and any staff member can do it, regardless of their technical
expertise.
Content management systems store the actual content (text and images) in a database. The system
can then automatically pull the content out and show it on the appropriate pages based on rules
you set up in advance. The ways you can organize it, and the types of rules you can use, depend on
how structurally flexible the CMS is. This setup makes it easy for all your content administrators—
the staff members writing and publishing the actual information on the site—to create content
without worrying about technical issues, or even knowing all the places the content should go.
Content Management Systems also separate graphic design from the content itself. This is
accomplished through the use of “themes,” or graphic design layers that control graphic elements,
font and navigation styles, and page layouts for each page on the site. You simply choose a pre-
packaged theme for your site, or create a theme that’s completely customized to your own look and
needs.
Content Management Systems are Open Source. It means the software’s source code is freely
available for everyone to see and change. These open source systems are created and supported by
a community of developers, and can be downloaded without cost. Both their feature sets and their
price tags make open source systems particularly attractive to nonprofits.
Open source content management systems are also designed to be modular. When you download
one you get the set of features a group of developers decided ought to be the base level of
functionality, called the “core” of the system. But there’s a huge range of add-on modules that
provide additional functionality for each CMS, and a rich network of developers working to create
more. If there’s something you want for your website that the core CMS doesn’t already do,
someone else has probably already built what you’re looking for—and, if not you can build your
own, or hire someone to build it for you.
An open source CMS certainly isn’t a cure-all; it may not even be the best option. But for many
organizations, it can offer useful savings in time, money and resources.
The most widely used Content Management Systems in the nonprofit world are:
Drupal
Joomla
Plone
Wordpress
WordPress
WordPress is a great choice for fairly small (a few hundred pages or less), simply arranged
websites. It’s the easiest system to install and understand, and is easy to maintain and update,
putting site setup within reach of anyone with a sense of technical adventure. There are many
predefined graphic themes available; adapting them to your particular needs can range from trivial
—if the theme allows you to select your own color and add your own logo, for instance—to a
relatively straightforward process for someone familiar with HTML and CSS. Updating and
editing images and text is also quite straightforward, and multiple add-on modules are available.
However, WordPress doesn’t scale as intuitively as the other three systems to support complex
sites. For custom content types or article listings displayed based on automatic rules, you’ll need to
try to find a contributed add-on or theme that provides that functionality. There is only limited
support for differentiation of user roles, although add-ons are available to support permissions
based on section or type of content.
Joomla
Joomla is a solid utility player, good for a variety of different situations, and it’s relatively
straightforward to install and set up. There’s a bit of a learning curve to understand how the menus,
site structure and content work and interrelate, but once you’ve got it the system provides a strong
infrastructure for straightforwardly creating useful site structures to support even very large sites.
Add-on modules support a wide variety of functionalities, from directories to shopping carts to
community features, providing a solid base for many different kinds of sites.
While Joomla supports more complex site structures than WordPress, it is not as flexible as Drupal or
Plone. Each piece of content is typically associated with a single page. This makes the system more
straightforward to understand, but can be cumbersome to update and limits very advanced structures
(like structuring a site around a multifaceted taxonomy). It’s not easy, for instance, to create your own
types of content (for example, a directory of state schools that includes key information about those
schools), and then show it in different views on different pages of your site. If you’re not sure what
any of this means, you probably don’t need to worry about it—these are advanced considerations
that won’t apply to the vast majority of sites.
Drupal
Flexible and powerful, Drupal is a great choice for more complex sites. It supports a wide variety of
site structures—with widely used add-ons, you can define very detailed rules as to what content
should be displayed where, and build your own custom content types. It has particularly strong
support for Web 2.0 and community functionality, including user-submitted content. It’s also easy for
content administrators to find and update content—once you have installed a WYSIWYG editor to let
them format the text, which does not come out of the box.
But Drupal’s power comes with complexities. Understanding what the system offers and how to
configure it is more difficult than WordPress or Joomla. The administrative screens for configuring a
site have a huge number of options and settings, making them harder to interpret. And the flexibility
of the system means it’s important to think through the best way to accomplish what you want before
diving in. Most people will want to hire a consultant familiar with Drupal to help them set up a site
rather than trying to go it alone.
Drupal is not as strong as Plone in workflow, and may not be the best choice for organizations that
want to have many different people with different roles and ownership over content.
Plone
Plone is a powerful and robust system suitable for organizations with very complex needs. It’s used by
major newspapers and huge businesses, and it shows. The system offers a huge degree of flexibility
and control, and it supports almost infinitely complicated workflows. And since the content admin
tools are well laid-out and friendly, it’s easy for non-technical administrators to update body text,
images and sidebar areas. Plone’s functionality is as strong, or stronger, than the other three systems
in every area we reviewed except for one—Web 2.0/Community support, where Drupal came out on
top.
Its main downside is in system installation and configuration. Plone requires a customized hosting
setup (as opposed to a typical Linux/Apache/MySQL/ PHP environment). Adding existing graphic
themes and add-in modules, creating custom themes and setting up the site structure is all more
complex than the other systems. Many seasoned technologists will likely want training to understand
the system. Learning Plone to build a single website doesn’t make much sense—you’ll want to hire a
consultant who’s already familiar with it. And since Plone is written in Python (unlike the more
familiar PHP of the other systems), it may be harder to find someone to extend the system through
custom code.
Reading Assignment: