0% found this document useful (0 votes)
1 views218 pages

Web

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views218 pages

Web

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 218

INT E R N E T

P R OG R A M M IN G
IN T E R N E T A N D W W W
1 - O V E RV IE W O F THE
CHAPTER
Basic Concepts of Internet and WWW
• Network is communication system connecting two or more computers.
• Internet is a worldwide network that connects smaller independent networks
worldwide.
• Internet could be connected by network cables or through satellite links.
• The communication is governed by protocols established by an international body -
Internet Engineering Task Force.
• The Internet connectivity is provided by Internet Service Providers (ISP).
• These corporations dedicate computers to act as servers - that is they make
information (such as Web pages or e-mail) available to users of the Internet.
• The origin of Internet devised from the concept of Advanced Research Project
Agency Network (ARPANET) developed by United States Department of Defence.
• The World Wide Web (WWW), commonly known as the Web, is an information
system enabling documents and other web resources to be accessed over the
Internet.
• Servers and resources on the World Wide Web are identified and located through
• The original and still very common document type is a web page formatted in
Hypertext Markup Language (HTML).
• This mark-up language supports plain text, images, embedded video and audio contents, and
scripts (short programs) that implement complex user interaction.
• The HTML language also supports hyperlinks (embedded URLs) which provide immediate
access to other web resources.
• Web navigation, or web surfing, is the common practice of following such
hyperlinks across multiple websites.
• The information in the Web is transferred across the Internet using the Hypertext
Transfer Protocol (HTTP).
• Multiple web resources with a common theme and usually a common domain name
make up a website.
• A single web server may provide multiple websites, while some websites, especially
the most popular ones, may be provided by multiple servers.
• The World Wide Web has become the world's dominant software platform billions of
people worldwide use to interact with the Internet.
• The Internet is a global system of computer networks interconnected through
telecommunications and optical or satellite networking.
• In contrast, the World Wide Web is a global collection of documents and other
resources, linked by hyperlinks and URIs.
• A Uniform Resource Identifier (URI) is a unique sequence of characters
that identifies a logical or physical resource used by web technologies.
• URIs may be used to identify anything, including real-world objects, such as
people and places, concepts, or information resources such as web pages and
books.
• URI identifies a resource by location (URL), name (URN), or both.
• URL and URN are subsets of URI.
• URI defines the identity of a resource and establishes the unique distinguished
identity of the resource regardless of the method used (name, location or both).
• URI syntax was first defined in RFC 2396, published in August 1998, and
finalized in RFC 3986, published in January 2005.
• The URI generic syntax consists of five components organized hierarchically in
order of decreasing significance from left to right:
URI = scheme ":" ["//" authority] path ["?" query] ["#" fragment]
• A Uniform Resource Name (URN) is a URI that identifies a resource by
name in a particular namespace.
• A URN may be used to talk about a resource without implying its location or how
to access it.
• For example, in the International Standard Book Number (ISBN) system, urn:
ISBN: 0-486-27557-4.
• However, it gives no information as to where to find a copy of that book.
• A Uniform Resource Locator (URL) is a URI that specifies the means of acting
upon or obtaining the representation of a resource, i.e. specifying both its primary
access mechanism and network location.
• For example, the URL http://example.org/wiki/Main_Page refers to a resource identified as
/wiki/Main_Page, whose representation is obtainable via the Hypertext Transfer Protocol (http
:) from a network host whose domain name is example.org.
• A URN is analogous to a person's name, while a URL is analogous to their street
address. In other words, a URN identifies an item and a URL provides a method
for finding it.
HTTP protocol
• Reference Model offers a means of standardization which is acceptable
worldwide.
• Since people using the computer network are located over a wide physical
range and their network devices might have heterogeneous architecture.
• In order to provide communication among heterogeneous devices, we need a
standardized model i.e. a reference model, which would provide us way how
these devices can communicate regardless their architecture.
• We have two reference models such as OSI model and TCP/IP reference
model. OSI model is a hypothetical one but the TCP/IP is practical model and
is used in the Internet.
• Application Layer is one of the layers of the TCP/IP model.
• An application layer is the topmost layer in the TCP/IP model.
• It is responsible for handling high-level protocols.
• This layer allows the user to interact with the application.
• Every application cannot be placed inside the application layer except those that have
interaction with the communication system.
• For example: text editor cannot be considered in application layer while web browser is, because
it uses HTTP protocol to interact with the network where HTTP protocol is an application layer
• HTTP stands for Hypertext transfer protocol.
• Hypertext is text which contains links to other texts.
• This protocol allows us to access the data over the World Wide Web.
• It transfers the data in the form of plain text, audio, video.
• HTTP functions as a request–response protocol in the client–server
model.
• A web browser, for example, may be the client whereas a process,
named web server, running on a computer hosting one or more websites
may be the server.
• The client submits an HTTP request message to the server.
• The server, which provides resources such as HTML files and other
content or performs other functions on behalf of the client, returns a
response message to the client.
• The response contains completion status information about the request
Web browsers
• Documents and downloadable media are made available to the network through web
servers and can be accessed by programs such as web browsers.
• A web browser is an application for accessing websites.
• When a user requests a web page from a particular website, the browser retrieves its
files from a web server and then displays the page on the user's screen.
• A web browser is not the same thing as a search engine.
• A search engine is a website that provides links to other websites.
• However, to connect to a website's server and display its web pages, a user must
have a web browser installed.
• In some technical contexts, browsers are referred to as "user agents.“
• If the URL uses the secure mode of HTTP (HTTPS), the connection between the
browser and the web server is encrypted for the purposes of communications
security and information privacy.
• During the course of browsing, cookies received from various websites are stored by
the browser.
• Cookies are small pieces of text sent to your browser by a website you visit.
• They help that website remember information about your visit, which can both make
it easier to visit the site again and make the site more useful to you.
January 2023 desktop browser share
Client-Server model
• The client–server model is a distributed application structure that partitions
tasks or workloads between the providers of a resource or service, called
servers, and service requesters, called clients.
• Often clients and servers communicate over a computer network on separate
hardware, but both client and server may reside in the same system.
• A server host runs one or more server programs, which share their resources
with clients.
• A client usually does not share any of its resources, but it requests content or
service from a server.
• Clients, therefore, initiate communication sessions with servers, which await
incoming requests.
• Examples of computer applications that use the client–server model are email,
network printing, and the World Wide Web.
• The "client–server" characteristic describes the relationship of cooperating
programs in an application.
• The server component provides a function or service to one or many clients,
which initiate requests for such services.
• Servers are classified by the services they provide.
• For example, a web server serves web pages and a file server serves computer files.
• The sharing of resources of a server constitutes a service.
• Whether a computer is a client, a server, or both, is determined by the nature
of the application that requires the service functions.
• For example, a single computer can run a web server and file server software at the
same time to serve different data to clients making different kinds of requests.
• Generally, a service is an abstraction of computer resources and a client does
not have to be concerned with how the server performs while fulfilling the
request and delivering the response.
• The client only has to understand the response based on the well-known
application protocol, i.e. the content and the formatting of the data for the
requested service.
• Clients and servers exchange messages in a request–response messaging
pattern.
• The client sends a request, and the server returns a response.
• This exchange of messages is an example of inter-process communication.
• To communicate, the computers must have a common language, and they must follow
rules so that both the client and the server know what to expect.
• All protocols operate in the application layer.
• The application layer protocol defines the basic patterns of the dialogue.
• To formalize the data exchange even further, the server may implement an
application programming interface (API).
• The API is an abstraction layer for accessing a service.
• By restricting communication to a specific content format, it facilitates cross-platform data
exchange.
• A server may receive requests from many distinct clients in a short period.
• A computer can only perform a limited number of tasks at any moment, and
relies on a scheduling system to prioritize incoming requests from clients to
accommodate them.
• To prevent abuse and maximize availability, the server software may limit the
availability to clients.
• Denial of service attacks are designed to exploit a server's obligation to
process requests by overloading it with excessive request rates.
• Encryption should be applied if sensitive information is to be communicated between the
client and the server.
Example
• When a bank customer accesses online banking services with a web
browser (the client), the client initiates a request to the bank's web
server.
• The customer's login credentials may be stored in a database, and the
webserver accesses the database server as a client.
• An application server interprets the returned data by applying the bank's
business logic and provides the output to the webserver.
• Finally, the webserver returns the result to the client web browser for
display.
• A host is any computer connected to a network.
• Whereas the words server and client may refer either to a computer or to
a computer program, server-host and client-host always refer to
computers.
• The host is a versatile, multifunction computer; clients and servers are
Web programming
• Web programming refers to the writing, markup and coding involved in Web
development, which includes Web content, Web client and server scripting and
network security.
• It is the creation of an application that works over the internet i.e. websites.
• The most common languages used for Web programming are XML, HTML,
JavaScript, Perl 5 and PHP.
• Web programming is different from just programming, which requires interdisciplinary
knowledge on the application area, client and server scripting, and database
technology.
• Web programming can be briefly categorized into client and server coding.
• The client side needs programming related to accessing data from users and providing
information.
• It also needs to ensure there are enough plugins to enrich user experience in a graphic user
interface, including security measures.
• To improve user experience and related functionalities on the client side, JavaScript is usually
used.
• It is an excellent client-side platform for designing and implementing Web applications.
• HTML5 and CSS3 supports most of the client-side functionality provided by other application
frameworks.
Frontend Development
• The part of a website where the user interacts directly is termed as front end. It
is also referred to as the ‘client side’ of the application.
• Here are some of the most common front-end languages:
• HTML
• HTML (Hypertext Markup Language) is among the basic web development technologies for
designing the client side of the app.
• Additionally, it is the standard front-end language used to describe the structure of a webpage.
• Front-end developers can use HTML to create static pages consisting of text, images, headings,
links, and tables.
• CSS
• CSS (Cascading Style Sheets) is a language that allows us to stylize HTML elements. It basically
makes it easy to create beautiful web pages.
• JavaScript
• JavaScript or JS is one of the essential web technologies.
• It is a popular scripting language used to make a web app or site interactive.
• For example, JavaScript allows us to add interactive elements like buttons, visualizations, and
animations.
• AJAX
• Ajax stands for Asynchronous Javascript and XML.
• It allows us to communicate with the server without the need to refresh the web page. As a result, it
improves performance and user experience.
Backend Development
• Back-end development means working on server-side software, which focuses on
everything you can't see on a website.
• Back-end Development refers to the server-side development. It focuses on
databases, scripting, and website architecture.
• PHP
• PHP is a popular server-side scripting language used for web development. It is an open-source language that
supports several databases. For instance, you can use PHP to connect to and manage a database
management system like MySQL.
• Node.js
• Node.js is an open-source runtime environment that allows developers to execute JS code outside a web
browser.
• Python
• Python is another very popular open-source, object-oriented programming language used for several
purposes. It can work on multiple platforms like Windows, Linux, and Mac. Additionally, one of the most liked
features of Python is its human-friendly syntax, which makes it easy to learn and write clean code.
• Ruby
• Developed in the 1990s, Ruby is a general-purpose, object-oriented programming language. It also has a
simple syntax, making it super easy to learn and write.
• Java
• Java is another widely used object-oriented programming language. Released in 1995 by Sun Microsystems,
Java is highly scalable and easy to use.
• JavaScript
• We can use JavaScript programming language for both front-end and back-end.
INT E R N E T
P R OG R A M M IN G
O D U C T IO N TO H T ML
CHAPTER 2: INT R
What is HTML
• HTML (Hyper Text Markup Language) is a language in which most websites
are written.
• HTML is used to create pages and make them functional.
• HTML was first created by Tim Berners-Lee, Robert Cailliau, and others
starting in 1989.
• Hypertext means that the document contains links that allow the reader to
jump to other places in the document or to another document altogether.
• The latest version is known as HTML5.
• A Markup Language is a way that computers speak to each other to control
how text is processed and presented.
• To do this, HTML uses two things: tags and attributes.
• Originally, HTML was developed with the intent of defining the structure of
documents like headings, paragraphs, lists, and so forth to facilitate the
sharing of scientific information between researchers.
• Now, HTML is being widely used to format web pages with the help of
different tags available in HTML language.
Tags and Attributes
• HTML documents imply a structure of nested HTML elements.
• These are indicated in the document by HTML tags, enclosed in angle
brackets.
• Tags and attributes are the basis of HTML.
• An element is indicated by a pair of tags: a "start tag" < > and "end tag" </
>.
• The text content of the element is placed between these tags.
• Tags may also enclose further tag markup between the start and end,
including a mixture of tags and text.
• This indicates further (nested) elements, as children of the parent element.
• The start tag may also include the element's attributes within the tag.
• These indicate other information, such as identifiers for sections within the
document, identifiers used to bind style information to the presentation of the
document.
• Some elements, such as the line break <br> do not permit any embedded
content, either text or further tags.
• The general form of an HTML element is:
• <tag attribute1="value1" attribute2="value2">''content''</tag>
• Example
• <body bgcolor=“tomato”>Main content</body>
• The name of an HTML element is the name used in the tags.
• Note that the end tag's name is preceded by a slash character, /, and that in
empty elements the end tag is neither required nor allowed.
• If attributes are not mentioned, default values are used in each case.
• Attributes usually come in name/value pairs like: name="value".
• Web pages can be created and modified by using HTML editors.
• You can use a simple text editor like Notepad (for Windows), TextEdit (for
Mac), or Sublime Text 3, Notepad ++, Komodo Edit or any other.
• You choose your HTML editor based on cross-platform support, Auto-
completion feature, Plugin options for extended functionalities, Coding
interface.
Steps in to HTML programming
• Step 1: Open your choice of HTML editor
• Step 2: Write Some HTML
• All HTML documents must start with a document type declaration: <!DOCTYPE html>. The
<!DOCTYPE> declaration represents the document type, and helps browsers to display web
pages correctly. It must only appear once, at the top of the page (before any HTML tags). The
<!DOCTYPE> declaration is not case sensitive.
• Step 3: Save the HTML Page using .htm or .html extension.
• Step 4: View the HTML Page in Your Browser
HTML Heading
HTML Paragraphs
The HTML <pre>
HTML Styles
HTML Text Formatting
Elements
Tag Description
<b> Defines bold text
<em> Defines emphasized text
<i> Defines a part of text in an alternate
voice or mood

