You are on page 1of 159

Productivity Improvement and Center of

Excellence
Computer Science Department
Web Technology Handout

Prepared by: Salim Mulugeta


Productivity improvement and center of excellence

Chapter One

Introduction to Internet Programming

1.1. Basics of Networking& Internet Service


a. Networking
 A network is a group of interconnected systems which share services and interact with each other by
means of a shared communication link.
 These systems can be located anywhere, depending up on types of network
 Network is often classified according to its geographical size.
Classification of Network (based on geographical location):- The most common classifications of
networks based on geographical limitations are:- Local Area Networks (LAN) and Wide Area Networks
(WAN).
Local Area Networks: - Computer network connecting computers and other devices in a workgroup,
department, building or campus. It has geographical limitation because it has fixed size and coverage.

Wide Area Networks (WAN):- these types of networks cover a very wide range of geographical distance. It is
collection of LAN.

Fig 1.1: network architectures

2|Page Lecture note


Productivity improvement and center of excellence

 WAN may be connected through:

o Satellite o leased line


o dial-up o RF link/Radio frequency
Networking Services: -

 Sharing of Input / Output Devices


 Sharing of Software
 Sharing of files residing on different computers
 Communication (Electronic Mail, Chatting, broadcasting)
 Electronic Trading (E-Commerce, EDI etc
 Sharing of Information / Exchange of data through Web Technology over Internet

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.

3|Page Lecture note


Productivity improvement and center of excellence

Figure 1.2 The


growth of Internet

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

1.2. History of Internet


The origins of the Internet reach back to the 1960s when the United States funded research projects of its
military agencies to build robust, fault-tolerant and distributed computer networks.

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

4|Page Lecture note


Productivity improvement and center of excellence

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

Basic Terminology used in Internet Technology


5|Page Lecture note
Productivity improvement and center of excellence

 World Wide Web ( www )  Hyperlink


 Web site  Server Software
 Portal  Browser Software
 Uniform Resource Locater  Protocols like TCP/IP, HTTP,FTP
 Home page  ISP ( Internet Service Provider )

1.3. What is WWW and How Does it work?

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.

Figure 1.3 How WWW works: retrieving a web page

1.4. Web Standards


Web standards are the formal, non-proprietary standards and other technical specifications that define and
describe aspects of the World Wide Web. In recent years, the term has been more frequently associated with the
trend of endorsing a set of standardized best practices for building web sites, and a philosophy of web design and
development that includes those methods

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

7|Page Lecture note


Productivity improvement and center of excellence

potential to enable developers to build rich interactive experiences, powered by


vast data stores, that are available on any device. Web Design and Applications involve
the standards for building and Rendering Web pages, including HTML, CSS, SVG, Ajax, and other
technologies for Web Applications (“WebApps”). These are the major standards for build the web pages.

Web standards, in the broader sense, consist of the following:

 Recommendations published by the World Wide Web Consortium


 Internet standard (STD) documents published by the Internet Engineering Task Force (IETF)
 Request for Comments (RFC) documents published by the Internet Engineering Task Force
 Standards published by the International Organization for Standardization (ISO)
 Standards published by Ecma International (formerly ECMA)
 The Unicode Standard and various Unicode Technical Reports (UTRs) published by the Unicode
Consortium
 Name and number registries maintained by the Internet Assigned Numbers Authority (IANA)

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

8|Page Lecture note


Productivity improvement and center of excellence

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.

9|Page Lecture note


Productivity improvement and center of excellence

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).

Request chain -----------------> UA -----------V------------- O<-------------- response chain

 Common protocols are:-

 IP(Internet Protocol)  SSH (Secure Shell Remote Protocol)


 UDP (User Datagram Protocol)  POP3 (Post Office Protocol 3)
 TCP (Transmission Control Protocol)  SMTP (Simple Mail Transfer Protocol)
 DHCP (Dynamic Host Configuration Protocol)  IMAP (Internet Message Access Protocol)
 HTTP (Hypertext Transfer Protocol)  SOAP (Simple Object Access Protocol)
 FTP (File Transfer Protocol)  PPP (Point-to-Point Protocol)
 Telnet (Telnet Remote Protocol)  RFB (Remote Framebuffer Protocol

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:-

 A browser fetches a web page from a server by a request.


 A request is a standard HTTP request containing a page address.
 A page address looks like: http://www.someone.com/page.htm
Display:-
 All web pages contain instructions on how to be displayed. The browser displays the
page by reading these instructions.
 The most common display instructions are called HTML tags.
e.g. the HTML tag for making a text bold is: <b>text</b>
iii. Web Site:- is a set of interconnected web pages displaying related information on a
specific subject
iv. Uniform Resource Locator (URL)
- Method of accessing Internet Resources, it is specific address of the website.
- It is a uniform ( same through out the world) way to locate a resource (file or document)
on the Internet.
- The URL specifies the address of a file and every file on the Internet has a unique
address.
- The actual URL is a set of four numbers separated by periods. An example of this would
be 202.147.23.8 but as these are difficult for humans to use, addresses are represented in
alphanumeric form that is more descriptive and easy to remember
v. Hyperlink
A hyperlink (or link) is a word, group of words, or image that you can click on to jump to a
new document or a new section within the current document.

The general form of URL has four parts


1. A scheme followed by a colon:- schemes are: http, ftp mailto, file, telnet
2. A server name:- A // followed by the host name (domain name) or IP address of the server
e.g. news server, mail server
3. An optional port number e.g. For telnet is 23, For http is 80
4. A path: - Consisting of folders and/or files.

1|Page Lecture Note


Productivity improvement and center of excellence

URL vs URN vs URI

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>]

e.g. HTTP://mailserv.tech.aau.edu.et/en/mail.html?Sid=test& lang=en

URN- is WHAT. It is name based.


URI- is HOW, WHERE and WHAT.
URI= URL + URN
HOW- is the Protocol.
WHERE- is the location of resource, website, book, etc.WHAT- is the name of the resource.
Because web servers allow for default documents and do not require a scheme to retrieve a
document, the slight difference between an URL and an URN and an URI is hard to tell.
URL is now used as the generic term.
Example
URL - http://www.pierobon.org/iis/reveiw1.html
URN - www.pierobon.org/iis/reveiw1.html#one
URI - http://www.pierobon.org/iis/reveiw1.html#one

1.5. Architecture of the Web


Most of the web structure is client/server architecture.
The Client/Server Architecture

2|Page Lecture Note


Productivity improvement and center of excellence

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

In three-tier architecture, there is an intermediary level, meaning the architecture is generally


split up between:-
1. A client, i.e. the computer, which requests the resources, equipped with a user interface
for presentation purposes
2. The application server (also called middleware), whose task it is to provide the requested
resources, but by calling on another server

3|Page Lecture Note


Productivity improvement and center of excellence

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

Multi-tier architecture (often referred to as n-tier architecture) is a client-server architecture


in which the presentation, the application processing, and the data management are logically
separate processes.

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.

1.6. Http Request/Response


HTTP is a protocol in which information sender and receiver communicate over the Internet.
Http uses a generic message format for transferring entities/messages. HTTP messages consists
requests from client to server and response from the client. It is request/response protocol
between client and server. Both request and response HTTP massages consists:
 Start/status line
 Message body
 Header fields

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.

1.7. Stateless Nature of Http


Http is a stateless protocol. When a client and server interact using Http, the server does not
maintain(store) any information or state about the client. Each interaction is unique and
incapable of remembering the results and data associated with the interactions it governs. Server
has no knowledge of the previous interactions.

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.

1.8. Web Browser Configuration

 A software, application program that enables us to search and find data


 Browse: navigate through and read
 It is a client program
 The first graphical web browser is Mosaic (1993)
 Lynx , the most common Opera, is a text based browser for UNIX shell
Today the most widely used browsers are Netscape Navigator and MS-Internet Explorer.

Chapter Two: Introduction to html/ XHTM


2.1. Hypertext Mark-up Language ( HTML )
5|Page Lecture Note
Productivity improvement and center of excellence

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 iconopen withnotepad
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

<title>Internet and WWW How to Program Headers</title>


</head>
<body>
<h1>Level 1 Header</h1>
<h2>Level 2 header</h2>
<h3>Level 3 header</h3>
<h4>Level 4 header</h4>
<h5>Level 5 header</h5>
<h6>Level 6 header</h6>
</body>
</html>
The output will be:-

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>

8|Page Lecture Note


Productivity improvement and center of excellence

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:

See the following HTML tags and their descriptions:-

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

<body bgcolor="#000000"> <body bgcolor="rgb(0,0,0)"> <body bgcolor="black"> The


lines above all set the background-color to black
 Background :- The background attribute can also specify a background-image for an
HTML page. The value of this attribute is the URL of the image you want to use. If the
image is smaller than the browser window, the image will repeat itself until it fills the
entire browser window. See the following:-
 <body background="clouds.gif"> <body <body
 <background="http://profdevtrain.austincc.edu/html/graphics/clouds.gif">
vi. Text=”,… ”
o To determine the text color for a webpage. The value of the text attribute can be red,
green, blue etc.
vii. Anchor tag attributes: anchor tag , <a>, uses to make hyperlink.
o link=”…”
 To determine the color of hyperlinks on a webpage.
o vlink=”…”
 To determine the color of visited hyperlinks on a webpage
o alink= “ ”
 To determine the color of active hyperlinks on a webpage
There are HTML tags that are used to defines a lot of elements for formatting output, like bold,
italic text, bold-italic, superscript, subscript, small text, strong and so on.
Example:-

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: &lt; or &#60;
 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
&nbsp; 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

Some Other Commonly Used Character Entities:


Result Description Entity Name Entity Number
¢ cent &cent; &#162;
£ pound &pound; &#163;
¥ Yen &yen; &#165;
€ euro &euro; &#8364;
§ section &sect; &#167;
© copyright &copy; &#169;
® registered trademark &reg; &#174;
× multiplication &times; &#215;
÷ division &divide; &#247;
A character entity has three parts: an ampersand (&), an entity name or an entity number, and
finally a semicolon (;). The & means we are beginning a special character, the ; means ending a
special character and the letters in between are sort of an abbreviation for what it's for.
2.4. HTML Links/ Hyperlinks
Links are extremely useful for bringing the user to another page that may be within website, or
may be another website that may useful to others. HTML uses a hyperlink to link to another
document on the Web. A hyperlink (or link) is a word, group of words, or image that can be
clicked on to jump to a new document or a new section within the current document. To create a
link to another document, the hyperlink attribute uses the “href” attribute.
An anchor can point to any resource on the Web: an HTML page, an image, a sound file, a
movie, etc. The HTML code for a link is simple, written as follow:- <a href="url">Link text</a>.

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

<audio src=http://htmlref.com/ch2/music.wav controls></audio> or


<audio>
<bgsound src=http://htmlref.com/ch2/music.wav controls>
</audio>
A complete example is shown here:
<html>
<body>
<h1>Simple Audio Examples</h1>
<h2>wav Format</h2>
<video src=”a.mp4” controls/>
<audio src="http://htmlref.com/ch2/music.wav" controls></audio>
<h2>ogg Format</h2>
<audio src="http://htmlref.com/ch2/music.ogg" controls></audio>
<h2>Multiple Formats and Fallback</h2>
<audio controls autobuffer autoplay>
<source src="http://htmlref.com/ch2/music.ogg" type="audio/ogg">
<source src="http://htmlref.com/ch2/music.wav" type="audio/wav">
<!--[if IE]>
<bgsound src="http://htmlref.com/ch2/music.wav">
<![endif]-->
</audio>
</body>
</html>
 Audio and video can also displayed by a tag called <embed>. It is written as <embed
src=url>…<embed>
2.7. HTML Framesets
With frames, it is possible to display more than one Web page in the same browser window. It
uses to partition a window into independent parts (frames) and used to display different
documents in different frame with single interface.
The <frameset> tag defines how to divide the window into frames. Each frameset defines a set of
rows or columns. The values of the rows/columns indicate the amount of screen area each
row/column will occupy.
Common frameset tags are:
Tag Description
<frameset> Defines a set of frames, container tag type
<frame> Defines a sub window (a frame). It is empty tag type.
Used to display document.
Two types of frameset:-
 Vertical frameset:-demonstrates how to make a vertical frameset with different documents.
<html><frameset cols="25%,50%,25%">
<frame src="framea.htm">
<frame src="frameb.htm">
<frame src="framec.htm">
</frameset>
</html>
 Horizontal frameset:- demonstrates how to make a horizontal frameset with different
documents.
<html><frameset rows="25%,50%,25%">
<frame src="framea.htm">
16 | 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

noresize Noresize Specifies that a frame cannot be resized


scrolling Yes, no Specifies whether or not to display scrollbars in a frame
auto
src URL Specifies the URL of the document to show in a frame

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

IFRAME - Inline Frames


The IFRAME element allows authors to insert a frame within a block of text. Inserting an inline
frame within a section of text is much like inserting an object via the OBJECT element: they

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

<td>row 2, cell 2</td>


</tr>
</table>
HTML code above looks in a browser:
Header 1 Header 2
row 1, cell 1 row 1, cell 2
row 2, cell 1 row 2, cell 2
Tables’ attribute
Border:- If no specify a border attribute to the table, it will be displayed without any borders.
Sometimes this can be useful, but most of the time, we want the borders with value of some
number.
<table border="n">
Headings in a table: demonstrates how to display table headers. <html><body><h4>
Table headers:
 Non break space: to use "&nbsp;" to handle cells that have no content.
 Table with a caption: demonstrates a table with a caption
 Cell padding: to create more white space between the cell content and its borders.
 CELLSPACING: controls the space between table cells. Although there is no official
default, browsers usually use a default of 2.

 CELLPADDING: sets the amount of space between the


contents of the cell and the cell wall. The default is 1. CELLPADDING is usually more
effective than CELLSPACING for
spreading out the contents of the table

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

width pixels Specifies the width of a table


%
Table 2.1 attributes of table

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.

Attribute Value Description


align left Aligns the content in a cell
right
center
justify
char
bgcolor rgb(x,x,x) Specifies a background color for a cell
#xxxxxx
colorname
colspan number Specifies the number of columns a cell should span
height pixels
% Sets the height of a cell
nowrap Nowrap
Specifies that the content inside a cell should not wrap
rowspan Number Sets the number of rows a cell should span
width pixels Deprecated. Use styles instead.
% Specifies the width of a cell
valign top Vertical aligns the content in a table row
middle
bottom

Table attributes of rows and cells

COLSPAN and ROWSPAN


Table cells can span across more than one column or row. Any cell ( <th> or <td> tag) can have
a rowspan="integer " or colspan=" integer" attribute to “span” more than one cell of the table,
that is, place that element's content into an area that would normally be occupied by two or more
cells.
The attributes COLSPAN ("how many across") and ROWSPAN ("how many down") indicate how
many columns or rows a cell should take up.
 COLSPAN number of columns to cover
 ROWSPAN: number of rows to cover
 WIDTH: width of cell
 HEIGHT: height of cell
 BGCOLOR: color of the background
 BORDERCOLOR: color of border around the table
 ALIGN: horizontal alignment of cell contents
 VALIGN: vertical alignment of cell contents
 VSPACE: vertical space between table and surrounding text
 HSPACE: horizontal space between table and surrounding text
 RULES: if there should be internal borders

22 | P a g e Lecture Note
Productivity improvement and center of excellence

Example:- write html code to display the following web page

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%">&hellip;</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>&nbsp;
<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

Different types of html lists:-


 Unordered Lists:- An unordered list starts with the <ul> tag. Each list item starts with
the <li> tag. The list items are marked with bullets (typically small black circles). The
“type” attribute can be used to specifies the style of the bullet points of the list items, its
value includes disc, square and circle.
Example:-
<html>
<body>
<h4>Disc bullets list:</h4>
<ul type="disc">
<li>Apples</li>
<li>Bananas</li>
<li>Lemons</li>
<li>Oranges</li <html><body>

 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.

Using Buttons, Checkboxes and Selection Lists


Radio Buttons:-
 Radio buttons are a popular form of interaction. we may have seen them on quizzes,
questionnaires, and other web sites that give the user a multiple choice question. Below are a
couple attributes you should know that relate to the radio button.
o Value: specifies what will be sent if the user chooses this radio button. Only one
value will be sent for a given group of radio buttons.
o Name: defines which set of radio buttons that it is a part of.
 Written as <input type="radio" /> defines a radio button. Radio buttons let a user select
ONLY ONE of a limited number of choices: see example
<form>
<input type="radio" name="sex" value="male" /> Male<br />
<input type="radio" name="sex" value="female" /> Female

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>

The followings are some of the common select attributes:-


Attribute Value Description
disabled Disabled Specifies that a drop-down list should be disabled
multiple Multiple Specifies that multiple options can be selected
name Name Specifies the name of a drop-down list
size Number Specifies the number of visible options in a drop-down list

Text Area Tags:-


 It uses to create an area in our form, where visitors can enter longer answers such as
entering an abstract or essay. Here, visitors can enter up to 32, 700 characters in a text
area.
 It is aritten as <textarea>…..</textarea> to create input area
 The text area tag has several attributes such as name, rows, cols and wrap.
 See the following example:-
<textarea name=”abstract” rows=”10” cols=”70” wrap=”wrap”>
</textarea>
Where

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.

It uses attributes as:-


 The NAME attribute identifies the text field to the server-side program.
 VALUE
For security reasons, this attribute is ignored; only the end user can specify a filename.
Otherwise, a malicious HTML author could steal client files by specifying a filename and then
using JavaScript to automatically submit the form when the page is loaded.

 ONCHANGE, ONSELECT, ONFOCUS, and ONBLUR


These attributes are used by browsers that support JavaScript to specify the action to take when
the mouse leaves the textfield after a change has occurred, when the user selects text in the
textfield, when the textfield gets the input focus, and when the textfield loses the input focus,
respectively.
Example:-
<FORM ACTION="http://localhost:8088/SomeProgram"
ENCTYPE="multipart/form-data" METHOD="POST">
Enter data file below:<BR>
<INPUT TYPE="FILE" NAME="fileName">
<input type="submit" value="upload the file" />

</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

<input type="submit" value="upload the file" />


</body>
</html>
Exercise: Test the output of the following codes
1.
<html>
<body>
<form action="<?php $_PHP_SELF ?>" method="POST">
FName: <input type="text" name="fname" />
LName: <input type="text" name="lname" />
GName: <input type="text" name="gname" />
Department: <input type="text" name="dname" />
College: <input type="text" name="cname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>

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

4.2 CSS Syntax


A CSS rule has two main parts: a selector, and one or more declarations. The selector is normally
the HTML element we want to style. Each declaration consists of a property and a value. The
property is the style attribute we want to change. Each property has a value, which is written as
follows:-

i.eselector {property: value}