<small> Defines smaller text


<strong Defines important text
>
<sub> Defines subscripted text
<sup> Defines superscripted text
<ins> Defines inserted text
<del> Defines deleted text
<mark> Defines marked/highlighted text
HTML Comment Tag
• You can add comments to your HTML source by using the following syntax:
• <!-- Write your comments here -->
• Notice that there is an exclamation point (!) in the start tag, but not in the end
tag.
• Note: Comments are not displayed by the browser, but they can help document
your HTML source code.
HTML Images
• The HTML <img> tag is used to embed an image in a web page.
• Images are not technically inserted into a web page; images are
linked to web pages.
• The <img> tag creates a holding space for the referenced image.
• The <img> tag is empty, it contains attributes only, and does not
have a closing tag.
• The <img> tag has two required attributes:
• src - Specifies the path to the image
• alt - Specifies an alternate text for the image
• <img src="url" alt="alternatetext" style="width:500px;height:600px;">
HTML Favicon
• A favicon is a small image displayed next to the page title in the
browser tab.
• You can use any image you like as your favicon.
• You can also create your own favicon on sites like
https://www.favicon.cc.
• A favicon image is displayed to the left of the page title in the
browser tab.
• Next, add a <link> element to your "index.html" file, after the <title>
element, like this:
HTML Tables
• A table in HTML consists of table cells inside rows and columns.
• Each table cell is defined by a <td> and a </td> tag.
• td stands for table data.
• Each table row starts with a <tr> and ends with a </tr> tag.
• tr stands for table row.
• You can have as many rows as you like in a table; just make sure that the
number of cells are the same in each row.
• Sometimes you want your cells to be table header cells. In those cases use
the <th> tag instead of the <td> tag:
• th stands for table header.
• <caption> Defines a table caption.
• <colgroup> Specifies a group of one or more columns in a table for formatting.
• <col> Specifies column properties for each column within a <colgroup> element.
• <thead> Groups the header content in a table.
• <tbody> Groups the body content in a table.
• <tfoot> Groups the footer content in a table.
• HTML tables can have borders of different styles and shapes. To add a border, use
the CSS border property on table, th, and td elements:
table, th, td {
border: 1px solid black;
}
• To set the width of a table, add the style attribute to the <table> element:
<table style="width:100%">
• Using a percentage as the size unit for a width means how wide will this element be compared to
its parent element, which in this case is the <body> element.
• To set the size of a specific column, add the style attribute on a <th> or <td>
element:
<th style="width:70%">
• To set the height of a specific row, add the style attribute on a table row element:
<tr style="height:200px">
• HTML tables can adjust the padding inside the cells, and also the space between
the cells. Cell padding is the space between the cell edges and the cell content. By
default the padding is set to 0.
• To add padding on table cells, use the CSS padding property:
th, td {
padding: 15px; }
• To add padding only above the content, use the padding-top property.
And the others sides with the padding-bottom, padding-left, and
padding-right properties:
th, td {
padding-top: 10px;
padding-bottom: 20px;
padding-left: 30px;
padding-right: 40px;
}
• Cell spacing is the space between each cell. By default the space is set
to 2 pixels. To change the space between table cells, use the CSS
border-spacing property on the table element:
table {
border-spacing: 30px;
}
• HTML tables can have cells that span over multiple rows and/or columns.
• To make a cell span over multiple columns, use the colspan attribute.
• The value of the colspan attribute represents the number of columns to span.
• To make a cell span over multiple rows, use the rowspan attribute.
• The value of the rowspan attribute represents the number of rows to span.
• Example:
<th colspan=2>Address</th>
<td>Kebele</td><td>House no.</td>
<tr>
<th rowspan="2">Phone</th>
<td>555-1234</td>
</tr>
<tr>
<td>555-8745</td>
</tr>
• Use CSS to make your tables look better. If you add a background color on every other table row, you
will get a nice zebra stripes effect. To style every other table row element, use the :nth-child(even)
selector like this:
tr:nth-child(even) {
background-color: #D6EEEE;
}
• Use the :hover selector on tr to highlight table rows on mouse over:
tr:hover {background-color: #D6EEEE;}
<!DOCTYPE html> <tr> <th rowspan=2>No.</th> <th rowspan=2>Type of
SME</th> <th rowspan=2>Male</th>
<html> <head> <style> <th rowspan=2>Female</th> <th rowspan=2>Total</th>
table, th, td { <th colspan=2>Address</th>
</tr>
border: 1px solid black; //border-collapse:
collapse; border-radius: 10px; border- <tr> <th>Kebele</th> <th>House no.</th> </tr>
style:dotted; border-color:blue; //border- <tr> <td>1</td><td>Metal
spacing:5px; work</td><td>10</td><td>10</td><td>20</td><td>01</td><td
>256</td>
}
</tr>
td{ padding:10px; } <tr> <td>2</td><td>Wood
th{ background-color: #96D4D4; padding:10px; Work</td><td>20</td><td>20</td><td>40</td><td>02</td><td
>560</td>
} </tr>
tr:nth-child(odd) { // background-color: #96D4D4;} <tr>
<td>3</td><td>Textile</td><td>30</td><td>40</td><td>70</td
tr:hover {background-color: #D6EEEE;} ><td>03</td><td>806</td>
</style> </tr>
</head> <tr>
<td>4</td><td>Agroprocessing</td><td>30</td><td>40</td><t
<body> d>70</td><td>04</td><td>796</td>
</tr>
<h1>Demonstrating table in HTML</h1>
</table>
<table border=1 style="width:50%;">
</body>
<caption>Statistical Data of MSE in </html>
Hossana.</caption>
• HTML lists The CSS list-style-type property is used to define the style
of the list item marker. It can have one of the following
HTML lists allow web developers to group a set of values:
related items in lists. An unordered list starts with disc Sets the list item marker to a bullet (default)
the <ul> tag. Each list item starts with the <li> tag.
The list items will be marked with bullets (small circle Sets the list item marker to a circle
black circles) by default. square Sets the list item marker to a square
Example: none The list items will not be marked
<ul> Example:
<li>Coffee</li> <ul style="list-style-type:disc;">
<li>Tea</li> <li>Coffee</li>
<li>Milk</li> <li>Tea</li>
<li>Milk</li>
</ul>
</ul>
An ordered list starts with the <ol> tag. Each list
item starts with the <li> tag. The list items will be Lists can be nested (list inside list). A list item (<li>) can
marked with numbers by default. contain a new list, and other HTML elements, like images
and links, etc.
Example: <ul>
<ol> <li>Tea
<li>Coffee</li> <ul>
<li>Tea</li> <li>Black tea</li>
<li>Milk</li> <li>Green tea</li>
</ol> </ul>
</li>
<!DOCTYPE html> li a:hover {
<html> background-color: #111111;
<head> }
<style> </style>
ul {
</head>
list-style-type: none;
<body>
overflow: hidden;
background-color: green;
<h2>Navigation Menu</h2>
} <ul>
li { <li><a href="#home">
Home</a></li>
float: left;
}
<li><a href="#news"> News</a></li>
li a { <li><a href="#contact">
Contact</a></li>
display: block;
<li><a href="#about"> About</a></li>
color: white;
padding: 16px;
</ul>
text-decoration: none; </body>
} </html>
HTML Block and Inline Elements
• Every HTML element has a default display value, depending on what type of element
it is.
• There are two display values: block and inline.
• A block-level element always starts on a new line, and the browsers automatically
add some space (a margin) before and after the element.
• A block-level element always takes up the full width available (stretches out to the
left and right as far as it can).
• Two commonly used block elements are: <p> and <div>.
• The <p> element defines a paragraph in an HTML document.
• The <div> element defines a division or a section in an HTML document.
<!DOCTYPE html>
<html>
<body>
<p style="border: 1px solid black">Hello World</p>
<div style="border: 1px solid black">Hello World</div>
<p>The P and the DIV elements are both block elements, and they will always start on a new line
and take up the full width available (stretches out to the left and right as far as it can).</p>
</body>
• An inline element does not start on a new line. An inline element only takes up
as much width as necessary. An inline element cannot contain a block-level
element!
• Example:
<!DOCTYPE html>
<html>
<body>
<p>This is an inline span <span style="border: 1px solid black">Hello World</span>
element inside a paragraph.</p>
<p>The SPAN element is an inline element, and will not start on a new line and only takes
up as much width as necessary.</p>
</body>
</html>
• The <div> element is often used as a container for other HTML elements.
• The <div> element has no required attributes, but style, class and id are
common. When used together with CSS, the <div> element can be used to
style blocks of content.
• The <span> Element The <span> element is an inline container used to mark
up a part of a text, or a part of a document. The <span> element has no
required attributes, but style, class and id are common. When used together
with CSS, the <span> element can be used to style parts of the text.
HTML class Attribute
• The HTML class attribute is used to specify a class for an HTML
element.
• Multiple HTML elements can share the same class.
• The class attribute is often used to point to a class name in a style sheet.
• It can also be used by a JavaScript to access and manipulate elements
with the specific class name.
• In the following example we have three <div> elements with a class
attribute with the value of "city".
• All of the three <div> elements will be styled equally according to the
.city style definition in the head section.
• The class attribute can be used on any HTML element. Note that the
class name is case sensitive!
<!DOCTYPE html> <body>
<html> <div class="city">
<h2>London</h2>
<head>
<p>London is the capital of
<style> England.</p>
.city { </div>
<div class="city">
background-color: tomato;
<h2>Paris</h2>
color: white; <p>Paris is the capital of France.</p>
border: 2px solid black; </div>
margin: 20px; <div class="city">
padding: 20px; <h2>Tokyo</h2>
} <p>Tokyo is the capital of Japan.</p>
</div>
</style> </body>
</head> </html>
HTML id Attribute
• The HTML id attribute is used to specify a unique id for an HTML element.
• You cannot have more than one element with the same id in an HTML
document.
• The id attribute is used to point to a specific style declaration in a style sheet.
• It is also used by JavaScript to access and manipulate the element with the
specific id.
• The syntax for id is: write a hash character (#), followed by an id name.
• Then, define the CSS properties within curly braces {}.
• The id name is case sensitive! The id name must contain at least one
character, cannot start with a number, and must not contain whitespaces
(spaces, tabs, etc.).
• A class name can be used by multiple HTML elements, while an id name must
only be used by one HTML element within the page.
• In the following example we have an <h1> element that points to the id name
"myHeader".
<!DOCTYPE html>
<html>
<head>
<style>
#myHeader {
background-color: lightblue;
color: black;
padding: 40px;
text-align: center;
}
</style>
</head>
<body>
<h1 id="myHeader">My Header</h1>
</body>
</html>
HTML Iframes
• An HTML iframe is used to display a web page within a web page. The HTML
<iframe> tag specifies an inline frame.
• An inline frame is used to embed another document within the current HTML
document.
• <iframe src="url" title="description"></iframe>
• It is a good practice to always include a title attribute for the <iframe>. This is
used by screen readers to read out what the content of the iframe is.
• Use the height and width attributes to specify the size of the iframe.
• The height and width are specified in pixels by default. By default, an iframe
has a border around it.
• To remove the border, add the style attribute and use the CSS border
property.
• With CSS, you can also change the size, style and color of the iframe's
border.
• Example:
<iframe src="Test.html" style="border:none;" height="300" width="100%"
The HTML <meta> Element
• The <meta> element is typically used to specify the character set, page
description, keywords, author of the document, and viewport settings.
• The metadata will not be displayed on the page, but is used by browsers (how to
display content or reload page), by search engines (keywords), and other web
services.
• Examples
• Define the character set used. This lets our browser display character from any
language.
• <meta charset="UTF-8">
• Define keywords for search engines.
• <meta name="keywords" content="HTML, CSS, JavaScript">
• Define a description of your web page:
• <meta name="description" content="My country Ethiopia">
• Define the author of a page:
• <meta name="author" content="Wondimagegn Leta">
• Refresh document every 30 seconds:
• <meta http-equiv="refresh" content="30">
• Setting the viewport to make your website look good on all devices:
HTML Forms
• An HTML form is used to collect user input.
• The user input is most often sent to a server for processing.
• The HTML <form> element is used to create an HTML form for user input.
• The form-data can be sent as URL variables (method="get") or as an HTTP post
transaction (method="post").
• The form action attribute specifies the URL of the file that will process the input when
the form is submitted.
• The "get" method:
• This method appends the form-data to the URL in name/value pairs.
• This method is useful for form submissions where a user want to bookmark the result.
• There is a limit to how much data you can place in a URL (varies between browsers), therefore,
you cannot be sure that all of the form-data will be correctly transferred. Never use the "get"
method to pass sensitive information! (password or other sensitive information will be visible in the
browser's address bar)
• The "post" method:
• This method sends the form-data as an HTTP post transaction.
• Form submissions with the "post" method cannot be bookmarked.
• The "post" method is more robust and secure than "get", and "post" does not have size limitations
or different types of input elements, such as: text fields, checkboxes, radio buttons, submit
• Input Type Text
• <input type="text"> defines a single-line text input field.
• Example:
• <input type="text" id="fname" name="fname"><br>
• Input Type Password
• <input type="password"> defines a password field.
• <input type="password" id="pwd" name="pwd">
• Input Type Submit
• <input type="submit">
• defines a button for submitting form data to a form-handler.
• The form-handler is typically a server page with a script for processing input data.
• The form-handler is specified in the form's action attribute.
<form action="register.php">
<input type="text" id="fname" name="fname" value="John"><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit">
</form>
• Input Type Reset
• <input type="reset"> defines a reset button that will reset all form values to their default
values.
• Input Type Radio
<input type="radio"> defines a radio button. Radio buttons let a user select ONLY
ONE of a limited number of choices
<input type="radio" id="male" name="gender" value="Male">
<input type="radio" id="female" name="gender" value="Female">
• Input Type Checkbox
<input type="checkbox"> defines a checkbox. Checkboxes let a user select ZERO
or MORE options of a limited number of choices.
<input type="checkbox" id="vehicle1" name="vehicle1" value="Bike">
<input type="checkbox" id="vehicle2" name="vehicle2" value="Car">
• Input Type Button
<input type="button"> defines a button.
<input type="button" onclick="alert('Hello!')" value="Click Me!">
• Input Type Color
The <input type="color"> is used for input fields that should contain a color.
Depending on browser support, a color picker can show up in the input field.
<input type="color" id="favcolor" name="favcolor">
• Input Type Date
• The <input type="date"> is used for input fields that should contain a date. Depending on
browser support, a date picker can show up in the input field. You can also use the min
and max attributes to add restrictions to dates. The <input type="month"> allows the user
to select a month and year. The <input type="week"> allows the user to select a week
and year.
<input type="date" id="datemax" name="datemax" max="1979-12-31">
<input type="date" id="datemin" name="datemin" min="2000-01-02">
<input type="month" id="bdaymonth" name="bdaymonth">
<input type="week" id="week" name="week">
• Input Type Email
• The <input type="email"> is used for input fields that should contain an e-mail address.
Depending on browser support, the e-mail address can be automatically validated when
submitted. Some smartphones recognize the email type, and add ".com" to the keyboard
to match email input.
• <input type="email" id="email" name="email">
• Input Type File
The <input type="file"> defines a file-select field and a "Browse" button for file uploads.
<input type="file" id="myfile" name="myfile">
• Input Type Hidden
• The <input type="hidden"> defines a hidden input field (not visible to a user). A hidden
field lets web developers include data that cannot be seen or modified by users when a
form is submitted. A hidden field often stores what database record that needs to be
updated when the form is submitted. While the value is not displayed to the user in the
page's content, it is visible (and can be edited) using any browser's developer tools or
"View Source" functionality. Do not use hidden inputs as a form of security!
<input type="hidden" id="custId" name="custId" value="3487">
• Input Type Number
• The <input type="number"> defines a numeric input field. You can also set restrictions on
what numbers are accepted.
• <input type="number" id="quantity" name="quantity" min="1" max="5">
• Input Type Tel
• The <input type="tel"> is used for input fields that should contain a telephone number.
• <input type="tel" id="phone" name="phone" pattern="[0-9]{3}-[0-9]{2}-[0-9]{3}">
• Input Type Url
• The <input type="url"> is used for input fields that should contain a URL address.
Depending on browser support, the url field can be automatically validated when
submitted.
• <input type="url" id="homepage" name="homepage">
Input Restrictions
Attribute Description
checked Specifies that an input field should be pre-selected when the
page loads (for type="checkbox" or type="radio")
disabled Specifies that an input field should be disabled
max Specifies the maximum value for an input field
maxlength Specifies the maximum number of character for an input field
min Specifies the minimum value for an input field
pattern Specifies a regular expression to check the input value against
readonly Specifies that an input field is read only (cannot be changed)
required Specifies that an input field is required (must be filled out)
size Specifies the width (in characters) of an input field
step Specifies the legal number intervals for an input field
form action="/action_page.php" style="background-color:lightblue; width:30%;">
<h3>Fill in your profile here</h3>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" required><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" required><br>
Male:<input type="radio" id="male" name="gender" value="Male" required>
Female<input type="radio" id="female" name="gender" value="Female" required> <br>
Programming:<input type="checkbox" id="programming" name="programming" value="Programming" >
Database:<input type="checkbox" id="database" name="database" value="Database" checked> <br>
Favorite Color:<input type="color" id="favcolor" name="favcolor"><br>
Birth Date:<input type="date" id="datemax" name="datemax" max="2000-12-31"><br>
Phone no.<input type="tel" id="phone" name="phone" placeholder="123-45-679" pattern="[0-9]{3}-[0-
9]{2}-[0-9]{3}"> <br>
Email:<input type="email" id="email" name="email"><br>
<label for="pwd">Password:</label><br>
<input type="password" id="pwd" name="pwd"><br><br>
Attachment: <input type="file" id="myfile" name="myfile"><br>
<input type="submit" value="Submit"><input type="reset" value="Reset">
</form>
HTML Links
• HTML links are hyperlinks.
• You can click on a link and jump to another document. When you move the mouse over a
link, the mouse arrow will turn into a little hand.
• Note: A link does not have to be text. A link can be an image or any other HTML element!
• The HTML <a> tag defines a hyperlink. It has the following syntax:
<a href="url">link text</a>
• The most important attribute of the <a> element is the href attribute, which indicates the
link's destination.
• The link text is the part that will be visible to the reader.
• Clicking on the link text, will send the reader to the specified URL address.
• Example
• This example shows how to create a link to W3Schools.com:
<a href="https://www.w3schools.com/">Visit W3Schools.com!</a>
• By default, An unvisited link is underlined and blue.
• A visited link is underlined and purple.
• An active link is underlined and red.
• But remember that Links can of course be styled with CSS, to get another look!
• By default, the linked page will be displayed in the current browser window.
• To change this, you must specify another target for the link.
• The target attribute specifies where to open the linked document. The
target attribute can have one of the following values:
• _self - Default. Opens the document in the same window/tab as it was clicked
• _blank - Opens the document in a new window or tab
• _parent - Opens the document in the parent frame
• _top - Opens the document in the full body of the window
Summarizing HTML using it all at a place
• Basic structure of HTML
<!DOCTYPE html>
<html>
<head>
<title>Ethiopia in my tongue </title>
<style>

</style>
</head>
<body>

</body>
</html>
The output…
• Ordered list, header, link and style ID
<ul>
<h1 id="myHeader">MY COUNTRY - ETHIOPIA</h1>
<li><a href="#home"> Home</a></li>
<li><a href="#news"> News</a></li>
<li><a href="#contact"> Contact</a></li>
<li><a href="#about"> About</a></li>
</ul>
#myHeader {
background-color: DodgerBlue;
color: black;
padding: 20px;
text-align: left;
}
The output…
• Copy all the content from the home page, create new page and
paste. Then change the name of the page as in the following list.
<ul>
<h1 id="myHeader" >MY COUNTRY - ETHIOPIA</h1>
<li><a href="new 1.html"> Home</a></li>
<li><a href="news.html"> News</a></li>
<li><a href="contact.html"> Contact</a></li>
<li><a href="about.html"> About</a></li>
</ul>
<style>
ul { list-style-type: none;
background-color:DodgerBlue;
overflow:hidden;
}
li a{ color:black;
display:block;
padding:16px;
}
li { float:left; }
li a:hover { background-color:white; }
</style>
• Div, h2, style attribute, align attribute, span
<div style="background-
color:#454545;color:white;padding:20px;">
<h2 align="center">
<span style="color:#39FF14;"> Eth </span>
<span style="color:yellow;"> io </span>
<span style="color:red;"> pia </span>
</h2>
<p>
Ethiopia, officially the Federal Democratic Republic of Ethiopia,
is a landlocked country in the Horn of Africa.
</p>
</div>
Form elements
<form action="#" style="background-color:lightblue; width:30%;">
<h3>Fill in your profile here</h3>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" required><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" required><br>
Male:<input type="radio" id="male" name="gender" value="Male" required>
Female<input type="radio" id="female" name="gender" value="Female"
required> <br>
Programming:<input type="checkbox" id="programming"
name="programming" value="Programming" >
Database:<input type="checkbox" id="database" name="database"
value="Database" checked> <br>
</form>
Form elements
<form action="#" style="background-color:lightblue; width:30%;">
Favorite Color:<input type="color" id="favcolor" name="favcolor"><br>
Birth Date:<input type="date" id="datemax" name="datemax" max="2000-12-
31"><br>
Phone no.<input type="tel" id="phone" name="phone" placeholder="123-45-
679" pattern="[0-9]{3}-[0-9]{2}-[0-9]{3}"> <br>
Email:<input type="email" id="email" name="email"><br>
<label for="pwd">Password:</label><br>
<input type="password" id="pwd" name="pwd"><br><br>
Attachment: <input type="file" id="myfile" name="myfile"><br>
<input type="submit" value="Submit"><input type="reset" value="Reset">
</form> label {
display:inline-block;
width:150px;
font-weight:bold;
}
<iframe src="Test.html" style="border:none;" height="300" width="100%"
title="Iframe Example"></iframe>
CA SC A D E D S T Y L E
SHEET S - C S S
CHAPTER - 3
Introduction
• CSS is the language we use to define styles for your web pages,
including the design, layout and variations in display for different
devices and screen sizes.
• A CSS rule consists of a selector and a declaration block.

• The selector points to the HTML element you want to style.


• The declaration block contains one or more declarations separated by
semicolons.
• Each declaration includes a CSS property name and a value, separated by a
colon.
<html>
<head> p{
<link rel="stylesheet" href="extcss.css"> color:red;
<style> font-size:25px;
h1 { }
font-size:25px;
color:blue;
}
</style>
</head>
<body>
<h1> Css header 1 for internet programming
</h1>
<h2 style="color:lightgreen; font-size:25px;">
Css header 2 for internet programming </h2>
<p> Internet Programming! </p>
</body>
</html>
<html>
<head> p{
<link rel="stylesheet" color:red;
href="extcss.css"> font-size:25px;
<style> }
p{
font-size:25px;
color:blue;
}
</style>
</head>
<body>
<p style="color:lightgreen; font-size:25px;">
Paragraph </p>
</body>
• What style will be used when there is more than one style specified for an
HTML element?
• It will be according to the following priority order:
• Inline style (inside an HTML element)
• External and internal style sheets (in the head section)
• Browser default
• So, an inline style has the highest priority, and will override external and
internal styles and browser defaults.
CSS Selectors
• We can divide CSS selectors into five categories:
• Simple selectors , Combinator selectors, Pseudo-class selectors, Pseudo-
elements, Attribute selectors
• Simple selectors
• select elements based on name, id, class
• The element selector selects HTML elements based on the element name.
p{
text-align: center;
color: red;
}
• The id selector uses the id attribute of an HTML element to select a specific
element.
#para1 {
text-align: center;
color: red;
}
<html>
<head>
<style>
#para1 {
text-align: center;
color: red; }
p{
text-align: left;
color: blue;
}
</style>
</head>
<body>
<p id="para1">Hello World!</p>
<p>This paragraph is not affected by the style.</p>
</body>
</html>
• The class selector
• selects HTML elements with a specific class attribute.
• To select elements with a specific class, write a period (.) character, followed by the class
name.
• A class name cannot start with a number!
.center {
text-align: center;
color: red;
}
• You can also specify that only specific HTML elements should be affected by a class.
• In this example only <p> elements with class="center" will be red and center-aligned
p.center {
text-align: center;
color: red;
}
• HTML elements can also refer to more than one class.
• In this example the <p> element will be styled according to class="center" and to
class="large"
<p class="center large">This paragraph refers to two classes.</p>
<html>
<head>
<link rel="stylesheet" type="text/css" href="extcss.css">
</head>
.center{
<body>
text-align:center;
<p class="center large">Paragraph</p> color:red;
<h1 class="center">Paragraph</h1> }
</body> p.center{
</html> text-align:center;
color:red;
}
.large{
font-size:30px;
}
• The grouping selector
• selects all the HTML elements with the same style definitions.
• It will be better to group the selectors, to minimize the code. To group selectors, separate
each selector with a comma like the following. Compare both options.
h1, h2, p {
text-align: center;
color: red;
}
h1 {
text-align: center;
color: red;
}
h2 {
text-align: center;
color: red;
}
p{
text-align: center;
color: red;
}
Combinator selectors
• Combinator selectors select elements based on a specific relationship between them.
• A Combinator is something that explains the relationship between the selectors.
• A CSS selector can contain more than one simple selector.
• Between the simple selectors, we can include a Combinator. There are four different Combinator in CSS:
• descendant selector (space)
• The descendant selector matches all elements that are descendants of a specified element.
• div p {
• background-color: yellow;
• }
• child selector (>)
• The child selector selects all elements that are the children of a specified element. Note that all descendants may not be children.
• div > p {
• background-color: yellow;
• }
• adjacent sibling selector (+)
• The adjacent sibling selector is used to select an element that is directly after another specific element. Sibling elements must have
the same parent element, and "adjacent" means "immediately following".
• div + p {
• background-color: yellow;
• }
• general sibling selector (~)
• The general sibling selector selects all elements that are next siblings of a specified element.
• div ~ p {
• background-color: yellow;
• }
<html>
<head>
<link rel="stylesheet" type="text/css" href="extcss.css">
</head>
<body> div p { /* descendant selector */
<div> background-color:yellow;
<p>Paragraph 1</p>
}
<p>Paragraph 2</p>
<section>
div > p{ /* child selector */
<p> Paragraph 3 </p> background-color:red;
</section> }
</div> div ~ p{ /* general sibiling selector */
<p>Paragraph 4 </p> background-color:green;
<p>Paragraph 5 </p> }
</body> div + p{ /* adjecent sibiling selector
</html> */
background-color:blue;
• Pseudo-class selectors
• Pseudo-class selectors select elements based on a certain state.
• A pseudo-class is used to define a special state of an element.
• For example, it can be used to: Style an element when a user mouses over it or Style visited and
unvisited links differently or Style an element when it gets focus.
• Syntax
selector:pseudo-class {
property: value;
}
• /* visited link */
a:visited {
color: #00FF00;
}
/* mouse over link */
a:hover {
color: #FF00FF;
}
/* selected link */
a:active {
color: #0000FF;
}
• Pseudo-elements selectors
• Pseudo-elements selectors select and style a part of an element.
• A CSS pseudo-element is used to style specified parts of an element.
• For example, it can be used to: Style the first letter, or line, of an element,
Insert content before, or after, the content of an element.
<!DOCTYPE html>
• Example <html>
p::first-line { <head>
color: #ff0000; <style>
font-variant: small-caps; p::first-letter {
color: #ff0000;
}
font-size: 200%;
p::first-letter { }
</style>
color: #ff0000;
</head>
font-size: xx-large; <body>
} <p>You can use the ::first-
letter pseudo-element to add a
p::first-line {
special effect to the first
color: #0000ff; character of a text!</p>
font-variant: small-caps; </body>
</html>
}
• Attribute selectors
• select elements based on an attribute or attribute value
• It is possible to style HTML elements that have specific attributes or attribute
values.
• The [attribute] selector is used to select elements with a specified attribute.
Example:
a[target] {
background-color: yellow;
}
Basic CSS styles
• CSS Comments
/* text-align: center;
color: red; } */
// text-align: left; }
• CSS Colors
• <h1 style="background-color:DodgerBlue;">Hello World</h1>
• <h1 style="color:Tomato;">Hello World</h1>
• The lower value, the more transparent.
• opacity: 0.3;
• The alpha parameter is a number between 0.0 (fully transparent) and
1.0 (fully opaque).
• background: rgba(0, 128, 0, 0.3)
• CSS Background images
• The background-image property specifies an image to use as the background of
an element.
body {
background-image: url("paper.gif");
}
• By default, the background-image property repeats an image both horizontally
and vertically. Some images should be repeated only horizontally or vertically.
• To repeat an image vertically, set
• background-repeat: repeat-x;
• To repeat an image vertically, set
• background-repeat: repeat-y;
• Showing the background image only once is also specified by:
• background-repeat: no-repeat;
• The background-position property is used to specify the position of the
background image.
• background-position Sets the starting position of a background image.
• The first value is the horizontal position and the second value is the vertical.
Example:
• background-position: right top;
• The background-attachment property specifies whether the background image
should scroll or be fixed (will not scroll with the rest of the page).
• background-attachment: fixed;
• background-attachment: scroll;
• To shorten the code, it is also possible to specify all the background properties in
one single property.
• This is called a shorthand property.
• When using the shorthand property the order of the property values is:
background-color background-image background-repeat background-
attachment background-position. It does not matter if one of the property
values is missing, as long as the other ones are in this order. Example:
• background: #ffffff url("img_tree.png") no-repeat fixed right top;
• CSS Borders
• The CSS border properties allow you to specify the style, width, and color of an
element's border.
• The allowed values of style are: dotted, dashed, solid, double, groove, ridge, inset, outset,
none, hidden.
• The border-style property can have from one to four values (for the top border,
right border, bottom border, and the left border).
• None of the OTHER CSS border will have ANY effect unless the border-style
property is set.
• Example:
• border-style: dotted;
• The border-width property specifies the width of the four borders.
• Example:
• border-width: 5px;
• border-width: medium;
• The border-color property is used to set the color of the four borders.
• Example:
• border-color: red;
• There are also properties for specifying each of the borders (top, right, bottom,
and left).
• Example
• border-top-style: dotted;
• border-right-style: solid;
• border-bottom-style: dotted;
• border-left-style: solid;
• If the border-style property has four values: (The order is top right bottom left)
• border-style: dotted solid double dashed;
• top border is dotted
• right border is solid
• bottom border is double
• left border is dashed
• If the border-style property has three values:
• border-style: dotted solid double;
• top border is dotted
• right and left borders are solid
• bottom border is double
• If the border-style property has two values:
• border-style: dotted solid;
• top and bottom borders are dotted
• right and left borders are solid
• If the border-style property has one value:
• border-style: dotted;
• all four borders are dotted
• To shorten the code, it is also possible to specify all the individual border
properties in one property.
• The border property is a shorthand property for the following individual border
properties:
• border-width
• border-style (required)
• border-color
• Example
• p{
border: 5px solid red;
}
• You can also specify all the individual border properties for just one side:
• p{
border-left: 6px solid red;
}
• The border-radius property is used to add rounded borders to an element.
• Example
• p{
border: 2px solid red;
border-radius: 5px;
}
<html>
<head>
<title> </title>
<link rel="stylesheet" href="web.css">
</head>
<body>
<div class="main">
<h1>Center of Public Opinion</h1>
</div>
</body>
</html>
body {
background-color:dodgerblue; /* background-color */
border-style: dotted solid double dashed;
border:5px solid white; /* Short hand property of border width, style,
color*/
border-radius:10px; /* Rounded rectangle */
}
h1{
color:white; /* Text color */
background-color:dodgerblue;
text-align:center;
opacity:0.8; /* Transparency */
//background-image: url("eth2.png");
//background-repeat:no-repeat;
//background-repeat:x-repeat;
background-attachment: scroll; /* bg attachment */
background-position: right top; /* position */
//background:gray url("eth2.png") no-repeat fixed right top; /* short hand
property */
//height:100%;
text-decoration:bold;
font-size:50px;
}
.main{
background-color:#F5F5Ff;
height:100%;
}
• CSS Margins
• Margins are used to create space around elements, outside of any defined
borders.
• CSS has properties for specifying the margin for each side of an element; margin-
top, margin-right, margin-bottom and margin-left.
• All the margin properties can have the following values:
• auto - the browser calculates the margin
• length - specifies a margin in px, pt, cm, etc.
• % - specifies a margin in % of the width of the containing element
• inherit - specifies that the margin should be inherited from the parent element
• NB: Negative values are allowed.
• Example
• Set different margins for all four sides of a <p> element:
p{
margin-top: 100px;
margin-bottom: 100px;
margin-right: 150px;
margin-left: 80px;
}
• To shorten the code, it is possible to specify all the margin properties in one
property.
• If the margin property has four values:
• margin: 25px 50px 75px 100px;
• top margin is 25px, right margin is 50px, bottom margin is 75px, left margin is 100px
• If the margin property has three values:
• margin: 25px 50px 75px;
• top margin is 25px, right and left margins are 50px, bottom margin is 75px
• If the margin property has two values:
• margin: 25px 50px;
• top and bottom margins are 25px, right and left margins are 50px
• If the margin property has one value:
• margin: 25px;
• all four margins are 25px
• You can set the margin property to auto to horizontally center the element within its
container.
• CSS Padding
• Padding is used to create space around an element's content, inside of any
defined borders.
• CSS has properties for specifying the padding for each side of an element:
padding-top, padding-right, padding-bottom, padding-left.
• All the padding properties can have the following values:
• length - specifies a padding in px, pt, cm, etc.
• % - specifies a padding in % of the width of the containing element
• inherit - specifies that the padding should be inherited from the parent element
• Note: Negative values are not allowed.
• Example:
Set different padding for all four sides of a <div> element:
div {
padding-top: 50px;
padding-right: 30px;
padding-bottom: 50px;
padding-left: 80px;
}
• To shorten the code, it is possible to specify all the padding properties in one
property.
• If the padding property has four values:
• padding: 25px 50px 75px 100px;
• top is 25px, right is 50px, bottom is 75px, left is 100px
• If the padding property has three values:
• padding: 25px 50px 75px;
• top is 25px, right and left are 50px, bottom is 75px
• If the padding property has two values:
• padding: 25px 50px;
• top and bottom are 25px, right and left are 50px
• If the padding property has one value:
• padding: 25px;
• all four paddings are 25px
• The CSS width property specifies the width of the element's content area.
• The content area is the portion inside the padding, border, and margin of an element.
• So, if an element has a specified width, the padding added to that element will be added to the
total width of the element.
• Example: Compare the outputs of the following div elements.
<style>
div.ex1 {
width: 300px;
background-color: yellow;
}
div.ex2 {
width: 300px;
padding: 25px;
background-color: lightblue;
}
</style>
• Here, the <div> element is given a width of 300px. However, the actual width of the <div> element
will be 350px (300px + 25px of left padding + 25px of right padding).
• To keep the width at 300px, no matter the amount of padding, you can use the box-sizing property.
This causes the element to maintain its actual width; if you increase the padding, the available
content space will decrease.
• div {
width: 300px;
padding: 25px;
box-sizing: border-box;
}
• CSS Box Model
• In CSS, the term "box model" is used when talking about design and layout.
• All HTML elements can be considered as boxes.
• The CSS box model is essentially a box that wraps around every HTML element.
• It consists of: margins, borders, padding, and the actual content.
• When you set the width and height properties of an element with CSS, you just
set the width and height of the content area.
• To calculate the full size of an element, you must also add padding, borders
and margins.
• The total width of an element should be calculated like this:
• Total element width = width + left padding + right padding + left border + right border +
left margin + right margin
• The total height of an element should be calculated like this:
• Total element height = height + top padding + bottom padding + top border + bottom
border + top margin + bottom margin
• CSS Outline
• An outline is a line drawn outside the element's border.
• CSS has the following outline properties:
• outline-style
• outline-color
• outline-width
• outline-offset
• outline
• Outline differs from borders! Unlike border, the outline is drawn outside the
element's border, and may overlap other content.
• Also, the outline is NOT a part of the element's dimensions; the element's
total width and height is not affected by the width of the outline.
• Please refer the values from border style.
• Example:
• outline-style: dotted;
CSS Text
• The color property is used to set the color of the text. The color is specified by:
• a color name - like "red"
• a HEX value - like "#ff0000"
• an RGB value - like "rgb(255,0,0)"
• The text-align property is used to set the horizontal alignment of a text. A text can
be left or right aligned, centered, or justified.
• text-align: center;
• text-align: left;
• text-align: right;
• text-align: justify;
• The vertical-align property sets the vertical alignment of an element.
• Example: vertical-align: text-top;
• The text-decoration-line property is used to add a decoration line to text.
• Example:
• text-decoration-line: overline;
• text-decoration-line: line-through;
• text-decoration-line: underline;
• text-decoration-line: overline underline;
• The text-decoration-color property is used to set the color of the decoration line.
• text-decoration-color: red;
• The text-transform property is used to specify uppercase and lowercase letters in a
text. It can be used to turn everything into uppercase or lowercase letters, or capitalize
the first letter of each word:
• text-transform: uppercase;
• text-transform: lowercase;
• text-transform: capitalize;
• The text-indent property is used to specify the indentation of the first line of a text:
• text-indent: 50px;
• The letter-spacing property is used to specify the space between the characters in a
text.
• letter-spacing: 5px;
• The line-height property is used to specify the space between lines:
• line-height: 0.8;
• The word-spacing property is used to specify the space between the words in a text.
• word-spacing: 10px;
• The text-shadow property adds shadow to text.
• Horizontal shadow, vertical shadow, shadow color, and a blur effect respectively are specified as
• text-shadow: 2px 2px 5px red;
• In CSS, we use the font-family property to specify the font of a text.
• If the font name is more than one word, it must be in quotation marks, like:
"Times New Roman".
• The font-family property should hold several font names as a "fallback" system, to
ensure maximum compatibility between browsers/operating systems.
• Start with the font you want, and end with a generic family (to let the browser pick a similar
font in the generic family, if no other fonts are available).
• The font names should be separated with comma.
• Example:
• .p1 {
font-family: "Times New Roman", Times, serif;
}
.p2 {
font-family: Arial, Helvetica, sans-serif;
}
.p3 {
font-family: "Lucida Console", "Courier New", monospace;
}
• The font-size property sets the size of the text.
• If you do not specify a font size, the default size for normal text, like paragraphs, is 16px
(16px=1em)
• font-size: 40px;
• The text size can be set with a vw unit, which means the "viewport width".
• That way the text size will follow the size of the browser window.
• Viewport is the browser window size.
• 1vw = 1% of viewport width. If the viewport is 50cm wide, 1vw is 0.5cm.
• <h1 style="font-size:10vw">Hello World</h1>
• The font property is a shorthand property for: font-style, font-variant, font-weight, font-
size/line-height, and font-family. Example:
• font: italic small-caps bold 12px/30px Georgia, serif;
CSS Links
• Links can be styled differently depending on what state they are in. The four links
states are:
• a:link - a normal, unvisited link
• a:visited - a link the user has visited
• a:hover - a link when the user mouses over it
• a:active - a link the moment it is clicked
• When setting the style for several link states, there are some order rules. a:hover
MUST come after a:link and a:visited. a:active MUST come after a:hover
• Example:
/* unvisited link */
a:link {
color: red;
}
• /* visited link */
a:visited {
color: green;
}
• /* mouse over link */
a:hover {
color: hotpink;
}
• /* selected link */
a:active {
color: blue;
}
• CSS Lists
• The list-style-type property specifies the type of list item marker. Example:
• ul.a {
list-style-type: circle; }
ul.b {
list-style-type: square; }
ol.c {
list-style-type: upper-roman; }
ol.d { list-style-type: lower-alpha; }
• The list-style-image property specifies an image as the list item marker. Example:
• list-style-image: url('sqpurple.gif');
• The list-style-position property specifies the position of the list-item markers (bullet
points).
• Example:
• list-style-position: outside;
• list-style-position: inside;
• When using the shorthand property, the order of the property values are: list-style-
type, list-style-position, list-style-image.
• Example:
• list-style: square inside url("sqpurple.gif");
• CSS Tables
• To specify table borders in CSS, use the border property.
• Example
• table, th, td {
border: 1px solid;
}
• The width and height of a table are defined by the width and height properties.
• table {
width: 100%;
}
• The text-align property sets the horizontal alignment (like left, right, or center) of the
content in <th> or <td>.
• td {
text-align: center;
}
• The vertical-align property sets the vertical alignment (like top, bottom, or middle) of
the content in <th> or <td>.
• td {
height: 50px;
vertical-align: bottom;
}
CSS Layout
• The display property specifies if/how an element is displayed.
• Every HTML element has a default display value depending on what type of element it is.
• The default display value for most elements is block or inline.
• However, you can override this.
• Changing an inline element to a block element, or vice versa, can be useful for making the
page look a specific way, and still follow the web standards.
Example: li {
display: inline;
}
• Hiding an element can be done by setting the display property to none.
h1 {
display: none;
}
• visibility:hidden; also hides an element. However, the element will still take up the same space
as before.
h1.hidden {
visibility: hidden;
}
• Setting the width of a block-level element will prevent it from stretching out to the
edges of its container.
• Then, you can set the margins to auto, to horizontally center the element within its
container.
• The element will take up the specified width, and the remaining space will be split
equally between the two margins.
• Problem occurs when the browser window is smaller than the width of the element.
• The browser then adds a horizontal scrollbar to the page.
• Using max-width instead, in this situation, will improve the browser's handling of
small windows.
• This is important when making a site usable on small devices. Example:
• max-width: 500px;
• Drag the browser window to smaller than 500px wide, to see the difference between the two divs!
• The position property specifies the type of positioning method used for an
element (static, relative, fixed, absolute or sticky).
• Elements are then positioned using the top, bottom, left, and right properties. However,
these properties will not work unless the position property is set first. They also work
differently depending on the position value.
• HTML elements are positioned static by default. Static positioned elements are not
affected by the top, bottom, left, and right properties. An element with position: static; is
not positioned in any special way; it is always positioned according to the normal flow of
the page.
• Example
• div.static {
position: static;
border: 3px solid #73AD21;
}
• An element with position: relative; is positioned relative to its normal position. Setting the top,
right, bottom, and left properties of a relatively-positioned element will cause it to be adjusted away
from its normal position. Other content will not be adjusted to fit into any gap left by the element.
• Example
• div.relative {
position: relative;
left: 30px;
border: 3px solid #73AD21;
}
o An element with position: fixed; is positioned relative to the viewport, which means it always stays in
the same place even if the page is scrolled.
o The top, right, bottom, and left properties are used to position the element.
o A fixed element does not leave a gap in the page where it would normally have been located.
• Example
• div.fixed {
position: fixed;
bottom: 0;
right: 0;
width: 300px;
border: 3px solid #73AD21;
}
o An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead
of positioned relative to the viewport, like fixed).
o However; if an absolute positioned element has no positioned ancestors, it uses the document body,
and moves along with page scrolling.
o Note: Absolute positioned elements are removed from the normal flow, and can overlap elements.
o An element with position: sticky; is positioned based on the user's scroll position.
o A sticky element toggles between relative and fixed, depending on the scroll position.
o It is positioned relative until a given offset position is met in the viewport - then it "sticks" in place (like
position:fixed).
• Example
• div.sticky {
position: sticky;
top: 0;
background-color: green;
border: 2px solid #4CAF50;
}
o When elements are positioned, they can overlap other elements. The z-index
property specifies the stack order of an element (which element should be placed in
front of, or behind, the others).
o An element can have a positive or negative stack order.
o z-index only works on positioned elements (position: absolute, position: relative,
position: fixed, or position: sticky) and flex items (elements that are direct children of
display: flex elements). Example
• img {
position: absolute;
left: 0px;
top: 0px;
z-index: -1;
}
o The CSS overflow property controls what happens to content that is too big
to fit into an area.
o The overflow property specifies whether to clip the content or to add scrollbars when the
content of an element is too big to fit in the specified area.
o The overflow property has the following values:
o visible - Default. The overflow is not clipped. The content renders outside the element's box
o hidden - The overflow is clipped, and the rest of the content will be invisible
o scroll - The overflow is clipped, and a scrollbar is added to see the rest of the content
o auto - Similar to scroll, but it adds scrollbars only when necessary
• Note: The overflow property only works for block elements with a specified height.
• By default, the overflow is visible, meaning that it is not clipped and it renders outside
the element's box.
• Example
• div { width: 200px; overflow: scroll;
}
o The overflow-x and overflow-y properties specifies whether to change the overflow
of content just horizontally or vertically (or both):
o overflow-x specifies what to do with the left/right edges of the content.
o overflow-y specifies what to do with the top/bottom edges of the content.