The selector is normally the HTML element/tag we wish to define, the property is the attribute
we wish to change, and each property can take a value. The property and value are separated by a
colon, and surrounded by curly braces: body {color: black}
Note: If the value is multiple words, put quotes around the value: p {font-family: "sans serif"}
Note: To specify more than one property, we must separate each property with a semicolon. The
example below shows how to define a center aligned paragraph, with a red text color:
p {text-align:center;color:red}
To make the style definitions more readable, it is better to describe one property on each line,
like this:
p
{
text-align: center;
color: black;
font-family: arial
font-size:12px;
}
Grouping
We can group selectors. Separate each selector with a comma. In the example below we have
grouped all the header elements. All header elements will be displayed in green text color:
h1,h2,h3,h4,h5,h6,table
{
color: green;
}
4.3 CSS Comments
Comments are used to explain code, and may help us when we edit the source code at a later date. CSS
comments, like other programming languages comments, are ignored by browsers.
A CSS comment begins with /* and ends with */ like this:
/*This is a comment*/
p{
text-align:center;
/*This is another comment*/
34 | 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

4.5 Styling Backgrounds

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

{ background-image: url('smiley.gif');background-repeat: no-repeat; background-


attachment:fixed;background-position: 50px 100px;}
</style></head><body>
<p><b>Note:</b> For this to work in Mozilla, the background-attachment property must
be set to "fixed".</p></body></html>
Background Repeat
We can set if an image set as a background of an element is to repeat (across=x and/or down=y) the
screen using the background-repeat property.background-repeat: value;
Values:
repeat
repeat-x
repeat-y
Example:-
<html>
<head>
<style type="text/css">body { background-image: url('smiley.gif');background-repeat:
no-repeat; background-attachment:fixed;background-position: 30% 20%; }
body {background-color: yellow}
h1 {background-color: #00ff00}
h2 {background-color: transparent}
p {background-color: rgb(250,0,255)}
{ background-image:url('bgdesert.jpg')}
{ background-image:url('smiley.gif');background-repeat:no-repeat;background-
attachment:fixed; background-position:center; }
</style>
</head><body> 102
<h1>This is header 1</h1>
<h2>This is header 2</h2>
<p>This is a paragraph</p>
<p><b>Note:</b> For this to work in Mozilla, the background-attachment property must
be set to "fixed".</p></body></html>
List multiple selectors (comma separated) before the
property list to apply the properties to multiple tags.
• H1, H2, H3, H4, H5, H6 { color: purple; }
H1 { color: purple; background: yellow; }
H2 { color: purple; background: white; }
H3 { color: blue; background: white; }
H4 { color: blue; background: yellow }
• Or
H1, H2 { color: purple; }
H3, H4 { color: blue; }
H1, H4 { background: yellow; }
38 | P a g e Lecture Note
Productivity improvement and center of excellence

H2, H3 { background: white; }


4.6 Styling Text
Color:-writtenasfollowing:color: value;
Possible values are
color name – example: red, black…
hexadecimal number – example: #ff0000, #000000
RGB color code – example: rgb(255, 0, 0), rgb(0, 0, 0)
Example:-
<html>
<head>
<style type="text/css"> h1 {color: #00ff00} h2 {color: #dda0dd}
p {color: rgb(0,0,255)}</style></head>
<body><h1>This is header 1</h1><h2>This is header 2</h2><p>This is a
paragraph</p>
</body></html>
Letter Spacing: can beadjust the space between letters in the following manner. Setting the value to 0,
prevents the text from justifying. We can use negative values.Written asletter-spacing: value;
Possible values arenormal or length.
<head>
<style type="text/css">h1 {letter-spacing: -3px}h4 {letter-spacing: 0.5cm}
</style></head><body><h1>This is header 1</h1><h4>
This is header 4</h4></body></html>
Text Align:- we can align text with the following:text-align: value;
Possible values are
left
right
center
justify
Examples:
<html>
<head>
<style type="text/css">h1 {text-align: center}h2 {text-align: left}
h3 {text-align: right}
</style></head>
<body><h1>This is header 1</h1><h2>This is header 2</h2><h3>This is header
3</h3></body></html>
Text Decoration:-text can be declared with the following:
text-decoration: value;
Possible values are
none
underline
overline

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

Text Direction:-we can sets the text direction


direction: value;
Possible values areltr or rtl
Example:-
<html>
<head>
<style type="text/css">
div.one {direction: rtl} div.two {direction: ltr} </style></head>
<body>
<div class="one">Some text. Right-to-left direction.</div>
<div class="two">Some text. Left-to-right direction.</div></body></html>
Text Transform:-we can control the size of letters in an (X)HTML element with the following:
text-transform: value;
Possible values are
none
capitalize
lowercase
uppercase
White Space
Whitespace can be controlled in an (X)HTML element with the following:white-space: value;
Possible values are
Example:-
<html><head><style type="text/css">
p { word-spacing: 30px}</style></head>
<body><p>This is some text. This is some text.</p>
</body></html>
Word Spacing:- to adjust the space between words in the following manner. we can use negative
values.
word-spacing: value;
Possible values are
normal
length
Line height
We can set the distance between lines in the following way:
line-height: value;
Possible values are
normal
number
length
%
41 | 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

<body><p class="normal">This is a paragraph</p><p class="small">This is a


paragraph</p>
</body></html>
4.8 Styling Links
Below are the various ways we can use CSS to style links.
a:link {color: #009900;}
a:visited {color: #999999;}
a:hover {color: #333333;}
a:focus {color: #333333;}
a:active {color: #009900;}
Remark: we must declare the a:link and a:visited before we declare a:hover. Furthermore, we
must declare a:hover before we can declare a:active as shown above.
Using the above code will style all links on the web page, unless we declare a seperate set of
link styles for a certain area of WebPages.
4.9 Styling Lists
List Style:-it is possible to control the appearance of ordered and unordered lists in one declaration with
the list-style property
list-style: value valuevalue;
Values:
image
position
type
Or we can control them individually
List Style Image:-we can use an image for the bullet of unordered lists with the list-style property
list-style-image: url(path_to_image.gif, jpg or png);
If we use an image, it is a good idea to declare the list-style-type also in case the user has images turned
off.
List Style Position
We can control the position of ordered and unordered lists with the list-style-position property
list-style-position: value;
Values
 inside
 outside
List Style Type
We can control the type of bullet ordered and unordered lists use with the list-style-type property
list-style-type: value;

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

 upper-latin  armenian  Georgian


4.10 Styling Tables
Table Borders
To specify table borders in CSS, use the border property. The example below specifies a black
border for table, th, and td elements:
table, th, td{
border: 1px solid black;
}
Notice that the table in the example above has double borders. This is because both the table, th,
and td elements have separate borders.
Collapse Borders
The border-collapse property sets whether the table borders are collapsed into a single border or
separated:
table{
border-collapse:collapse;
}
table,th, td{
border: 1px solid black;
}
Table Width and Height
Width and height of a table is defined by the width and height properties. The example below
sets the width of the table to 100%, and the height of the th elements to 50px:
table{
width:100%;
}
th{
height:50px;
}
Table Text Alignment
The text in a table is aligned with the text-align and vertical-align properties. The text-align
property sets the horizontal alignment, like left, right, or center:
td{
text-align:right;
}
The vertical-align property sets the vertical alignment, like top, bottom, or middle:
td {
height:50px;
vertical-align:bottom;
}
Table Padding

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

<div class="big">Big bold text.</div>


<span class="big">Normal text - class not applied.</span>
Example: in a paragraph, let we put this:
<span class="greenboldtext">sentence</span>
Then in the CSS file, add this style selector:
.greenboldtext{
font-size: small;
color: #008080;
font-weight: bold;
}
Pseudo Classes
Pseudo-classes are classes that define tag states. Most commonly, these are used to make link styles
change when the mouse pointer hovers over a hyperlink, hyperlink is clicked, etc.
Pseudo class Link state

a:link Normal link

a:visited Already visited link

a:hover Mouse hovers the link

a:active User is clicking on the link

Table pseudo classes


Example:
a:link {
text-decoration: underline;
font-weight: normal;
color: #003300;
}
a:visited {
text-decoration: underline;
font-weight: normal;
color: #999999;
}
a:hover {color:green}

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

border: 1px solid blue;


background: red;
}

Example: group declaration of css


h1, .legs, #snout{
font-size: 20pt;}
4.12 CSS Box Model
In CSS, the term box model is used when talking about design and layout. The CSS box model is
essentially a box that wraps around HTML elements, and it consists of: margins, borders, padding, and
the actual content.
The box model allows us to place a border around elements and space elements in relation to other
elements. The image below illustrates the box model.

Figure 3.1 CSS box model


Explanation of the different parts:
 Margin - Clears an area around the border. The margin does not have a background color, and it
is completely transparent
 Border - A border that lies around the padding and content. The border is affected by the
background color of the box
 Padding - Clears an area around the content. The padding is affected by the background color of
the box
 Content - The content of the box, where text and images appear
In order to set the width and height of an element correctly in all browsers, we need to know how the box
model works.
4.13 CSS Border
Border
We can set the color, style and width of the borders around an element in one declaration by using the
border property:-
border: 1px solid #333333;
Values:
color stylewidth
Or we can set each property individually

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

Figure different border styles

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.

Property Description Values


Margin A shorthand property for setting the margin-top, margin-right
margin properties in one declaration margin-bottom, margin-left
margin-bottom Sets the bottom margin of an element Auto, length or %
margin-left Sets the left margin of an element Auto, length, or %
margin-right Sets the right margin of an element Auto, length, or %
margin-top Sets the top margin of an element Auto, length or %
Table CSS margin
4.15 CSS Padding
The padding clears an area around the content (inside the border) of an element. The padding is affected
by the background color of the element.

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.

Property Description Values


Padding A shorthand property for setting all the padding padding-top
properties in one declaration padding-right
padding-bottom
padding-left

padding-bottom Sets the bottom padding of an element Length and %

padding-left Sets the left padding of an element Length and %


padding-right Sets the right padding of an element Length and %
padding-top Sets the top padding of an element Length%
Table CSS padding
<html>

Page 51 Lecture Note


Productivity improvement and center of excellence

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!

Page 52 Lecture Note


Productivity improvement and center of excellence

 JavaScript can put dynamic text into an HTML page - A JavaScript


statement like this: document.write("<h1>" + name + "</h1>") can write a
variable text into an HTML page
 JavaScript can react to events - A JavaScript can be set to execute when
something happens, like when a page has finished loading or when a user
clicks on an HTML element
 JavaScript can read and write HTML elements - A JavaScript can read
and change the content of an HTML element
 JavaScript can be used to validate data - A JavaScript can be used to
validate form data before it is submitted to a server. This saves the server
from extra processing
4.3. Running the JavaScript
Any time including JavaScript in an HTML document, we must enclose those lines
inside a <SCRIPT>...</SCRIPT> tag pair. These tags alert the browser program
to begin interpreting all the text between these tags as a script. Because other
scripting languages (such as Microsoft’s VBScript) can take advantage of these
script tags, we must specify the precise name of the language in which the enclosed
code is written. Therefore, when the browser receives this signal that our script
uses the JavaScript language, it employs its built-in JavaScript interpreter to handle
the code.
JavaScript is case-sensitive. Hence, we must enter any item in our script that uses a
JavaScript word with the correct uppercase and lowercase letters. HTML tags
(including the <SCRIPT> tag) can be in the case of our choice, but everything in
JavaScript is case-sensitive. JavaScript should be put between the following:-
<SCRIPT LANGUAGE=”JavaScript”>
//your script here
</SCRIPT>
Or

Page 53 Lecture Note


Productivity improvement and center of excellence

<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

Javascript can come at different places. There is a flexibility given to include


JavaScript code anywhere in an HTML document. But, the following are the most
preferred ways to include JavaScript in an HTML file.
 Script in <head>...</head> section.
 Script in <body>...</body> section.
 Script in <body>...</body> and <head>...</head> sections.
 Script in and external file and then include in <head>...</head> section.
 Wherever we use/ define a JavaScript block in our web page, simply use the
following block of HTML.
<script type=”text/JavaScript”>
// Your script goes here.
</script>
 We can place these script blocks anywhere on the page that we wish, there are
some rules and conventions however.
 But, for external external File, use the SRC attribute of the <SCRIPT> tag to
call JavaScript code from an external text file.

Page 54 Lecture Note


Productivity improvement and center of excellence

 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>

Scripts in both <head>…..</head> and <body>…..</body> tags


We can place an unlimited number of scripts in our document, so we can have
scripts in both the body and the head section.
4.4. Input-Output in Java/ Message Boxes
In JavaScript, input-output can be done in different ways:
 document.write method writes a string to the web page. Anything between
double quotes will be displayed as it is in the web page. However, if there is
something out of quotes, it is evaluated as expression and the result will be sent
to the web page.
 The alert method is produces a browser alert box. These are incredibly useful
for debugging and learning the language. However, they are not good way to
communicate with the users. An alert box is often used if we want to make sure
information comes through to the user. When an alert box pops up, the user will
have to click "OK" to proceed. The Syntax is
window.alert("sometext"); or simply write as alert(“some text”)
Example:-
<html>
<head>
<script language="javascript">
document.write("This message is written by JavaScript");
function message()
{
alert("message to display");
}
</script>
</head>
Page 56 Lecture Note
Productivity improvement and center of excellence

<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>

Page 57 Lecture Note


Productivity improvement and center of excellence

 The Page Printing:- JavaScript helps us to implement this functionality using


print function of window object. The JavaScript print function window.print()
will print the current web page when executed. We can call this function
directly using onclick event as follows:
<html>
<head>
<script type="text/javascript">
</script>
</head>
<body>
<form>
<input type="button" value="Print" onclick="window.print()">
</form>
</body>
</html>

4.5. Working with Variables and Data


In JavaScript, a value can be one of several types as shown bellow:-
Type Example Description
String “John” a series of characters inside quotation marks
Number 4.5 any number not inside quotes
Boolean True a logical true or false
Null Null completely devoid of any value
Object a software thing that is defined by its properties
and methods
Table JavaScript data types
i. Declaring Variables
To declare variable, we use the var keyword, followed by the name we want to
give to the variable. JavaScript variables can be declared with the var keyword as
var variablename;
To declare a new variable called myAge, the JavaScript statement is var myAge;
Variable names obey number of restrictions (rules).
Page 58 Lecture Note
Productivity improvement and center of excellence

 Don’t use any reserved keyword as a variable name.


 A variable name cannot contain space characters. Therefore, one-word variable
names are fine. For example, the followings are invalid:- var my age; var my Age;
 Variable names should avoid all punctuation symbols except for the underscore
character. Also, the first character of a variable name cannot be a numeral.
 To put together, a variable name can contain letters of the alphabet, both capital and
small, number and _ (underscore). Still, the name should start with letters of the
alphabet, or _, not digits
Example: see the following correct variable declaration,
var firstName;
var he89;
var TH_;
Example: Wrong variable names:
var first name; //space not allowed
var 89he; //can’t start with digit
var TH.; //punctuation mark not allowed
ii. Assigning Values to Variables
After the declaration shown above, the variables are empty which means they
have no data values yet. After declaring a variable, it is possible to assign a
value to it by using equal sign (=) as follows:
var myAge;
myAge = 25;
However, we can also assign values to the variables as: var age=5;
iii. Assigning Values to Undeclared Variables
To assign values to variables that have not yet been declared, the variables
will automatically be declared. These statements:
age=5;
The above statements have the same effect as:

Page 59 Lecture Note


Productivity improvement and center of excellence

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:-
&&, ||

Page 60 Lecture Note


Productivity improvement and center of excellence

4.7. Java Script Statements


A. Working with Conditional Statements
Conditional statements are used to perform different actions based on different
conditions. Broadly, there are two ways to execute code conditionally:
 If statement
 switch statement
i. If condition/if -----else condition:- The simplest program decision is to follow a
special branch or path of the program if a certain condition is true. Formal
syntax for this construction follows:
if (condition) {
statement[s] if true
}
If the condition evaluates to true, then one or more statements inside the curly
braces execute before continuing on with the next statement after the closing brace.
If the condition evaluates to false, then the statements inside the curly brace are
ignored and processing continues with the next statement after the closing brace.
The formal syntax definition for an if...else construction is as follows:
if (condition) {
statement(s) if true
}
[else if(condition){
statement(s) if true
}]
[else {
statement(s) if false
}]
Where [ ] indicates optional parts of the JavaScript code.
Example:-
<script type="text/javascript">
var book = "maths";
if( book == "history" ){
document.write("<b>History Book</b>");
}else if( book == "maths" ){
document.write("<b>Maths Book</b>");
}else{
document.write("<b>Unknown Book</b>");}
Page 61 Lecture Note
Productivity improvement and center of excellence

</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)
{

Page 62 Lecture Note


Productivity improvement and center of excellence

case 'A': document.write("Good job<br />");


case 'B': document.write("Pretty good<br />");
case 'C': document.write("Passed<br />");
case 'D': document.write("Not so good<br />");
case 'F': document.write("Failed<br />");
default: document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
</script>

B.Working with Loops


A loop is a set of commands that executes repeatedly until a specified condition is
met, and JavaScript supports loop like for, do while, and while loop statements. In
addition, we can use the break and continue statements within loop statements.
i. for Loop
A for loop repeats until a specified condition evaluates to false. A syntax of for
statement is:-
for ([initialization]; [condition]; [increment]){ Statement(s)}
Example :-
<html> <body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
if ( i = = 3)
{
break;
}
document.write ("The number is " + i); document.write ("<br />");
}
</script>
</body>
</html>
ii. do...while Statement
Page 63 Lecture Note
Productivity improvement and center of excellence

The do...while statement repeats until a specified condition evaluates to false. A


do...while statement is written as follows:
do{
statement
}while (condition);
statement executes once before the condition is checked. If condition is true, the
statement executes again. At the end of every execution, the condition is checked.
When the condition is false, execution stops and control passes to the statement
following do...while.
Example: the do loop iterates at least once and reiterates until i is no longer less
than 5.
i=1;
do
{
i + = 1;
document.write (i);
} while (i < 5);

iii. while Statement


A while statement executes its statements as long as a specified condition evaluates
to true. A while statement looks as follows:
while (condition){
statement
}
The condition test occurs before statement in the loop are executed. If the
condition returns true, statement is executed and the condition is tested again. If the
condition returns false, execution stops and control is passed to the statement
following while.
<html>
<body>

Page 64 Lecture Note


Productivity improvement and center of excellence

<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

var counter = 100, sum = 0;


for (var i = 0; i <= counter; i++)
{ if(i==60 || i==70 || i==80)
continue;
sum = sum + i;
}
document.write(“the sum is ” + sum);
</script>

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>

4.8. JavaScript Functions


Functions are one of the fundamental building blocks in JavaScript. A function is a
set of statements that performs a specific task. To use a function, we must first
define it; then the script can be called it.
In function definition, it consists of the function keyword, followed by:
 The name of the function.
 A list of arguments to the function, enclosed in parentheses and separated by
commas.
The JavaScript statements that define the function, enclosed in curly braces, { }.
The statements in a function can include calls to other functions defined in the
current application. The syntax to define function:
function functionName ( [parameter1]...[,parameterN] ) {
statement[s]
}
Function names have the same restrictions as variable names.
Example: the following code defines a simple function named square:
function square(number) {
return number * number;
}
The function square takes one argument, called number. The function consists of
one statement that indicates to return the argument of the function multiplied by
itself. The return statement specifies the value returned by the function.
 Function Parameters:- Functions receive parameter values from the calling
statement. Parameters (also known as arguments) provide a mechanism for
“handing off” a value from one statement to another by way of a function
call. If no parameters occur in the function definition, both the function

Page 68 Lecture Note


Productivity improvement and center of excellence

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>

Page 69 Lecture Note


Productivity improvement and center of excellence

4.9. Form Processing and Validation


Forms are widely used on the Internet. The form input is often sent back to the
server or mailed to a certain e-mail account. With the help of JavaScript the form
input can easily be checked before sending it over the Internet. It is sent only if the
input is valid.
Form data that typically are checked by a JavaScript could be:
 has the user left required fields empty?
 has the user entered a valid e-mail address?
 has the user entered a valid date?
 has the user entered text in a numeric field?
In the name field, we will receive an error message when nothing is entered. Age
is number and we expect a positive number only. If user enters characters which
are not number, or negative value, it is not valid age. So the script should check
this and determine its validity.
The email field is a little bit more sophisticated. It shouldn’t work if there is no @
symbol in the email because valid email addresses contain that symbol. The criteria
for accepting the input as a valid e-mail address is the @. The person may enter
wrong emails which could pass as valid but this is the least check we could do.

Page 70 Lecture Note


Productivity improvement and center of excellence

Figure form validation


Example: a script that creates and validates the above form:
<html>
<head>
<script language="JavaScript">
function check( )
{
if (form1.urname.value = = "")
alert("Please enter a string as your name!");
else
alert("Hi " + form1.urname.value + "! Name ok!");
if(form1.age.value < 0 || form1.age.value = = "")
alert("Age should be number and greater than 0.");
else
alert("Age is ok");
if (form1.email.value = = "" || form1.email.value.indexOf('@', 0) = = -1)
alert("No valid e-mail address!");
else
alert("Email OK!");
if(form1.urmessage.value = = "")
alert("No message written");
else
alert("Message ok");
}
</script>
</head>
<body>
<h2> <u> Form validation </u> </h2>
<form name="form1">
Enter your name: <input type="text" name="urname"> <br>
Enter your age: <input type="text" name="age"> <br>
Enter your e-mail address: <input type="text" name="email"> <br>
Write message: <textarea name="urmessage" cols=40
rows=10></textarea><br><br>
<input type="button" name="validate" value="Check Input"
onClick="check( )">
Page 71 Lecture Note
Productivity improvement and center of excellence

</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:

<html> (validate_email(email,"Not a valid e-


<head> mail address!")==false)
<script type="text/javascript"> {email.focus();return false;}
function validate_email(field,alerttxt) }}
{ </script>
with (field) </head>
{ <body>
apos=value.indexOf("@"); <form action="submitpage.htm"
dotpos=value.lastIndexOf("."); onsubmit="return
if (apos<1||dotpos-apos<2) validate_form(this);"
{alert(alerttxt);return false;} method="post">
else Email: <input type="text"
return true; name="email" size="30">
}} <input type="submit"
function validate_form(thisform) value="Submit">
{ </form>
with (thisform) </body>
{ </html>
if

4.10. JavaScript Animation


It is possible to use JavaScript to create animated images. The trick is to let a
JavaScript change between different images on different events. In the following
example we will add an image that should act as a link button on a web page. We
Page 72 Lecture Note
Productivity improvement and center of excellence

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.

Page 73 Lecture Note


Productivity improvement and center of excellence

 clearTimeout(setTimeout_variable) - This function calls clears any timer


set by the setTimeout() functions.

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>

Here is the explanation of the above example:


 We are using JavaScript function getElementById() to get a DOM object and
then assigning it to a global variable imgObj.

Page 74 Lecture Note


Productivity improvement and center of excellence

 We have defined an initialization function init() to initialize imgObj where


we have set its position and left attributes.
 We are calling initialization function at the time of window load.
 Finally, we are calling moveRight() function to increase left distance by 10
pixels. You could also set it to a negative value to move it to the left side
Automated Animation:
In the above example we have seen how an image moves to right with every click.
We can automate this process by using JavaScript function setTimeout() as
follows:

<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>

Page 75 Lecture Note


Productivity improvement and center of excellence

<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>

Page 76 Lecture Note


Productivity improvement and center of excellence

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.

Page 77 of 160 Lecture Note


Productivity improvement and center of excellence

Chapter Five
1. Server Side Scripting Basics

1.1.Overview of Web Scripting


Web page is a document, typically written in HTML that is almost always accessible via HTTP. Or pages
on which, information is displayed on the web. It can be static or dynamic.

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.

1.2.Introduction to server-side scripting


Server-side scripting is a web server technology in which a user's request is fulfilled by running a script
directly on the web server to generate dynamic web pages. It is usually used to provide interactive web
sites that interface to databases or other data stores. The primary advantage of server-side scripting is
the ability to highly customize the response based on the user's requirements, access rights, or queries
into data stores. From security point of view, server-side scripts are never visible to the browser as these
scripts are executed on the server and emit HTML corresponding to user's input to the page.

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

Page 78 of 160 Lecture Note


Productivity improvement and center of excellence

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:

i. Client to server: Customer-enter information as request.


ii. Server to client: Web pages can be assembled from back end-server to give output.

A server side script can:-

 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

The main focus here is PHP.

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

What you need to get started


Hopefully you have established a basic idea of what server-side scripting is, and when you should use it.
Next you need some basic requisites to be able to write and execute scripts. Basically you need:

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.

1.3.PHP Basic Syntax


The PHP parsing engine needs a way to differentiate PHP code from other elements in the page. The
mechanism for doing so is known as ‘escaping to PHP.’ There are four ways to do this:

i. Canonical PHP tags


The most universally effective PHP tag style is:

<?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:

 Choose the --enable-short-tags configuration option when building PHP.


 Set the short_open_tag setting in php.ini file to on. This option must be disabled to parse
XML with PHP because the same syntax is used for XML tags.
iii. ASP-style tags: ASP-style tags mimic the tags used by Active Server Pages to delineate
code blocks. ASP-style tags look like this:
<%
Your PHP code
here
%>
To use ASP-style tags, we should set the configuration option
in your php.ini file.

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.

Page 81 of 160 Lecture Note


Productivity improvement and center of excellence

 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.

The general format of the print statement is as follows:

print outputstatement;
print(outputstatement);
Example: different ways of echo and print
echo 123; //output: 123

echo “Hello World!”; //output: Hello world!

echo (“Hello World!”); //output: Hello world!

echo “Hello”,”World!”; //output: Hello World!

echo Hello World!; //output: error, string should be enclosed in quotes

print (“Hello world!”); //output: Hello world!


The command print is very similar to echo, with two important differences:
 Unlike echo, print can accept only one argument.
 Unlike echo, print returns a value, which represents whether the print statement
succeeded.
It is possible to embed HTML tags in echo or print statements. The browser will parse and interpret
them like any tag included in HTML page and display the page accordingly.
Table1.1 Using echo/print statements
echo/print statement PHP output web page display
echo “Hello World”; HelloWorld! HelloWorld!

echo “Hello”; HelloWorld! HelloWorld!


echo “World!”;
echo “Hello\nWorld!”; Hello Hello World!
World!
echo “Hello<br>World!”; Hello<br>World Hello
World!
echo “<u> <i> Hello world!</i></u>”; <u>Hello world!</u> Hello world!

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

Page 82 of 160 Lecture Note


Productivity improvement and center of excellence

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";
?>

Page 83 of 160 Lecture Note


Productivity improvement and center of excellence

1.6.Working with Variables


A variable is a special container that can be defined to hold a value such as number, string, object, array,
or a Boolean. The main way to store information in the middle of a PHP program is by using a variable.
Here are the most important things to know about variables in PHP.
 All variables in PHP are denoted with a leading dollar sign ($).
 The value of a variable is the value of its most recent assignment.
 Variables are assigned with the = operator, with the variable on the left-hand side and the
expression to be evaluated on the right.
 Variables can, but do not need, to be declared before assignment.
 Variables in PHP do not have intrinsic types - a variable does not know in advance
whether it will be used to store a number or a string of characters.
 Variables used before they are assigned have default values.
 PHP does a good job of automatically converting types from one to another when
necessary.

Variable Naming Rules

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.

The correct way of declaring a variable in PHP is:

$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:

 It evaluates to FALSE in a Boolean context.


 It returns FALSE when tested with IsSet() function.

Strings:

They are sequences of characters, like "PHP supports string operations". Following are valid examples of
string

$string_1 = "This is a string in double quotes";


$string_2 = "This is a somewhat longer, singly quoted string";
$string_39 = "This string has thirty-nine characters";
$string_0 = ""; // a string with zero characters
Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables with
their values as well as specially interpreting certain character sequences.

<? php
$variable = "name";
$literally = 'My $variable will not print!\\n';
print($literally);
$literally = "My $variable will print!\\n";
print($literally);

Page 85 of 160 Lecture Note


Productivity improvement and center of excellence

?>
This will produce the following result:

My $variable will not print!\n


My name will print
There are no artificial limits on string length - within the bounds of available memory, you ought to be
able to make arbitrarily long strings.

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.

The escape-sequence replacements are:

 \n is replaced by the newline character


 \r is replaced by the carriage-return character
 \t is replaced by the tab character
 \$ is replaced by the dollar sign itself ($)
 \" is replaced by a single double-quote (")
 \\ is replaced by a single backslash (\)

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.

Page 86 of 160 Lecture Note


Productivity improvement and center of excellence

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

PHP Local Variables


A variable declared in a function is considered local; that is, it can be referenced solely in that
function. Any assignment outside of that function will be considered to be an entirely different variable
from the one contained in the function:

<?
$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.

PHP Function Parameters


PHP Functions are covered in detail in PHP Function Chapter. In short, a function is a small unit of
program which can take some input in the form of parameters and does some processing and may
return some value.

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;

Page 87 of 160 Lecture Note


Productivity improvement and center of excellence

}
$retval = multiply (10);
Print "Return value is $retval\n";
?>
This will produce the following result.

Return value is 100

PHP Global Variables


In contrast to local variables, a global variable can be accessed in any part of the program. However, in
order to be modified, a global variable must be explicitly declared to be global in the function in which it
is to be modified. This is accomplished, conveniently enough, by placing the keyword GLOBAL in front of
the variable that should be recognized as global. Placing this keyword in front of an already existing
variable tells PHP to use the variable having that name. Consider an example:

<?
$somevar = 15;
function addit() {
GLOBAL $somevar;
$somevar++;
print "Somevar is $somevar";
}
addit();
?>
This will produce the following result.

Somevar is 16

PHP Static Variables


In contrast to the variables declared as function parameters, which are destroyed on the function's exit,
a static variable will not lose its value when the function exits and will still hold that value should the
function be called again.

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

1.7.Work with constants


A constant is a name or an identifier for a simple value. A constant value cannot change during the
execution of the script. By default a constant is case-sensitive. By convention, constant identifiers are
always uppercase. A constant name starts with a letter or underscore, followed by any number of
letters, numbers, or underscores. If you have defined a constant, it can never be changed or undefined.

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.

Differences between constants and variables are

 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.

Page 89 of 160 Lecture Note


Productivity improvement and center of excellence

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.

Checking Whether a String Contains a Valid Number:

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:

To round a number to the closest integer, use round( ) :


$number = round(2.4); // $number = 2
To round up, use ceil( ):
$number = ceil(2.4); // $number = 3
To round down, use floor( ):
$number = floor(2.4); // $number = 2
Operating on a Series of Integers

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:

for ($i = $start; $i <= $end; $i += $increment) {


echo “$i<br>”; }
Generating Random Numbers within a Range

To generate a random number within a range of numbers: Use mt_rand( ):

// random number between $upper and $lower, inclusive


$random_number = mt_rand($lower, $upper);
Calculating Exponents

To raise e to a power, use exp( ):

$exp = exp(2); // 7.3890560989307


Page 90 of 160 Lecture Note
Productivity improvement and center of excellence

To raise it to any power, use pow( ):

$exp = pow( 2, M_E); // 6.5808859910179


$pow = pow( 2, 10); // 1024
Formatting Numbers

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.

Use the number_format( ) function to format as an integer:

$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:

print number_format($number, 2); // 1,234.56

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.

Syntax :- variable = substr(string, start [, length ]);

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:

$name = "Fred Flintstone";

$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.

written as $number = substr_count(big_string, small_string);

The output is always integer.

For example:

Page 91 of 160 Lecture Note


Productivity improvement and center of excellence

$sketch = <<< End_of_Sketch

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

bacon spam tomato and spam;

End_of_Sketch;

$count = substr_count($sketch, "spam");

print("The word spam occurs $count times.");

The word spam occurs 14 times.

 substr_replace(): permits many kinds of string modifications:

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:

$greeting = "good morning citizen";

$farewell = substr_replace($greeting, "bye", 5, 7);

// $farewell is "good bye citizen"

Use a length value of 0 to insert without deleting the original strings:

$farewell = substr_replace($farewell, "kind ", 9, 0);

// $farewell is "good bye kind citizen"

Use a replacement of "" to delete without inserting:

$farewell = substr_replace($farewell, "", 8);

// $farewell is "good bye"

Here's how we can insert at the beginning of the string without deleting from original character:

Let $farewell= "good bye"

Page 92 of 160 Lecture Note


Productivity improvement and center of excellence

$well = substr_replace($farewell, "now it's time to say ", 0, 0);

//$well is "now it's time to say good bye"'

A negative value for start indicates the number of characters from the end of the string from which to
start the replacement:

$farewell = substr_replace($farewell, "riddance", -3);

// $farewell is "now it's time to say good riddance"

A negative length indicates the number of characters from the end of the string at which to stop
deleting:

$farewell = substr_replace($farewell, "", -8, -5);

// $farewell is "now it's time to say good dance"

 strrev() function:- takes a string and returns a reversed copy of it. Has syntax:-
$string = strrev(string);

For example:

echo strrev("There is no cabal");

labac on si erehT

 str_repeat() function:- takes a string and a count and returns a new string consisting of the

argument string repeated count times.

Written as $repeated = str_repeat(string, count);

For example, to build a crude horizontal rule:

echo str_repeat('-', 40); this will displays 40 dashes.

 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 ]]);

The default is to pad on the right with spaces:

$string = str_pad('Fred Flintstone', 30);


echo "$string:35:Wilma";
Fred Flintstone :35:Wilma
The optional third argument is the string to pad with:

$string = str_pad('Fred Flintstone', 30, '. ');


Page 93 of 160 Lecture Note
Productivity improvement and center of excellence

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:

echo '[' . str_pad('Fred Flintstone', 30, ' ', STR_PAD_LEFT) . "]\n";


echo '[' . str_pad('Fred Flintstone', 30, ' ', STR_PAD_BOTH) . "]\n";
[ Fred Flintstone]
[ Fred Flintstone ]

 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.

Written as strops(orginal string, new string)

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"

Page 94 of 160 Lecture Note


Productivity improvement and center of excellence

As with strrpos(), strrchr() searches backward in the string, but only for a character, not for an
entire string.

 Using the strlen() function


The strlen() function is used to find the length of a string. For example:- To find the length of "Hello
world!", we can write as follows

<?php
echo strlen("Hello world!");
?>
Reading Assignment

 PHP Date and Time


 PHP Operators

Page 95 of 160 Lecture Note


Productivity improvement and center of excellence

2. PHP Statements and Forms


2.1. Decision Statements
The if, else if ...else and switch statements are used to take decision based on the different condition.

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.

The If...Else Statement


Use this statement, if you want to execute some code if a condition is true and another code if a
condition is false.

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!";
?>

Page 96 of 160 Lecture Note


Productivity improvement and center of excellence

The ElseIf Statement


If you want to execute some code if one of the several conditions is true, then use the elseif statement.

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


If you want to select one of many blocks of code to be executed, use the Switch statement.

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)
{

Page 97 of 160 Lecture Note


Productivity improvement and center of excellence

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 ?";
}
?>

2.2. PHP Loops


Loops in PHP are used to execute the same block of code a specified number of times. PHP supports
following four loop types.

The for Loop Statement


The for loop is used when you know in advance how many times the script should run.

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)