• Example
• div {
overflow-x: hidden; /* Hide horizontal scrollbar */
overflow-y: scroll; /* Add vertical scrollbar */
}
• The float property is used for positioning and formatting content e.g. let
an image float left to the text in a container.
• The float property can have one of the following values:
• left - The element floats to the left of its container
• right - The element floats to the right of its container
• none - The element does not float (will be displayed just where it occurs in the
text). This is default
• inherit - The element inherits the float value of its parent
• In its simplest use, the float property can be used to wrap text around
images.
Example:
img {
float: right;
}
<style>
div {
float: left;
padding: 15px;
}
.div1 { background: red; }
.div2 { background: yellow; }
.div3 { background: green;}
</style>
<body>
<div class="div1">Div 1</div>
<div class="div2">Div 2</div>
<div class="div3">Div 3</div>
</body>
JavaScript
Chapter - 4
Introduction
• As of 2022, 98% of websites use JavaScript on the client side for
webpage behavior, often incorporating third-party libraries.
• All major web browsers have a dedicated JavaScript engine to execute
the code on users' devices.
• JavaScript It is multi-paradigm, supporting event-driven, functional,
and imperative programming styles.
• It has application programming interfaces (APIs) for working with text,
dates, regular expressions, standard data structures, and the Document
Object Model (DOM).
• An application programming interface (API):
• is a way for two or more computer programs to communicate with each other.
• It is a type of software interface, offering a service to other pieces of software
• In contrast to a user interface, which connects a computer to a person, an
application programming interface connects computers or pieces of software to
each other.
• The Document Object Model (DOM):
• is a programming interface for HTML(HyperText Markup
Language) and XML(Extensible markup language) documents.
• With DOM, we can easily access and manipulate tags, IDs, classes, Attributes, or
Elements of HTML using commands or methods provided by the Document
object.
• Using DOM, the JavaScript gets access to HTML as well as CSS of the web page
and can also add behavior to the HTML elements.
• so basically Document Object Model is an API that represents and interacts
with HTML or XML documents.
• Although Java and JavaScript are similar in name, syntax, and
respective standard libraries, the two languages are distinct and differ
greatly in design.
• JavaScript and Java are completely different languages, both in concept
and design.
• JavaScript was invented by Brendan Eich in 1995, and became an ECMA
standard in 1997.
• ECMA-262 is the official name of the standard. ECMAScript is the official name of
the language.
• JavaScript was initially created to “make web pages alive”.
• The programs in this language are called scripts.
• They can be written right in a web page’s HTML and run automatically as the
page loads.
• Scripts are provided and executed as plain text.
• They don’t need special preparation or compilation to run.
• When JavaScript was created, it initially had another name: “LiveScript”.
• But Java was very popular at that time, so it was decided that positioning a
new language as a “younger brother” of Java would help.
• But as it evolved, JavaScript became a fully independent language with its
own specification called ECMAScript, and now it has no relation to Java at
all.
• ECMAScript is a JavaScript standard intended to ensure the interoperability of web
pages across different browsers.
• It is standardized by Ecma International in the document ECMA-262.
• Ecma International is a nonprofit standards organization for information and
communication systems.
• It acquired its current name in 1994, when the European Computer Manufacturers
Association (ECMA) changed its name to reflect the organization's global reach and
activities.
• As a consequence, the name is no longer considered an acronym and no longer uses
Starting with JavaScript
• In HTML, JavaScript code is inserted between <script> and </script> tags.
• Old JavaScript examples may use a type attribute: <script
type="text/javascript">.
• The type attribute is not required. JavaScript is the default scripting language in
HTML.
• You can place any number of scripts in an HTML document.
• Scripts can be placed in the <body>, or in the <head> section of an HTML
page, or in both.
• Placing scripts at the bottom of the <body> element improves the display
speed, because script interpretation slows down the display.
• Scripts can also be placed in external files.
• External scripts are practical when the same code is used in many different
web pages.
• JavaScript files have the file extension .js.
• To use an external script, put the name of the script file in the src (source)
attribute of a <script> tag:
• <script src="myScript.js"></script>
• You can place an external script reference in <head> or <body> as you like.
• The script will behave as if it was located exactly where the <script> tag is
located.
• External scripts cannot contain <script> tags.
• Placing scripts in external files has some advantages:
• It separates HTML and code
• It makes HTML and JavaScript easier to read and maintain
• Cached JavaScript files can speed up page loads
• To add several script files to one page - use several script tags.