Page 98 of 160 Lecture Note


Productivity improvement and center of excellence

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>

The while loop Statement


The while statement will execute a block of code if and as long as a test expression is true. If the test
expression is true then the code block will be executed. After the code has executed the test expression
will again be evaluated and the loop will continue until the test expression is found to be false.

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

Page 99 of 160 Lecture Note


Productivity improvement and center of excellence

$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>

The do...while loop Statement


The do...while statement will always execute the block of code once, it will then check the condition,
and repeat the loop while the condition is true.

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>

This will produce the following result:


The number is= 1 2 3 4 5 6

Page 100 of 160 Lecture Note


Productivity improvement and center of excellence

The foreach loop Statement

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

foreach (array as value)


{
code to be executed;
}
Example

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 break statement

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" );
?>

This will produce the following result:


Loop stopped at i = 3

The continue statement

Page 101 of 160 Lecture Note


Productivity improvement and center of excellence

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.

In PHP, there are three kinds of arrays:

 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.

Page 102 of 160 Lecture Note


Productivity improvement and center of excellence

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:

Values of the array: 1 3 2 4 5


Values of the array: one two three four five

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

In this example we use an array to assign credit_hours to the different courses:

$credit_hour = array("AIP"=>3, "AP"=>3, "DCN"=>4, "CMT"=>4, "EDP"=>4);


This is equivalent with:

$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);

Page 103 of 160 Lecture Note


Productivity improvement and center of excellence

$grade = array("AIP"=>'A', "AP"=>'B', "DCN"=>'C', "CMT"=>'A', "EDP"=>'C');


$grade_point= array("AIP"=>12, "AP"=>9, "DCN"=>8, "CMT"=>16, "EDP"=>8);
foreach($credit_hour as $value)
$total_credit_hour+=$value;
foreach($grade_point as $value)
$total_grade_point+=$value;
$semester_gpa=number_format(($total_grade_point/$total_credit_hour),2);
echo "GPA:".$semester_gpa;
?>
This will produce the following result:

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:

Abebe scored:A in AIP


Abebe scored:B in AP
Ermias scored:B in AIP
Ermias scored:C in AP

The above code is equivalent with:


<?php
$grade['Abebe']['AIP']="A";

$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)

Page 104 of 160 Lecture Note


Productivity improvement and center of excellence

echo "<br>Ermias scored:".$value." in ".$key;”\


?>
This will produce the same output as the above example.

Adding and Removing Array Elements

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:-

 sort() : sorts the elements in the numeric and alphabetical order.


 rsort() : sorts the elements in the reverse order.
 asort() : sorts the elements in the array without changing the indices.
 ksort() : sorts the arrays by key.