• <script src="myScript1.js"></script>
<script src="myScript2.js"></script>
Example 1 - JavaScript Can Change HTML Content
One of many JavaScript HTML methods is getElementById().
<!DOCTYPE html>
<html>
<body>
<p id="demo">JavaScript can change HTML content.</p>
<button type="button" onclick='document.getElementById("demo").innerHTML
= "Hello JavaScript!"'>Click Me!</button>
</body>
</html>
Example 2 - JavaScript Can Change HTML Attributes
<!DOCTYPE html>
<html>
<body>
<p>In this case JavaScript changes the value of the src (source)
attribute of an image.</p>
<button
onclick="document.getElementById('myImage').src='pic_bulbon.gif'">
Turn on the light</button>
<img id="myImage" src="pic_bulboff.gif" style="width:100px">
<button
onclick="document.getElementById('myImage').src='pic_bulboff.gif'">
Turn off the light</button>
</body>
</html>
Example 3 - JavaScript Can Change HTML Styles (CSS)
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change the style of an HTML element.</p>
<button type="button"
onclick="document.getElementById('demo').style.fontSize='35px'">Click
Me!</button>
</body>
</html>
Example 4 - JavaScript Can Hide HTML Elements
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can hide HTML elements.</p>
<button type="button"
onclick="document.getElementById('demo').style.display='none'">Click
Me!</button>
</body>
</html>
The HTML DOM Tree of Objects
• The DOM is a W3C (World Wide Web Consortium) standard.
• The DOM defines a standard for accessing documents.
• The W3C Document Object Model (DOM) is a platform and language-neutral interface that
allows programs and scripts to dynamically access and update the content, structure, and
style of a document. The W3C DOM standard is separated into 3 different parts:
• Core DOM - standard model for all document types
• XML DOM - standard model for XML documents
• HTML DOM - standard model for HTML documents
• The HTML DOM can be accessed with JavaScript (and with other programming languages).
• In the DOM, all HTML elements are defined as objects.
• The programming interface is the properties and methods of each object.
• A property is a value that you can get or set (like changing the content of an HTML
element).
• A method is an action you can do (like add or deleting an HTML element).
• The innerHTML Property
• The easiest way to get the content of an element is by using the innerHTML property.
• The innerHTML property is useful for getting or replacing the content of HTML elements.
• The innerHTML property can be used to get or change any HTML element, including <html> and
<body>.
• JavaScript HTML DOM Document
• The HTML DOM document object is the owner of all other objects in your web page.
• The document object represents your web page.
<!DOCTYPE html>
<html>
<body>
<p id="intro"></p>
<p id="demo"></p>
<p class="intro"></p>
<script>
document.getElementById("demo").innerHTML = "Paragraph by element";
const x = document.getElementsByClassName("intro");
x[0].innerHTML="Paragraph by class";
const y = document.getElementsByTagName("p");
y[0].innerHTML = "Paragraph by tag";
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<form id="frm1" action="/action_page.php">
First name: <input type="text" name="fname" value="Abebe"><br>
Last name: <input type="text" name="lname" value="Tola"><br><br>
<input type="submit" value="Submit">
</form>
<p>These are the values of each element in the form:</p>
<p id="demo"></p>
<script>
const x = document.forms["frm1"];
let text = "";
for (let i = 0; i < x.length ;i++) {
text += x.elements[i].value + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
JavaScript Output
<html>
<head>
<title>Java</title>
</head>
<body>
<p id="demo"> </p>
<script>
document.getElementById("demo").innerHTML=5+6;
alert("I am alerting. You got this?");
console.log("Hi");
</script>
<button type="button" onclick="document.write('The write property');">Click
here</button>
</body>
</html>
JavaScript Statements
• JavaScript statements are composed of: Values, Operators,
Expressions, Keywords, and Comments.
• The statements are executed, one by one, in the same order as they
are written.
• Semicolons separate JavaScript statements.
• JavaScript ignores multiple spaces.
• JavaScript statements can be grouped together in code blocks, inside
curly brackets {...}.
• JavaScript statements often start with a keyword to identify the
JavaScript action to be performed.
Keywor Description
d
var Declares a variable
let Declares a block variable
const Declares a block constant
if Marks a block of statements to be executed on a condition
switch Marks a block of statements to be executed in different cases
for Marks a block of statements to be executed in a loop
function Declares a function
return Exits a function
try Implements error handling to a block of statements
JavaScript Syntax
• JavaScript syntax is the set of rules, how JavaScript programs are
constructed.
• The JavaScript syntax defines two types of values: Fixed values and
Variable values.
• Fixed values
• Fixed values are called Literals.
• The two most important syntax rules for fixed values are:
• Numbers that are written with or without decimals and Strings that are text, written within
double or single quotes.
• Variable values
• Variable values are called Variables.
• In a programming language, variables are used to store data values.
• JavaScript uses the keywords var, let and const to declare variables.
• An equal sign is used to assign values to variables.
JavaScript Comments
• JavaScript comments can be used to explain JavaScript code, and to
make it more readable.
• JavaScript comments can also be used to prevent execution, when
testing alternative code.
• In Single Line Comments, that start with //, Any text between // and the end of the
line will be ignored by JavaScript (will not be executed).
• Example
// Change heading
• Multi-line comments start with /* and end with */. Any text between /* and */ will be
ignored by JavaScript.
• Example
/* The code below will change the heading with id = "myH"
and the paragraph with id = "myP" in my web page: */
JavaScript Variables
• There are 4 Ways to Declare a JavaScript Variable: Using var, Using let, using
const and using nothing.
• The let and const keywords were added to JavaScript in 2015. If you want your code
to run in older browsers, you must use var.
• If you want a general rule: always declare variables with const.
• If you think the value of the variable can change, use let.
• Examples:
• var x = 5;
• let x = 5;
• const price1 = 5;
const price2 = 6;
let total = price1 + price2;

• All JavaScript variables must be identified with unique names. These unique names
are called identifiers.
• Identifiers are JavaScript names used to name variables,keywords, and functions.
• The rules for legal names are the same in most programming languages.
• A JavaScript name must begin with: A letter (A-Z or a-z) , A dollar sign ($) Or an
underscore (_)
• Subsequent characters may be letters, digits, underscores, or dollar signs.
• Numbers are not allowed as the first character in names.
• All JavaScript identifiers are case sensitive.
• Creating a variable in JavaScript is called "declaring" a variable.
• After the declaration, the variable has no value (technically it is undefined).
• To assign a value to the variable, use the equal sign.
• You can also assign a value to the variable when you declare it.
• You can declare many variables in one statement by separating the variables
by comma.
• If you re-declare a JavaScript variable declared with var, it will not lose its
value. But you cannot re-declare a variable declared with let or const.
• Variables declared inside a { } block cannot be accessed from outside the
<p id="demo"></p>
<p id="demo1"></p>
<script>
{ var x=5; // can be accessed outside this block. }
{ let x=2; // cannot be accessed outside this block. }
y=6; // y variable hoisted above the declaration
var y;
document.getElementById("demo").innerHTML="x="+x+" and
"+"y="+y;
//**************************************************************
const z = 3;
z = 3.14;
z = z + 10;
document.getElementById("demo1").innerHTML=z;
//**************************************************************
</script>
JavaScript Operators
• There are different types of JavaScript operators:
• Arithmetic Operators
• Arithmetic Operators are used to perform arithmetic on numbers.
• Assignment Operators
• Assignment operators assign values to JavaScript variables.
• Comparison Operators
• Operator Description
• == equal to
• === equal value and equal type
• != not equal
• !== not equal value or not equal type
• > greater than
• < less than
• >= greater than or equal to
• <= less than or equal to
• ? ternary operator
• String Operators
• All the comparison operators above can also be used on strings alphabetically. The + can also be used to
add (concatenate) strings. Adding a number and a string will return a string.
• Logical Operators8
• Operator Description
• && logical and
• || logical or
• ! logical not
<p id="op"></p>
<p id="st"></p>
<script>
let x = 5, y=10;
let str1='Res', str2="ult=";
let female=10, male=30;
//total = female + male + " students";
total = "students=" + female + male; // evaluating expressions left
to right
str3=str1+str2; //Concatenation
// z = x + y; //Arithmetic Operator
// z=x<=y; // Comparision operator
// z = (x<y ? x : y); // ternary operator
z= !((x<y) && (y>x)); //Logical operator
document.getElementById("op").innerHTML = str3+z;
document.getElementById("st").innerHTML = total;
• JavaScript arrays are written with square brackets.
• Array items are separated by commas.
• The following code declares (creates) an array called cars, containing three items (car
names):
const cars = ["Saab", "Volvo", "BMW"];
• Array indexes are zero-based, which means the first item is [0], second is [1], and so
on.
• JavaScript objects are written with curly braces {}.
• Object properties are written as name:value pairs, separated by commas.
const person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
• The object (person) in the example above has 4 properties: firstName, lastName, age,
and eyeColor.
• You can use the JavaScript typeof operator to find the type of a JavaScript
variable.
• The typeof operator returns the type of a variable or an expression:
typeof "" // Returns "string“
<p id="dtype"></p>
<script>
const person = {firstName:"John", lastName:"Doe"};
document.getElementById("dtype").innerHTML=typeof person;
</script>
JavaScript Functions
• A JavaScript function is a block of code designed to perform a particular task.
• A JavaScript function is executed when "something" invokes it (calls it).
• A JavaScript function is defined with the function keyword, followed by a name,
followed by parentheses ().
• Function names can contain letters, digits, underscores, and dollar signs (same rules
as variables).
• The parentheses may include parameter names separated by commas: (parameter1,
parameter2, ...).
• The code to be executed, by the function, is placed inside curly brackets: {}.
• function name(parameter1, parameter2, parameter3…) {
// code to be executed
}
• Function parameters are listed inside the parentheses () in the function definition.
• Function arguments are the values received by the function when it is invoked.
• Inside the function, the arguments (the parameters) behave as local variables.
• The code inside the function will execute when "something" invokes (calls) the
function:
• When an event occurs (when a user clicks a button)
• When it is invoked (called) from JavaScript code
• Automatically (self invoked)
<p id="func"></p>
<script>
x=add(4,5);
document.getElementById("func").innerHTML =
x;
function add(a,b) { return a+b; }
</script>

� You can reuse code


� Variables declared within a JavaScript function, become LOCAL to
the function.
JavaScript Events
• HTML events are "things" that happen to HTML elements.
• When JavaScript is used in HTML pages, JavaScript can "react" on
these events. An HTML event can be something the browser does, or
something a user does. Here are some examples of HTML events:
• An HTML web page has finished loading
• An HTML input field was changed
• An HTML button was clicked
• Often, when events happen, you may want to do something.
• JavaScript lets you execute code when events are detected.
• HTML allows event handler attributes, with JavaScript code, to be added
to HTML elements.
Example: The following program displays date on mouse over.
html>
<head>
<title></title>
</head>
<body>
<button onmouseover="document.getElementById('dt').innerHTML =
Date();">The time is:</button>
<p id="dt"> </p>
</body>
</html>
JavaScript String Methods
<p id="str"></p>
<script>
let n="Software Engineering";
document.getElementById("str").innerHTML = n.slice(0,10); // end included but not the start
document.getElementById("str").innerHTML = n.slice(10);
document.getElementById("str").innerHTML = n.substring(0,10); //The difference is that start and end
values
// less than 0 are
treated as 0 in substring()
let text = "Please visit Microsoft!";
let newText = text.replace("Microsoft", "W3Schools");
document.getElementById("str").innerHTML = newText;
document.getElementById("str").innerHTML = newText.toUpperCase();
document.getElementById("str").innerHTML = newText.toLowerCase();
document.getElementById("str").innerHTML = "Hello".concat(" ","World");
document.getElementById("str").innerHTML = " Hellow ".trim();
document.getElementById("str").innerHTML = "5".padStart(4,"x");
document.getElementById("str").innerHTML = "software".charAt(3);
document.getElementById("str").innerHTML = "software".charCodeAt(3);
Conditional Statements
• Very often when you write code, you want to perform different actions for
different decisions.
• You can use conditional statements in your code to do this.
• Use if to specify a block of code to be executed, if a specified condition is
true
• Syntax:
• if (condition) {
// block of code to be executed if the condition is true
}
<!DOCTYPE html>
<html>
<body>
<p>Display "Good day!" if the hour is less than 18:00:</p>
<p id="demo">Good Evening!</p>
<script>
if (new Date().getHours() < 18) {
document.getElementById("demo").innerHTML = "Good day!";
}
</script>
</body>
</html>
<p id="demo"></p>
<script>
let day;
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
}
document.getElementById("demo").innerHTML = "Today is " + day;
JavaScript Loops
• The for statement creates a loop with 3 optional expressions:
for (expression 1; expression 2; expression 3) {
// code block to be executed
}
<p id="demo"></p>
<script>
let text = "";
for (let i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
document.getElementById("demo").innerHTML = text;
}
</script>
The JavaScript for in statement loops through the properties of an
Object:
• The JavaScript for in statement loops through the properties of an Object
<p id="demo"></p>
<script>
const person = {fname:"John", lname:"Doe", age:25};
let txt = "";
for (let x in person)
{
txt += person[x] + " ";
}
document.getElementById("demo").innerHTML = txt;
</script>
The JavaScript for in statement can also loop over the properties of an Array:
<h2>JavaScript For In</h2>
<p>The for in statement can loops over array values:</p>
<p id="demo"></p>
<script>
const numbers = [45, 4, 9, 16, 25];
for (let x in numbers) {
console.log(numbers[x]);
}
</script>
</body>
</html>
• The forEach() method calls a function (a callback function) once for
each array element.
<!DOCTYPE html>
<html>
<body>
<script>
const numbers = [45, 4, 9, 16, 25];
numbers.forEach(myFunction);
function myFunction(v) {
console.log(v);
}
</script>
</body>
</html>
The while loop statement is simpler than the for loop. It consists of a
condition and block statement. The condition is evaluated before each pass
through the loop. If the condition is true then it executes block statement.
<html>
<head>
<title>JS while</title>
</head>
<body>
<script>
let i=0;
while(i<6){
document.write(i);
document.write("</br>");
i++;
}
</script>
</body>
</html>
• The do...while loop is much like a while loop.
• It will repeat the loop until the specified condition is false.
• This loop will always be executed at least once, even if the condition is
false, because the block of statements is executed before the condition
is tested.
• In this loop statement, curly braces are optional.
<script>
let i=0;
do{
document.write(i);
document.write("</br>");
i++;
} while(i<6);
</script>
• Break statement is used to exit from the innermost loop, switch statement,
or from the statement named by label.
• It terminates the current loop and transfers control to the statement
following the terminated loop.
• The continue statement skips the statement following it and executes the
loop with next iteration.
• It is used along with an if statement inside while, do-while, for, or label
statements.
• The continue statement does not terminate the loop. Instead, in a while
loop, it jumps back to the condition and in a for loop, it jumps to the update
expression.
<html>
<head>
<title>JS break continue</title>
</head>
<body>
<script>
for(let i=0;i<=10;i++){
if(i==4)
//continue;
break;
document.write(i);
document.write("<br>");
}
</script>
</body>
</html>
JavaScript WITH statement
With statement saves a lot of typing when properties of same object have to be
accessed. For example, it is common to work with deeply nested object
hierarchies.
Example:
<html>
<head>
<title>WITH statement </title>
</head>
<body>
<script>
with(document){
write("Writing using with");
}
</script>
</body>
</html>
JavaScript String Search
<p id="demo"></p>
<script>
let text = "Please LOCATE where 'Locate' occurs!";
let findex = text.indexOf("locate");
let lindex = text.lastIndexOf("locate");
let lindex2=text.lastIndexOf("locate",5);
let indexs=text.search("locate");
let indexs2=text.search(/locate/);
// g indicates all possible matches. i indicates case insensetive
const myArr = text.match(/oc/gi);
let swith = text.startsWith("Please");
let ewith = text.endsWith("occurs");
//document.getElementById("demo").innerHTML = lindex;
//document.getElementById("demo").innerHTML = lindex;
//document.getElementById("demo").innerHTML = indexs;
//document.getElementById("demo").innerHTML = indexs2;
//document.getElementById("demo").innerHTML = myArr.length + " " + myArr;
//document.getElementById("demo").innerHTML = swith;
//document.getElementById("demo").innerHTML = ewith;
</script>
JavaScript Numbers
<p id="demo"></p>
<script>
let x = 123.123;
//document.getElementById("demo").innerHTML = x.toString();
//document.getElementById("demo").innerHTML =
x.toExponential();
//document.getElementById("demo").innerHTML =
x.toExponential();
//document.getElementById("demo").innerHTML =
x.toExponential(4);
//document.getElementById("demo").innerHTML = x.toFixed(2);
//document.getElementById("demo").innerHTML = Number("10");
//document.getElementById("demo").innerHTML = x.valueOf();
let d = new Date("1970-01-02");
JavaScript Array Methods
<script>
let my=["home","car","marriage"];
let your=["job","education"];
const x = [[1,2],[3,4],[5,6]];
document.getElementById("demo").innerHTML = my.toString(); //converts an array to a string
document.getElementById("demo").innerHTML = my.join("*"); //you can specify the separator
//document.getElementById("demo").innerHTML = my.pop(); //removes the last element
document.getElementById("demo").innerHTML = my.push("home");//adds a new element
document.getElementById("demo").innerHTML = my.shift(); //pop the first element
document.getElementById("demo").innerHTML = my.concat(your); //merging arrays
document.getElementById("demo").innerHTML = x.flat(); //reducing the dimensionality
document.getElementById("demo").innerHTML = your.splice(1,0,"sport");//position and
removed elements
document.getElementById("demo").innerHTML = your;
document.getElementById("demo").innerHTML = my.sort();
document.getElementById("demo").innerHTML = my.reverse();
</script>
<p id="demo"></p>
JavaScript Date Objects
<script>
const d = new Date()
document.getElementById("demo").innerHTML = d;
document.getElementById("demo").innerHTML = d.getMonth();
document.getElementById("demo").innerHTML = d.getFullYear();
document.getElementById("demo").innerHTML = d.getDate();
document.getElementById("demo").innerHTML = d.getDay();
document.getElementById("demo").innerHTML = d.getHours();
document.getElementById("demo").innerHTML = d.getMinutes();
document.getElementById("demo").innerHTML = d.getSeconds();
document.getElementById("demo").innerHTML = d.getMilliseconds();
document.getElementById("demo").innerHTML = d.getTime();
document.getElementById("demo").innerHTML = d;
</script>
JavaScript Random
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
Math.floor(Math.random()*10);
</script>
</body>
</html>
JavaScript Classes
• JavaScript Classes are templates for JavaScript Objects.
• Use the keyword class to create a class.
• Always add a method named constructor(): Add any number of methods.
• class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
• A JavaScript class is not an object, it is a template for JavaScript objects.
• When you have a class, you can use the class to create objects:
• const myCar1 = new Car("Ford", 2014);
const myCar2 = new Car("Audi", 2019);
• The constructor method is a special method called automatically when a new object
is created.
• It has to have the exact name "constructor".
• It is used to initialize object properties.
• If you do not define a constructor method, JavaScript will add an empty constructor
method.
• Class methods are created with the same syntax as object methods.
<p id="demo"></p>
<script>
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
age() { const date = new Date();
return date.getFullYear() - this.year; }
}
const myCar = new Car("Ford", 2014);
document.getElementById("demo").innerHTML ="My car is " + myCar.age() + "
years old.";
</script>
Chapter 5
PHP
Introduction
• PHP is an acronym for "Hypertext Preprocessor".
• It is a widely-used, open source scripting language.
• PHP scripts are executed on the server and it is free to download and
use.
• PHP can generate dynamic page content.
• It can create, open, read, write, delete, and close files on the server.
PHP can collect form data, send and receive cookies, add, delete, and
modify data in your database.
• It controls user-access and can encrypt data. With PHP you are not
limited to output HTML. You can output images or PDF files.
• PHP is one of the best server side scripting languages, because:
• It runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.),
• It is compatible with almost all servers used today such as (Apache, IIS, etc.),
• It supports a wide range of databases,
• It is free to download from the official PHP resource: www.php.net,
• It is easy to learn and runs efficiently on the server side.
PHP Syntax