For example:
<?php
// define array
$data = array(15,81,14,74,2);

Page 105 of 160 Lecture Note


Productivity improvement and center of excellence

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 )
?>

2.4. PHP Functions

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

i. Creating PHP Function:


We can create a function its name should start with keyword function and all the PHP code should be
put inside { and } braces as shown in the following example below:

<?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);
?>

Page 106 of 160 Lecture Note


Productivity improvement and center of excellence

iii. Passing Arguments by Reference:


It is possible to pass arguments to functions by reference. This means that a reference to the variable is
manipulated by the function rather than a copy of the variable's value.

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;

Page 107 of 160 Lecture Note


Productivity improvement and center of excellence

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');

Page 108 of 160 Lecture Note


Productivity improvement and center of excellence

}
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

2.5. PHP Error Handling


Error handling is the process of catching errors raised by the program and then taking appropriate
action. Its very simple in PHP to handle an errors.

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.

o Defining Custom Error Handling Function:


It is possible to write our own function to handling any error. PHP provides a framework to define error
handling function. This function must be able to handle a minimum of two parameters (error level and
error message) but can accept up to five parameters (optionally: file, line-number, and the error
context):

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();

Page 110 of 160 Lecture Note


Productivity improvement and center of excellence

}
//set error handler
set_error_handler("handleError");
//trigger error
myFunction (1,"fatal error","c:\\",12);
?>

2.6. PHP Forms


One of the most powerful features of PHP is the way it handles HTML forms. The basic concept that is
important to understand is that any form element will automatically be available to your PHP scripts.

 The syntax could be written as -


<form action=“url to submit the form filled” method=“get” or “post”>
<!–- form contents -->
</form>
 Where action=“…” is the page that the form should submit its data to, and
method=“…” is the method by which the form data is submitted. If the method is get the
data is passed in the url string, if the method is post it is passed as a separate file.

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.

The GET Method:-


 Has restriction to send to server/ database parts up to 1024 characters only.
 Never use GET method for systems which have password or other sensitive information
to be sent to the server.
 GET can't be used to send binary data, like images or word documents, to the server
because GET method sends the encoded user information.
 The data sent by GET method can be accessed using QUERY_STRING environment
variable.

Example: - Save it as info.php

<?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" />

Page 111 of 160 Lecture Note


Productivity improvement and center of excellence

<input type="submit" />


</form>
</body></html>

The above code’s action attribute value can be represented as the filename itself like:-

<form action=”info.php” method=”Get”>

The POST Method:


The POST method transfers information via HTTPs headers. The information is encoded as described in
case of GET method and put into a header called QUERY_STRING.

 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.

The $_REQUEST variable


 The PHP $_REQUEST variable contains the contents of $_GET, $_POST, and
$_COOKIE variables
 This variable can be used to get the result from form data sent with both the GET and
POST methods.

Example1: - Create the following two.

<?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

We can categorize validation in to the following groups:

 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");

Page 113 of 160 Lecture Note


Productivity improvement and center of excellence

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

 uses regular expression on the string Syntax: preg_match($regexp,$subject)


if(!preg_match("/PHP/","PHP is SSS"))
die("match not found");
else
echo "Match Found!";
 Digits 0-9 only: This uses to check whether an input is digit/ number or not. The
following is a syntax to check if $age is a number or not. If not number, it display “ Please
enter numbers only for Age”

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

die("Invalid email format");


 URL Address: If there is an input field named "website" we can check for a valid URL
address like this

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>

Page 115 of 160 Lecture Note


Productivity improvement and center of excellence

Email:<input type="text" name="email"><font>*</font><br>


Username:<input type="text" name="username"><font>*</font><br>
Password:<input type="Password" name="password"><font>*</font><br>
Website(if any):<input type="text" name="website"><br>
<input type="submit" name="signup" value="SignUp"><input type="reset" value="Reset">
</form></div></div>
<?php
echo "<div id=xr><div id=xxx>";
if(isset($_POST['signup']))
{
if(!empty($_POST['fname'])&&!empty($_POST['lname'])&&!empty($_POST['sex'])&&!
empty($_POST['age'])&&!empty($_POST['email'])&&!empty($_POST['username'])&&!
empty($_POST['password']))
{
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$sex=$_POST['sex'];
$age=$_POST['age'];
$email=$_POST['email'];
$usernames=array("abc","123","xyz");
$gender=array("M","F");
$username=$_POST['username'];
$password=$_POST['password'];
$website=$_POST['website'];
$c=0; $minchar=6;
if(!preg_match("/^[a-zA-Z ]*$/",$fname)) {
echo ("First Name can contain only characters<br>");
$c++;
}
if(!preg_match("/^[a-zA-Z ]*$/",$lname)) {
echo ("Last Name can contain only characters<br>");
$c++;
}
if(!in_array($sex,$gender)){
echo ("Please select your gender!<br>");
$c++;
}
if(!preg_match("/^[0-9]*$/",$age)) {
echo ("Age can only be numbers<br>");
$c++;
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
echo ("Invalid email format<br>");
$c++;
}
if(in_array($username,$usernames))
{
echo ("$username already exist!<br>");
$c++;
}
if(strlen($password)<$minchar) {
echo ("Password must be above 6 characters!<br>");
$c++;
}

Page 116 of 160 Lecture Note


Productivity improvement and center of excellence

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>

Page 117 of 160 Lecture Note


Productivity improvement and center of excellence

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.

Database: is a set of tables. We should have 1 database for 1 application.

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.

Rows: single record of data. Ex. “Abebe”, “Kebede”, “abe@gmail.com”, “password”

Field: is the intersection of a row and a column. Ex. FirstName: ”Abebe”

Index: data structure on a table to increase look up speed.

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.

3.2. Connect to an MySQL server/existing Database

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:

Page 118 of 160 Lecture Note


Productivity improvement and center of excellence

PHP database interactions in five steps:

 Create a database connection


 Perform Database query
 Use returned data if any
 Release returned data
 Close database connection

Creating a database connection:

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.

Optional - If a second call is made to mysql_connect() with the same arguments, no


new_link new connection will be established; instead, the identifier of the already opened
connection will be returned.

Page 119 of 160 Lecture Note


Productivity improvement and center of excellence

Optional - A combination of the following constants:

MYSQL_CLIENT_SSL - Use SSL encryption

MYSQL_CLIENT_COMPRESS - Use compression protocol


client_flags
MYSQL_CLIENT_IGNORE_SPACE - Allow space after function names

MYSQL_CLIENT_INTERACTIVE - Allow interactive timeout seconds of inactivity before


closing the connection

Therefore, mysql_connect() function written as follows with respective parameters:-

mysql_connect(server,username,passwd,new_link,client_flag);

There are also functions in PHP which have different purposes. For instance,

 mysql_select_db("database name"): Equivalent to the MySQL command USE; makes


the selected database the active one.
 mysql_query("query"): Used to send any type of MySQL command to the server.
 mysql_fetch_rows("results variable from query"): Used to return a row of the entire
results of a database query.
 mysql_fetch_array("results variable from query"): Used to return several rows of the
entire results of a database query.
 mysql_free_result(“result variable from query”): Used to release the returned results.
 mysql_error(): Shows the error message that has been returned directly from the
MySQL server.

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

Page 120 of 160 Lecture Note


Productivity improvement and center of excellence

mysqli_select_db(“connection”,”databasename”) function. If the database you are looking to work on


is not available, you can create it using mysql_query() or mysqli_query() function together with CREATE
command followed by database name. mysql_query function can take two parameters and returns
TRUE on success or FALSE on failure. The parameters are:- sql and connection. The syntax of the
function is:- mysql_query(sql, connection variable); or mysqli_query(connection variable,sql);

To create a database uses the following sql syntax:

CREATE DATABASE database_name

Example Using : mysql Example Using : mysqli

<?php <?php

$connection=$mysql_connect("localhost", "root", "") ; $connection=$mysqli_connect("localhost", "root", "");

If($connection) If($connection)

echo "Connected to MySQL<br />"; echo "Connected to MySQL<br />";

$sql=mysql_select_db("test"); }else{

If($sql){ $result=mysqli_query($connection,“create database


test”);//create a database called test if not available
echo "Connected to Database";//display this message if
database is selected If($result)

}else{ mysqli_select_db($connection,"test")

$result=mysql_query(“create database test”, else


$connection);//create a database called test if not
available die(“Database not
selected:”.mysql_error($connection));//select test
If($result) database

mysql_select_db("test");//select test database }

else mysqli_close($connection);//closing connection

die(“Database not selected:”.mysql_error()); ?>

?>

mysql_close();//closing connection

Output:

Page 121 of 160 Lecture Note


Productivity improvement and center of excellence

Connected to MySQL
Connected to Database

 mysql_query ("create database test”,$connection): told MySQL to create a database


called test.
 die(mysql_error()); will print out an error if there is a problem in the database creation
process.

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

Create Table MySQL

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:

CREATE TABLE table_name (column_name1 data_type,column_name2 data_type,....)

We are now going to design a MySQL query to summon our table from database test.

Example Using : mysql Example Using : mysqli

<?php <?php

// Make a MySQL Connection // Make a MySQL Connection

$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

Page 122 of 160 Lecture Note


Productivity improvement and center of excellence

$sql=mysql_select_db($dbname); $sql2="CREATE TABLE example(

If($sql) id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id),

{ // Create a MySQL table in the selected database name VARCHAR(30), age INT)";

$sql2="CREATE TABLE example( $result=mysqli_query($connection,$sql2);

id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), If($result)

name VARCHAR(30), age INT)"; echo "Table Created!";

$result=mysql_query($sql2,$connection); else

If($result) die(“Table Creation


failed:”.mysqli_error($connection));
echo "Table Created!";
}else{
else
die(“Mysql server Connection
die(“Table Creation failed:”.mysql_error()); Failed:”.mysqli_error($connection));

}else{ }

die(“Database selection failed:”.mysql_error()); mysqli_close($connection);//closing connection

}else{ ?>

die(“Mysql server Connection Failed:”.mysql_error());

mysql_close();//closing connection

?>

3.3. Send/Insert Data to a Database

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:

INSERT INTO table_name VALUES (value1, value2, value3,...) Or

Page 123 of 160 Lecture Note


Productivity improvement and center of excellence

INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,...)

<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:

// Make a MySQL Connection


$connection=mysqli_connect("localhost", "root", "","test”);
If($connection){
// Insert a row of information into the table "example"
$sql2="INSERT INTO example(name, age) VALUES('$name', '$age') ";
$result=mysqli_query($connection,$sql2) ;
If($result)
echo "Data Inserted!";
else
die(“Data not inserted:”.mysqli_error($connection));
} else
die(“Database not selected:”.mysqli_error($connection));
}else{
die(“Connection Failed:”.mysqli_error($connection));
}
mysqli_close($connection);//closing connection
?>

3.4. Retrieve Data from a Database

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.

The SELECT statement is used to select data from a database.

Syntax: SELECT column_name(s) FROM table_name

Example:

Example Using : mysql Example Using : mysqli

<?php <?php

// Make a MySQL Connection // Make a MySQL Connection