• A PHP script can be placed anywhere in the document.


• PHP script starts with <?php and ends with ?>.
<?php
// PHP code goes here
?>
• The default file extension for PHP files is ".php".
• A PHP file normally contains HTML tags, and some PHP scripting
code.
• PHP statements end with a semicolon (;). In PHP, keywords (e.g. if,
else, while, echo, etc.), classes, functions, and user-defined
functions are not case-sensitive.
• However; all variable names are case-sensitive!
PHP Comments
• A comment in PHP code is a line that is not executed as a part of the
program.
• Its only purpose is to be read by someone who is looking at the code.
• Comments can be used to Let others understand your code, Remind
yourself of what you did - Most programmers have experienced coming back
to their own work a year or two later and having to re-figure out what they
did.
• Comments can remind you of what you were thinking when you wrote the
code.
• PHP supports several ways of commenting:
// This is a single-line comment
# This is also a single-line comment
/*
This is a multiple-lines comment block
that spans over multiple
lines
PHP echo and print Statements
• With PHP, there are two basic ways to get output: echo and print.
• “echo” has no return value while print has a return value of 1 so it can
be used in expressions.
• “echo” can take multiple parameters while print can take one
argument.
• “echo” is marginally faster than print.
• The echo statement can be used with or without parentheses: echo or
echo().
$x=2;
Echo "Hello world!<br>";
print "Hello world!<br>";
print "Study PHP " .$x."<br>";
PHP Variables
• Variables are "containers" for storing information.
• In PHP, a variable starts with the $ sign, followed by the name of the variable.

• A variable name must start with a letter or the underscore character.


• A variable name cannot start with a number.
• A variable name can only contain alpha-numeric characters and underscores (A-
z, 0-9, and _).
• Variable names are case-sensitive.
• When you assign a text value to a variable, put quotes around the value.
• Unlike other programming languages, PHP has no command for declaring a
variable.
• It is created the moment you first assign a value to it.
• Example
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
• In PHP, variables can be declared anywhere in the script.
• The scope of a variable is the part of the script where the variable can
be referenced/used.
• PHP has three different variable scopes: local, global and static.
• A variable declared outside a function has a GLOBAL SCOPE and can only be
accessed outside a function.
• A variable declared within a function has a LOCAL SCOPE and can only be
accessed within that function.
• You can have local variables with the same name in different functions,
because local variables are only recognized by the function in which
they are declared.
• The global keyword is used to access a global variable from within a
function.
• To do this, use the global keyword before the variables (inside the
function).
• PHP also stores all global variables in an array called
$GLOBALS[index].
<?php
$x = 5;
$y = 10;
function myTest() {
$x = 6; // local variable
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];//array
stores global variables
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>
• Normally, when a function is completed/executed, all of its variables are
deleted.
• However, sometimes we want a local variable NOT to be deleted.
• We need it for a further job.
• To do this, use the static keyword when you first declare the variable.
• Then, each time the function is called, that variable will still have the
information it contained from the last time the function was called.
• A constant is an identifier (name) for a simple value.
• The value cannot be changed during the script.
• A valid constant name starts with a letter or underscore (no $ sign before the
constant name).
• Note: Unlike variables, constants are automatically global across the entire
script.
• To create a constant, use the define() function.
• define(name, value, case-insensitive)
• define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;
• define("GREETING", "Welcome to W3Schools.com!", true);
echo greeting;
• Variables can store data of different types, and different data types can
do different things.
• PHP supports String, Integer, Float (double), Boolean, Array, Object,
NULL, Resource data types.
• A string can be any text inside quotes. You can use single or double
quotes.
• $x = "Hello world!";
• An integer data type is a non-decimal number between -2,147,483,648
and 2,147,483,647.
• $x = 5985;
• A float (floating point number) is a number with a decimal point or a
number in exponential form.
• $x = 10.365;
• A Boolean represents two possible states: TRUE or FALSE. Booleans
are often used in conditional testing.
• $x = true;
• $y = false;
• An array stores multiple values in one single variable.
• In PHP, the array() function is used to create an array.
• The count() function is used to return the length (the number of
elements) of an array.
$cars = array("Volvo","BMW","Toyota");
echo count($cars);
• In PHP, there are three types of arrays:
• Indexed arrays - Arrays with a numeric index
$cars = array("Volvo", "BMW", "Toyota");
• Associative arrays - Arrays with named keys
• $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); or
• $age['Peter'] = "35";
• $age['Ben'] = "37";
• $age['Joe'] = "43";
• Multidimensional arrays - Arrays containing one or more arrays
• The elements in an array can be sorted in alphabetical or numerical
order, descending or ascending.
• sort() - sort arrays in ascending order
• $cars = array("Volvo", "BMW", "Toyota");
sort($cars);
• rsort() - sort arrays in descending order
• $cars = array("Volvo", "BMW", "Toyota");
rsort($cars);
• asort() - sort associative arrays in ascending order, according to the value
• $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);
• ksort() - sort associative arrays in ascending order, according to the key
• $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
ksort($age);
• arsort() - sort associative arrays in descending order, according to the value
• $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
arsort($age);
• krsort() - sort associative arrays in descending order, according to the key
• $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
krsort($age);
• PHP Object
• Classes and objects are the two main aspects of object-oriented programming.
• A class is a template for objects, and an object is an instance of a class.
• When the individual objects are created, they inherit all the properties and
behaviors from the class, but each object will have different values for the
properties.
• Let's assume we have a class named Car.
• A Car can have properties like model, color, etc.
• We can define variables like $model, $color, and so on, to hold the values of these
properties.
• When the individual objects (Volvo, BMW, Toyota, etc.) are created, they inherit all the
properties and behaviors from the class, but each object will have different values for the
properties.
• If you create a __construct() function, PHP will automatically call this function when you
create an object from a class.
<?php
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model; }
public function message() {
return "My car is a " . $this->color." " .$this->model. "!";
}}
$myCar = new Car("black", "Volvo");
echo $myCar -> message();
echo "<br>";
$myCar = new Car("red", "Toyota");
echo $myCar -> message();
?>
PHP Strings
• The PHP strlen() function returns the length of a string.
• echo strlen("Hello world!"); // outputs 12
• The PHP str_word_count() function counts the number of words in a
string.
• echo str_word_count("Hello world!"); // outputs 2
• The PHP strrev() function reverses a string.
• echo strrev("Hello world!"); // outputs !dlrow olleH
• The PHP strpos() function searches for a specific text within a string. If
a match is found, the function returns the character position of the first
match. If no match is found, it will return FALSE. The first character
position in a string is 0.
• echo strpos("Hello world!", "world"); // outputs 6
• The PHP str_replace() function replaces some characters with some
other characters in a string.
PHP Numbers
• PHP uses is_int() function to check if the type of a variable is integer.
• $x = 59.85;
• var_dump(is_int($x));
• The pi() function returns the value of PI:
• echo(pi()); // returns 3.1415926535898
• The min() and max() functions can be used to find the lowest or highest value in a
list of arguments:
• echo(min(0, 150, 30, 20, -8, -200)); // returns -200
• echo(max(0, 150, 30, 20, -8, -200)); // returns 150
• The sqrt() function returns the square root of a number:
• echo(sqrt(64)); // returns 8
• The round() function rounds a floating-point number to its nearest integer:
• echo(round(0.60)); // returns 1
• echo(round(0.49)); // returns 0
• The rand() function generates a random number:
• echo(rand());
• To get more control over the random number, you can add the optional min and max
parameters to specify the lowest integer and the highest integer to be returned.
• echo(rand(10, 100));
Operators
<?php
$x=2;$y=4; // //Assignemnt operator
echo "Sum=".($x + $y) ."<br>"; // arithmetic operation
echo "Exponent=".($x**$y)."<br>"; // x to the power of y
echo "Short form=".($x+=$y)."<br>"; // $x = $x + $y;
echo "Comparision=".($x >= $y)."<br>" ; // Comparision operator
echo "Spaceship=".(3 <=> 4)."<br>"; // equal gives 0. Left is greater gives 1.
Right greater gives -1
echo "Post increment:".$x++."<br>"; // Post increment returns $x and then
increments $x
echo "Pre increment:".++$x."<br>"; // Pre increment increments $x and then
returns $x
echo "Logical operation:".((3 > 4) || (2 == 2))."<br>"; // Logical operation
?>
PHP conditional Statements
<?php
$t=date("D");
if($t=="Mon"){
echo "We have Security class today"."<br>";
}else if($t=="Tue"){
echo "We have Internet programming class today"."<br>";
}else if($t=="Wed"){
echo "We have data structure class today"."<br>";
}else if($t=="Thu"){
echo "We have requirement class today"."<br>";
}else if($t=="Fri"){
echo "We have no class today"."<br>";
}
?>
switch($t){
case "Mon": echo "We have Security class today"."<br>";
break;
case "Tue": echo "We have Internet programming class
today"."<br>";
break;
case "Wed": echo "We have data structure calss today"."<br>";
break;
case "Thu": echo "We have requirement class today"."<br>";
break;
case "Fri": echo "We have no class today"."<br>";
break;
}
<?php
$x=1;$sum=0;
//*****************************
while($x<10){
if($x==5) break;
$sum=$sum+$x;
$x++; }
echo "While SUM=".$sum."<br>";
//****************************
$sum=0;
for($x=1;$x<10;$x++){
if($x==6){continue;}
$sum=$sum+$x;}
echo "For SUM=".$sum."<br>";
//**************************
$x=1;$sum=0;
do{
if($x==4) break;
$sum=$sum+$x;
$x++;
}while($x<10);
echo "Dowhile SUM=".$sum."<br>";
//****************************
echo "Fruits:"."<br>";
$fruits=array("Banana","Organe","Apple");
foreach($fruits as $v){
echo $v."<br>";
}
<?php
function msg(){ // Function without parameters
echo "Let me tell your age"."<br>";
}
function age($a) { // Function with parameter
echo "You are ".$a." years old"."<br>";
}
function sum($x,$y){
return $x+$y; // Function with return values
}
echo "Sum of 4 and 5 is:".sum(4,5)."<br>";
msg();
age(20);
age(21);
?>
<?php
function add_five(&$value) {
$value += 5;
}
$num = 2;
add_five($num);
echo $num;
?>
PHP Regular Expressions
• A regular expression is a sequence of characters that forms a search pattern.
• When you search for data in a text, you can use this search pattern to
describe what you are searching for.
• A regular expression can be a single character, or a more complicated
pattern.
• Regular expressions can be used to perform all types of text search and text
replace operations.
• In PHP, regular expressions are strings composed of delimiters, a pattern
and optional modifiers.
• Example:
$exp = "/w3schools/i";
• In the example above, / is the delimiter, w3schools is the pattern that is being
searched for, and i is a modifier that makes the search case-insensitive.
• The delimiter can be any character that is not a letter, number, backslash or
space.
• The most common delimiter is the forward slash (/), but when your pattern
• preg_match() Returns 1 if the pattern was found in the string and 0 if
not
<?php
$str = "Visit W3Schools";
$pattern = "/w3schools/i";
echo preg_match($pattern, $str); // Outputs 1
?>
• preg_match_all() Returns the number of times the pattern was found in
the string
<?php
$str = "The rain in SPAIN falls mainly on the plains.";
$pattern = "/ain/i";
echo preg_match_all($pattern, $str); // Outputs 4
?>
• preg_replace() Returns a new string where matched patterns have been
replaced with another string
<?php
$str = "Visit Microsoft!";
$pattern = "/microsoft/i";
echo preg_replace($pattern, "W3Schools", $str); // Outputs "Visit
W3Schools!"
?>
• Modifiers can change how a search is performed.
• i-Performs a case-insensitive search
• m-Performs a multiline search (patterns that search for the beginning
or end of a string will match the beginning or end of each line)
• u-Enables correct matching of UTF-8 encoded patterns
PHP Form Handling
• The PHP super globals $_GET and $_POST are used to collect form-
data.
• Both GET and POST create an array (e.g. array( key1 => value1, key2
=> value2, key3 => value3, ...)).
• This array holds key/value pairs, where keys are the names of the form
controls and values are the input data from the user.
• Both GET and POST are treated as $_GET and $_POST.
• These are super globals, which means that they are always accessible,
regardless of scope - and you can access them from any function, class
or file without having to do anything special.
• $_GET is an array of variables passed to the current script via the URL
parameters.
• $_POST is an array of variables passed to the current script via the
HTTP POST method.
• Information sent from a form with the GET method is visible to everyone (all
variable names and values are displayed in the URL).
• GET also has limits on the amount of information to send.
• The limitation is about 2000 characters.
• However, because the variables are displayed in the URL, it is possible to
bookmark the page.
• This can be useful in some cases.
• GET may be used for sending non-sensitive data.
• GET should NEVER be used for sending passwords or other sensitive
information!
• Information sent from a form with the POST method is invisible to others (all
names/values are embedded within the body of the HTTP request) and has no
limits on the amount of information to send.
• Moreover POST supports advanced functionality such as support for multi-
part binary input while uploading files to server. However, because the
The form in the source page looks like the following:
<form method="POST" action="welcome.php">
<label>Name:</label><input type="text" name="fname">
<br>
<label>Email:</label><input type="email" name="mail">
<br>
<input type="submit" value="Submit">
</form>
The code in the destination page (welcome.php) looks like
the following:
<?php
echo "Welcome ".$_POST['fname'];
//echo "Welcome ".$_GET['fname'];
• $_SERVER["PHP_SELF"] is a super global variable that returns the
filename of the currently executing script.
• $_SERVER["PHP_SELF"] sends a submitted form data to the page itself, instead
of jumping to a different page.
• This way, the user will get error messages on the same page as the form.
• htmlspecialchars() function converts special characters to HTML
entities.
• This means that it will replace HTML characters like < and > with &lt; and &gt; .
• This prevents attackers from exploiting the code by injecting HTML or Javascript
code (Cross-site Scripting attacks) in forms.
• Cross-site scripting (XSS) is a type of computer security vulnerability typically
found in Web applications.
• XSS enables attackers to inject client-side script into Web pages viewed by other
users.
• Example:
• <form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
• However, consider that a user enters the following URL in the address bar:
• http://www.example.com/test_form.php/%22%3E%3Cscript%3Ealert('hacked')%3
C/script%3E
• In this case, the above code will be translated to:
• <form method="post" action="test_form.php/"><script>alert('hacked')</script>
• The htmlspecialchars() function converts special characters to HTML entities.
• Now if the user tries to exploit the PHP_SELF variable, it will result in the
following output:
• <form method="post" action="test_form.php/&quot;&gt;&lt;script&gt;alert('hacked')&lt;/script&g
t;">
• The exploit attempt fails, and no harm is done!
• PHP trim() function strips unnecessary characters (extra space, tab,
newline) from the user input data.
• PHP stripslashes() function removes backslashes (\) from the user
input data
• Notice that at the start of the script, we check whether the form has been
submitted using $_SERVER["REQUEST_METHOD"].
• If the REQUEST_METHOD is POST, then the form has been submitted -
and it should be validated.
• If it has not been submitted, skip the validation and display a blank form.
<?php
$name=$email=$nameerr=$emailerr="";
if($_SERVER['REQUEST_METHOD'] == "POST") {
if(empty($_POST['fname'])){
$nameerr="Please input your name";
}else{
$name=htmlspecialchars(stripslashes(trim($_POST['fname'])));
}
if(empty($_POST['mail'])){
$emailerr="Please input your email";
}else{
$email=htmlspecialchars(stripslashes(trim($_POST['mail'])));
}
if(empty($nameerr) && empty($emailerr)){
echo "Welcome ".$name."<br>";
echo "Your email ".$email." is recieved.";
}
}
?>
• The preg_match() function searches a string for pattern, returning true if
the pattern exists, and false otherwise.
• The code below shows a simple way to check if the name field only
contains letters, dashes, apostrophes and whitespaces.
• $name = $_POST["name"];
• if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
• PHP's filter_var() function is the easiest and safest way to check whether
an email address is well-formed.
• $email = $_POST["email"];
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
PHP Date and Time
<?php
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y") . "<br>";
echo "Today is " . date("m") . "<br>";
echo "Today is " . date("d") . "<br>";
echo "Today is " . date("l") . "<br>";
echo date("h:i:s"). "<br>";
?>
• PHP include and require Statements
• The include (or require) statement takes all the text/code/markup that exists in
the specified file and copies it into the file that uses the include statement.
• Including files is very useful when you want to include the same PHP, HTML, or
text on multiple pages of a website.
• It is possible to insert the content of one PHP file into another PHP file (before
the server executes it), with the include or require statement.
• The include and require statements are identical, except upon failure:
• require will produce a fatal error (E_COMPILE_ERROR) and stop the script
• include will only produce a warning (E_WARNING) and the script will continue
• So, if you want the execution to go on and show users the output, even if the
include file is missing, use the include statement.
• Otherwise, in case of FrameWork, CMS, or a complex PHP application
coding, always use the require statement to include a key file to the flow
of execution.
• This will help avoid compromising your application's security and integrity,
just in-case one key file is accidentally missing.
• Including files saves a lot of work.
• This means that you can create a standard header, footer, or menu file for
all your web pages.
• Then, when the header needs to be updated, you can only update the
header include file.
• Syntax
• include 'filename';
or
• require 'filename';
PHP File Handling
• PHP has several functions for creating, reading, uploading, and editing files.
• The readfile() function reads a file and writes it to the output buffer.
<?php
echo readfile("webdictionary.txt");
?>
• The readfile() function returns the number of bytes read on success.
• A better method to open files is with the fopen() function.
• This function gives you more options than the readfile() function.
• The first parameter of fopen() contains the name of the file to be opened and the second
parameter specifies in which mode the file should be opened.
• The following example also generates a message if the fopen() function is unable to
open the specified file:
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>
• The fread() function reads from an open file.
• The first parameter of fread() contains the name of the file to read from and the second parameter
specifies the maximum number of bytes to read.
• The following PHP code reads the "webdictionary.txt" file to the end:
• fread($myfile,filesize("webdictionary.txt"));
• The fclose() function is used to close an open file.
• The fgets() function is used to read a single line from a file.
• After a call to the fgets() function, the file pointer has moved to the next line.
• The feof() function checks if the "end-of-file" (EOF) has been reached.
• The feof() function is useful for looping through data of unknown length.
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
?>
• The fgetc() function is used to read a single character from a file.
• <?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
?>
• A file is created using the same function used to open files. If you use
fopen() on a file that does not exist, it will create it, given that the file is
opened for writing (w) or appending (a).
• $myfile = fopen("testfile.txt", "w");
• The fwrite() function is used to write to a file. The first parameter of fwrite()
contains the name of the file to write to and the second parameter is the
string to be written.
• You can append data to a file by using the "a" mode. The "a" mode
appends text to the end of the file, while the "w" mode overrides (and
erases) the old content of the file.
PHP Cookies
• A cookie is often used to identify a user.
• A cookie is a small file that the server embeds on the user's computer.
Each time the same computer requests a page with a browser, it will
send the cookie too. With PHP, you can both create and retrieve cookie
values.
• A cookie is created with the setcookie() function.
• setcookie(name, value, expire, path, domain, secure, httponly);
• Only the name parameter is required. All other parameters are optional.
• To modify a cookie, just set (again) the cookie using the setcookie()
function.
• To delete a cookie, use the setcookie() function with an expiration date in
the past.
• <?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); //
86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
PHP Sessions
• A session is a way to store information (in variables) to be used across multiple
pages.
• Unlike a cookie, the information is not stored on the user’s computer.
• When you work with an application, you open it, do some changes, and then you
close it.
• This is much like a Session.
• The computer knows who you are.
• It knows when you start the application and when you end.
• But on the internet there is one problem:
• the web server does not know who you are or what you do, because the HTTP address doesn't
maintain state.
• Session variables solve this problem by storing user information to be used across
multiple pages (e.g. username, favorite color, etc).
• By default, session variables last until the user closes the browser.
• So; Session variables hold information about one single user, and are available to all
pages in one application.
• A session is started with the session_start() function. Session variables are set with
the PHP global variable: $_SESSION. The session_start() function must be the very
first thing in your document. Before any HTML tags.
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
PHP MySQL Database
• With PHP, you can connect to and manipulate databases.
• MySQL is the most popular database system used with PHP.
• MySQL is a database system used on the web.
• It is a database system that runs on a server and it is ideal for both small and
large applications.
• MySQL is very fast, reliable, and easy to use.
• It uses standard SQL.
• MySQL compiles on a number of platforms.
• It is free to download and use.
• It is developed, distributed, and supported by Oracle Corporation.
• MySQL is named after co-founder Monty Widenius's daughter: My.
• PHP combined with MySQL are cross-platform (you can develop in Windows
and serve on a Unix platform)
• The data in a MySQL database are stored in tables.
• A table is a collection of related data, and it consists of columns and rows.
• PHP 5 and later can work with a MySQL database using:
• MySQLi extension (the "i" stands for improved) and PDO (PHP Data Objects)
• Earlier versions of PHP used the MySQL extension. However, this extension
was deprecated in 2012.
• PDO will work on 12 different database systems, whereas MySQLi will only
work with MySQL databases.
• So, if you have to switch your project to use another database, PDO makes the
process easy. You only have to change the connection string and a few queries.
• With MySQLi, you will need to rewrite the entire code - queries included.
• Both are object-oriented, but MySQLi also offers a procedural API.
• Both support Prepared Statements.
• Prepared Statements protect from SQL injection, and are very important for web application
security.
o Using of Object-Oriented MySQLi to Connect to MySQL to PHP:

<?php
// Create connection
$conn = new mysqli("localhost", "root", " "); //server name, username and
password
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
o The connection will be closed automatically when the script ends. To close the connection
before, use the following:
� $conn->close(); // MySQLi Object-Oriented:

o The CREATE DATABASE statement is used to create a database in MySQL.

• <?php
// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
?>
o The CREATE TABLE statement is used to create a table in MySQL.

• $sql = "CREATE TABLE MyGuests (


id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON
UPDATE CURRENT_TIMESTAMP
)";
o After a database and a table have been created, we can start adding data in
them.

• $sql = "INSERT INTO MyGuests (firstname, lastname, email)


VALUES ('John', 'Doe', '[email protected]')";
o Multiple SQL statements must be executed with the mysqli_multi_query()
function.
• $sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', '[email protected]');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', '[email protected]')";
if ($conn->multi_query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
o The SELECT statement is used to select data from one or more tables. We can use the *
character to select ALL columns from a table:

• $sql = "SELECT id, firstname, lastname FROM MyGuests";


$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " .
$row["lastname"]. "<br>";
}
} else {
echo "0 results";
}

You might also like