$connection=mysql_connect("localhost", "root", ""); $connection=mysqli_connect("localhost", "root",


"","test”);
If($connection){
If($connection){

Page 125 of 160 Lecture Note


Productivity improvement and center of excellence

$sql=mysql_select_db("test"); / Retrieving all records from "example" table

If($sql){ $sql=”select * from example ";

// Retrieving all records from "example" table $result=mysqli_query($connection,$sql) ;

$sql2="select * from example"; If($result){

$result=mysql_query($sql2,$connection) ; //Displaying the values using a table

If($result){//Displaying the values using a echo “<table border=1><tr><th>Id</th>”;


table
echo “<th>Name</th><th>Age</th></tr>”;
echo "<table border=1><tr><th>Id</th>";
While($row=mysqli_fetch_assoc($result))
echo "<th>Name</th><th>Age</th></tr>";
{
While($row=mysql_fetch_array($result))
echo “<tr><td>”.$row[‘id’].”</td>”;
{ echo "<tr><td>".$row['id']."</td>";
echo “<td>”.$row[‘name’].”</td>”;
echo "<td>".$row['name']."</td>";
echo “<td>”.$row[‘age’].”</td></tr>”;
echo "<td>".$row['age']."</td></tr>";
}
}
echo “</table>”;
echo "</table>";
}else
}else
die(“Record Not
die("Record Not Selected:".mysql_error()); Selected:”.mysqli_error($connection));

} else }else{

die("Database not die(“Connection Failed:”.mysqli_error($connection));


selected:".mysql_error());
}
}else{
mysqli_close($connection);//closing connection
die("Connection Failed:".mysql_error());
?>
}

?>

Output:

Page 126 of 160 Lecture Note


Productivity improvement and center of excellence

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”);

3.5. Modify/Updating Existing Data

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.

The UPDATE statement is used to update existing records in a table.

Syntax
UPDATE table_name SET column1=value, column2=value2,... WHERE some_column=some_value

Page 127 of 160 Lecture Note


Productivity improvement and center of excellence

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.

Example Using : mysql Example Using : mysqli

<?php <?php

// Make a MySQL Connection // Make a MySQL Connection

$connection=mysql_connect("localhost", "root", $connection=mysqli_connect("localhost", "root",


""); "","test”);

If($connection){ If($connection){

$sql=mysql_select_db("test"); // Updating record

If($sql){ $sql=”update example set age=17 where id=4 ";

// Updating record $result=mysqli_query($connection,$sql) ;

$sql2=" update example set age=17 where id=4 If($result){


";
echo “Age successfully updated!”;
$result=mysql_query($sql2,$connection) ;
}else
If($result){
die(“Record Not
echo “Age successfully updated!”; Updated:”.mysqli_error($connection));

}else }else{

die("Record Not updated:".mysql_error()); die(“Connection Failed:”.mysqli_error($connection));

} else }

die("Database not selected:".mysql_error()); mysqli_close($connection);//closing connection

}else{ ?>

die("Connection Failed:".mysql_error());

?>

Output:

Age successfully updated!

In the above example:

 UPDATE - Performs an update MySQL query


Page 128 of 160 Lecture Note
Productivity improvement and center of excellence

 SET - The new values to be placed into the table follow SET
 WHERE - Limits which rows are affected

3.6. Remove Existing Data

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:

DELETE from table_name where column_name comparison_operator value

For example: delete all records in which age is below 18.

Example Using : mysql Example Using : mysqli

<?php <?php

// Make a MySQL Connection // Make a MySQL Connection

$connection=mysql_connect("localhost", "root", $connection=mysqli_connect("localhost", "root",


""); "","test”);

If($connection){ If($connection){

$sql=mysql_select_db("test"); // Updating records

If($sql){ $sql=” delete from example where age<18";

// deleting records $result=mysqli_query($connection,$sql) ;

$sql2="delete from example where age<18 "; If($result){

$result=mysql_query($sql2,$connection) ; echo “Records Deleted!”;

If($result){ }else

echo “Records Deleted!”; die(“Record Not


Deleted:”.mysqli_error($connection));
}else
}else{
die("Record Not deleted:".mysql_error());
die(“Connection Failed:”.mysqli_error($connection));

Page 129 of 160 Lecture Note


Productivity improvement and center of excellence

} else }

die("Database not selected:".mysql_error()); mysqli_close($connection);//closing connection

}else{ ?>

die("Connection Failed:".mysql_error());

?>

Output:

Records Deleted!

3.7. Data base security using server side scripting

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);
?>

Page 130 of 160 Lecture Note


Productivity improvement and center of excellence

Output:

md5 encryption 12345678=25d55ad283aa400af464c76d713c07ad


sha1 encryption 12345678=7c222fb2927d828af22f592134e8932480637c0d
hash encryption 12345678=7c222fb2927d828af22f592134e8932480637c0d
crypt encryption 12345678=$1$.90.tj5.$CG0sUopGFc1ADWxBqDjPu.

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:

bad_guy', 'mypass', ''), ('good_guy

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.

Page 131 of 160 Lecture Note


Productivity improvement and center of excellence

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.

Protecting against SQL injection is easy:

 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.

4. Files and Directories

4.1. Reading files/ Directories


Files and directories have three levels of access: User, Group and Other. The three typical permissions
for files and directories are:

 Read (r)
 Write (w)
 Execute (x)

Page 132 of 160 Lecture Note


Productivity improvement and center of excellence

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:-

1. Open the file stream with the fopen() function


Syntax:- variable= fopen(“text file”, “mode”); where mode mean r, r+, w, w+ etc as
shown in the next page.
2. Write data to or read data from the file stream
 We use fread(($filepointer,”filesize”) function to read files or data.. We can also use
fgets() function to read files or data. It is written with two parameters like
fgets($filepointer,”filesize”)
o Reads up to $bytes of data, stops at newline or end of file (EOF)
 PHP supports two basic functions for writing data to text files:
o file_put_contents() function writes or appends a text string to a file. Its syntax for
the file_put_contents() function is: file_put_contents (filename, string[, options]
o fwrite() function incrementally writes data to a text file. Its syntax for the fwrite()
function is: fwrite($handle, data[, length]);
3. Close the file stream with the fclose() function:- used when finished working with a file
stream to save space in memory.
Syntax:- fclose(file name that contains the opened files);
Example:- $handle = fopen('people.txt', 'r');

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

Page 133 of 160 Lecture Note


Productivity improvement and center of excellence

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.

 Open a file using fopen() function.


 Get the file's length using filesize() function.
 Read the file's content using fread() function.
 Close the file with fclose() function.

The following example assigns the content of a text file to a variable then displays those contents on the
web page.

<html><head><title>Reading a file using PHP</title></head><body>


<?php
$filename = "/home/user/guest/tmp.txt";
$file = fopen( $filename, "r" );
if( $file == false )
{
echo ( "Error in opening file" );
exit();
}
$filesize = filesize( $filename );
$filetext = fread( $file, $filesize );
fclose( $file );
echo ( "File size : $filesize bytes" );
echo ( "<pre>$filetext</pre>" );
?>
</body></html>
Note That:- There are two ‘shortcut’ functions that don’t require a file to be opened:

 $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

4.1. Writing a File


A new file can be written or text can be appended to an existing file using the PHP function as discus in
the previous discussions. These functions require two arguments specifying a file pointer and the string
of data that is to be written. Optionally a third integer argument can be included to specify the length of
the data to write. If the third argument is included, writing would will stop after the specified length has
been reached. The following is the syntax to write files:-

fwrite(file we write on it, string what we write[,length of string])


The following example creates a new text file then writes a short text heading inside it. After closing this
file its existence is confirmed using file_exists() function which takes file name as an argument. See the
following example how open file, write in file and close files

<?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

Example:- This example shows costsharing payment system

<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;

 To write files incrementally, use the fwrite() function


 fclose() closes a file.
 fgetc() reads a single character
 feof() determines if the end is true.
 fgets() reads a line of data
 file() reads entire file into an array

Page 136 of 160 Lecture Note


Productivity improvement and center of excellence

See the following examples

Example 3:

Example 1:- <?php


$lines = file('welcome.txt');
<?php foreach ($lines as $l_num => $line)
$myFile = "welcome.txt"; {
if (!($fh=fopen($myFile,'r'))) echo "Line #{$l_num}:“ .$line.”<br/>”;
exit("Unable to open file."); }
while (!feof($fh)) ?>
{ Example 4:-
$x=fgetc($fh);
echo $x; <?php
} $myFile = "testFile.txt";
fclose($fh); $fh = fopen($myFile, 'a') or die("can't open
?> file");
Example 2 $stringData = "New Stuff 1\n";
fwrite($fh, $stringData);
<?php $stringData = "New Stuff 2\n";
$myFile = "welcome.txt"; fwrite($fh, $stringData);
$fh = fopen($myFile, 'r'); fclose($fh); ?>
$theData = fgets($fh);
fclose($fh);
echo $theData;?>

Page 137 of 160 Lecture Note


Productivity improvement and center of excellence

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.

Reading an Entire File

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

Page 138 of 160 Lecture Note


Productivity improvement and center of excellence

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>”);

4.2 Create Directories


Basic functions/methods that are used to open directories, read directories and close directories are;-
o To iterate through the entries in a directory, open a handle to the directory with the opendir()
function
o Use the readdir() function to return the file and directory names from the open directory
o Use the closedir() function to close a directory handle

Example 1:- This is used to demonstrate how gare directory contents of files are displayed.

<?php

$Dir = "C:\\gare";

$DirOpen = opendir($Dir);

while ($CurFile = readdir($DirOpen)) {

echo $CurFile . "<br />";

closedir($DirOpen);

?>

Example 2:- The following example shows how the content of the current directory opened

$handle = opendir('./');

while(false !== ($file=readdir($handle)))

{ echo "$file<br />";

Page 139 of 160 Lecture Note


Productivity improvement and center of excellence

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>";

Page 140 of 160 Lecture Note


Productivity improvement and center of excellence

}
else echo "<p>The directory does not exist.</p>";
?>

4.3 Rename and Delete Files and Directories

 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

o The syntax is: rename(old_name, new_name)

 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

4.4 Upload Files


Web applications allow visitors to upload files to and from their local computer. The files that are
uploaded and downloaded may be simple text files or more complex file types, such as images,
documents, or spreadsheets.

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

<form method=”post” action=” ” enctype= multipart/form-data >


<input type="file" name="picture_file" />
</form>
The MAX_FILE_SIZE (uppercase) attribute of a hidden form field specifies the maximum number of bytes
allowed in the uploaded file and it must appear before the file input field.

When the form is posted, information for the uploaded file is stored in the $_FILES auto global array.

The $_FILES[] array contains five elements:

a. // Contains the error code associated with the file $_FILES['picture_file']['error']


b. // Contains the temporary location of the file
$_FILES['picture_file']['tmp_name'] contents

c. // Contains the name of the original file


$_FILES['picture_file']['name']
d. // Contains the size of the uploaded file in bytes
Page 141 of 160 Lecture Note
Productivity improvement and center of excellence

$_FILES['picture_file']['size']

e. // Contains the type of the file


$_FILES['picture_file']['type']

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>

Page 143 of 160 Lecture Note


Productivity improvement and center of excellence

5. Introduction to CMS

5.1. Overview of Content Management Systems (CMS)


A web presence is critical for almost every nonprofit, but creating websites can be daunting. It can
take a lot of time, money and technical expertise, which are often in short supply. And just because
you have a website up and running doesn’t mean your work is done. You still need to keep up with
maintenance, updates and desirable new features. This is where an open source Content
Management System (CMS) can help.

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.

How does this work?

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

Page 144 of 160 Lecture Note


Productivity improvement and center of excellence

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

Page 145 of 160 Lecture Note


Productivity improvement and center of excellence

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

Page 146 of 160 Lecture Note


Productivity improvement and center of excellence

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:

 Joomla, Drupal and Wordpress installations


 Joomla, Drupal and Wordpress elements
 Joomla, Drupal and Wordpress front end
 Joomla, Drupal and Wordpress back end

Page 147 of 160 Lecture Note


Productivity improvement and center of excellence

Page 148 of 160 Lecture Note

You might also like