Web Programming Module
Web Programming Module
Prepared by:
Ermias T. & Yared Y.
3.1.3 Attaching CSS with HTML (External , Embedded and Inline) ............. 28
HTML defines the meaning and structure of web content. Other technologies besides
HTML are generally used to describe a web page's appearance/presentation (CSS) or
functionality/ behavior (JavaScript).
HTML has been in use by the World-Wide Web (WWW) global information initiative
since 1990. It is a simple markup language used to create hypertext documents that are
platform independent. HTML markup can represent hypertext news, mail,
documentations, and hyper media; menus of options; database query results;
<html>
<head>
Compiled by Computer Science and IT Department Staff
10
<title>
page title
</title>
</head>
<body>
content
</body>
</html>
Q. Explain in detail the different versions of HTML?
In HTML, a tag is used for creating an element. Tags are used to delimit the start and
end of elements in the markup. Normal html elements have a start tag to indicate
where they begin, and an end tag to indicate where they end. The start and end tags of
certain normal elements can be omitted. An HTML tag is composed of the name of the
element, surrounded by angle brackets (<>). An end tag also has a slash after the
opening angle bracket, to distinguish it from the start tag.
E.g.
<p> paragraph </p>
You may have come across the term HTML elements in this module or some other
document. You may have also seen HTML tags and HTML elements used
interchangeably. But there is a difference between the two. HTML tags are just the
opening and closing entities of an element. Whereas HTML Elements contain the
opening tag, closing tag and content (content is optional for void elements).
There are six different kinds of HTML elements. Void elements, template elements,
raw text elements, Escapable raw text elements, Foreign elements and Normal
Elements
Q. Read and write a short essay about the different types of elements
<title></title>
- Web browsers usually display it in a window's title bar when the window is
open, and (where applicable) in the task bar when the window is
minimized.
- Sets the title of the web page to be displayed in the browser’s title bar and is
found within the <head> tag.
<body></body>
-The body tag contains the visible part of the web page and is displayed in the
display area of the browser. Just like the html and head tag, both the start and end tags of the
body tag may be omitted and inferred from child elements (HTML5). It contains several
other tags and content in it.
Attributes:
HTML Attributes are special words used to control the behavior of an element.
HTML Attributes are a modifier of an HTML element type. An attribute is added to an
HTML start tag before the closing angle bracket separated by space from the elements
name. We can include more than one attribute in an element, but one has to be space
separated from the other.
Some of the common attributes used in the body element
✓ bgcolor=“color”
✓ background=“img url”
✓ text=“text color”
✓ link=“link color”
✓ alink=“active link color”
✓ vlink=“visited link color”……
Compiled by Computer Science and IT Department Staff
12
adding attributes to body
<body bgcolor="red">
E.g.
<meta charset="utf-8">
You can add comments to your html document using the following syntax:
In HTML, a link is created by wrapping the text or other content inside an <a> tag
(anchor tag) and using the href attribute, also known as Hypertext reference, or target
that contains the web address.
<a href="https://www.google.com">Google</a>.
You can also add supporting information to a link using the title attribute.
Another attribute that we can use on the anchor tag is the target attribute. The target
attribute can be applied to a link to specify how the new page is opened.
Active Learning:
- First create a simple web page containing the basic html tags.
- Then add one or more paragraphs
- Change some of the content into links
- Preferably add title to each of the links you created
Headings –
Headings are predefined formats for text presentation and there are six heading
formats defined in HTML:
<h1> up to <h6>
<h1> the largest font size
<h6> the smallest font size
Format :<h1>…</h1>
E.g., <h2>a text in heading two</h2>
One thing you should bear in mind is html out of the box comes with no styling.
This has to do with the purpose of html, which is used to structure content in the
browser. The styles you see when you apply different tags like headings, lists, links
etc. comes by default with the browser and it is called user agent stylesheet. You can
check this by going to the developer’s tool of your preferred browser and selecting the
styles tab. You will learn more about the different types of style sheets including user
agent style sheet and how to style your web page in the next chapter
Q. Write simple html code by using the html tags you have seen above?
Paragraph: definition of paragraph
Format: <p>…</p>
E.g., <p>this is a paragraph of text. it has a new line before and after it.</p>
The browser inserts a new line before and after the text in the paragraph tag.
Attribute:
align=“alignment” {left, right, center, justify}
line break - inserts a new line.
Format: <br>. E.g., Line one <br> line two <br> line three <br> line four
Compiled by Computer Science and IT Department Staff
15
horizontal rule - inserts a horizontal line
Format: <hr>
Attributes:
✓ width=“width” {absolute: in pixels or relative: in %}
✓ noshade
✓ color=“color” {browser dependent}
E.g. <hr width=“75%” noshade color=“#FF0000”>
sub/sup - define either a subscript or a superscript
Format: <sub>…</sub> ; <sup>…</sup>
E.g.
X<sub>1</sub><sup>2</sup> + 2X<sub>3</sub>
The src attribute contains a path pointing to the image you want to embed in the
page, which can be a relative or absolute URL, in the same way as href attribute values
in <a> elements
<img src="dinosaur.jpg">
You can also embed an image using its absolute URL from
<img src="https://www.example.com/images/dinosaur.jpg">
Another attribute we frequently see in an img tag is alt. Its value is textual
description of the image, which is displayed in a situation where the image
cannot be seen or takes a long time to render.
You can also use width and height attributes to specify the width and height of the
image. Do not apply a width and height that is out of proportion, this will result in the
image being very fuzzy. Which is not what your user desire.
You can also add title attribute to add supporting information to the user. The
information inside title is display when the mouse is over the element like a tooltip
Supported image formats are: gif, jpg/jpeg, png
The name attribute gives the map a name so that it can be referenced. The attribute must
be present and must have a non-empty value with no-space characters
<map name="primary">
<area shape="circle" coords="75,75,75" href="left.html">
<area shape="circle" coords="275,75,75" href="right.html">
</map>
<img usemap="#primary" src="sample-image.jpg" alt="350 x 150 pic">
A table is a structured data made up of rows and columns. To create table in html
use the fowling elements table, tr, th, td, and captions
tr stands for table row, th stands for table header and td stands for table data
If you have a reason to merge columns or rows or the website you are building
needs this functionality you can use the colspan and rowspan attribute to do so. These
attributes are used to span two or more columns or rows respectively. Both colspan
and rowspan takes unitless numbers that specifies the number of columns and rows
you want to span
E.g.
<table>
<caption align=“center” valign=“bottom”>table 1.0</caption>
<tr>
<th>Column 1</th>
<th>Column 2</th>
</tr>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
</tr>
<tr>
<td>Cell 3</td>
<td>Cell 4</td>
</tr>
</table>
Q. Read in detail about the different table attributes, row attributes and data/heading
attributes?
II. Ordered Lists (ol) - element represents an ordered list of items — typically
rendered as a numbered list.
Format:
<ol>
<li>…</li>
<li>…</li>…
</ol>
Attribute: type=“number type” {1, i, I, a, A}
E.g. <ol type=“i”> <li>book</li><li>marker</li><li>chalk</li></ol>
other attributes:
reversed: items will be numbered from high to low
start: an integer to start counting from for the list items
<dt>…</dt>
<dd>…</dd>
</dl>
E.g. <dl>
<dt>book</dt><dd>something that we read …</dd>
<dt>marker</dt><dd>something we write with …</dd>
Compiled by Computer Science and IT Department Staff
19
</dl>
Q. Write a list of students by using order list and change the type to roman numbers
An HTML document that describes frame layout has a different markup than
HTML document without frames. A standard document has one HEAD section and
one BODY. A frameset document has a HEAD and a FRAMESET in place of BODY.
Attributes:
Cols -> specifies how many columns are contained in the frameset and the size of
each column. You can specify the width of each column in one of four ways: Pixels,
Percentage, wildcard symbol (takes reminder of the window) and relative width of the
browser window
Rows -> This attribute works just like the cols attribute and takes the same values,
but it is used to specify the rows in the frameset
Border -> specifies the width of the border
Syntax:
< frame src = "URL" >
Example:
Compiled by Computer Science and IT Department Staff
20
<!DOCTYPE html>
<html>
<head>
<title>Frame tag</title>
</head>
<frameset cols="25%,50%,25%">
<frame src="frame1.html" >
<frame src="frame2.html">
<frame src="frame3.html">
</frameset>
</html>
Users interact with forms through named controls. There are various from controls
available like text fields, text area, check box, drop-down menus etc.
Form attributes:
Form controls
The src attribute specify the location of the video file. Contorls attribute adds a feature
for the user to control the video or audio.
The <audio> element works just like the <video> element, with a few small
differences.
<audio controls>
<source src=”audio source” type=”type of audio like audio/mp3”>
<source src=”audio source” type=”type of audio like ”>
<p> if the browser doesn’t support this feature it will fallback to this
text </p>
</audio>
This will create a canvas on the page with a size of 320 by 240 pixels. If the browser
doesn’t support <canvas> we can add a suitable fallback text in between the opening
and closing tag. You will have to give the canvas a class name or id so that it will be
easily referenced in JavaScript.
You will use the following methods after you get the reference of the canvas in
JavaScript
- Getcontext
- fillStyle
- fillRect
- etc.
Q After you are introduced to JavaScript, draw a rectangle using the methods
given above
E.g.
<svg viewBox="0 0 300 100" xmlns="http://www.w3.org/2000/svg"
stroke="red" fill="grey">
<circle cx="50" cy="50" r="40" />
Compiled by Computer Science and IT Department Staff
24
<circle cx="150" cy="50" r="4" />
</svg>
Declaration Block:
Declarations are grouped in blocks, that is in a structure delimited by an opening
brace, '{' and a closing one, '}'
E.g.
An inline style loses many of the advantages of style sheets by mixing content with
presentation. Use this method sparingly when you need a style to be applied to a single
occurrence of an element.
2. Embedded stylesheet
This type of stylesheet should be used when a single document has a unique style. You
define internal styles in the head section by using the <style> tag.
e.g.
<head>
<style>
H1 {
color:yellow;
Text-align:left;
}
P{
margin-left:20px;
}
</style>
</head>
3. External style sheets
An external style sheet is used when the style is applied to many pages. With an
external style sheet, you can change the look of an entire website by changing one file
(the style sheet). Each page should be linked to the style sheet using the <link> tag
inside the head section.
The whole structure is called a ruleset. Note the names of the individual parts:
Selector –
This is the HTML element name at the start of the ruleset. It defines the
element(s) to be styled.
Property – These are ways in which you can style an HTML element. In CSS, you
choose which properties you want to affect in the rule.
Value – To the right of the property—after the colon—there is the property value.
This chooses one out of many possible appearances for a given property.
p, li, h1 {
color: red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>CSS Selectors</title>
</head>
<body>
<p>Type Selector</p>
</body>
</html>
if you want to change the text color of the paragraph you can use the name of
the element p and set the color property to the color of your choice
2. Class selector -> The element(s) on the page with the specified class. Multiple
instances of the same class can appear on a page. We use
the . (dot) symbol and the name of the class to use it as a
selector in css
3. Id selector -> The element on the page with the specified ID. On a given
HTML page, each id value should be unique. We use # (hashtag
) symbol and the name of the id as a selector
4. Attribute Selector -> The element(s) on the page with the specified
attribute.
5. Pseudo-class selector -> The specified element(s), but only when in the
specified state. (For example, when a cursor hovers over
a link.)
Q. Read in detail the above ways of selectors it’s definition, advantage, syntax and
examples for each?
When the browser needs to resolve what styles to apply to a given HTML element,
it uses a set of CSS precedence rules. You remember the first letter CSS which stands
for Cascade, this is what the browser uses to resolve conflicting rules in your
stylesheet. The other determining factor in selecting CSS rules is specificity.
Specificity is the means by which browsers decide which CSS property values are the
most relevant to an element and, therefore, will be applied.
Following are CSS precedence rules
1. !important after CSS properties.
2. Specificity of CSS rule selectors.
3. Sequence of declaration.
!important
If you need a certain CSS property to take precedence over all other CSS rules
setting the same CSS property for the same HTML elements, you can add the
instruction !important after the CSS property when you declare it. The !important
instruction has the highest precedence of all precedence factors.
<style>
div {
font-size: 16px !important;
}
.text-size {
font-size: 18px;
}
</style>
<div class="text-size">
!important
</div>
The code above is trying to change the font-size of an element using different
selectors. Normally, since class selectors has higher specificity than a CSS rule with an
Compiled by Computer Science and IT Department Staff
32
element selector, it would take precedence over the first rule. But since the element
selector has the word !important, it will take precedence over the class selector.
Specificity
Specificity is how the browser decides which rule applies if multiple rules have
different selectors, but could still apply to the same element. It is basically a measure
of how specific a selector's selection will be. Specificity is a weight that is applied to a
given CSS declaration, determined by the number of each selector type in the
matching selector.
Selector types
The following list of selector types increases by specificity:
1. Type Selectors (e.g., p) and pseudo-elements(e.g., ::before).
2. Class Selectors (e.g., .examples), attributes selectors (e.g., [type=”radio”] and
pseudo-classes(e.g., :hover)
3. ID Selectors (e.g., #example)
Universal Selector (*), combinators (+, >, ~, || ) and negation pseudo-class (:not())
have no effect on specificity.
The cascade
Stylesheets cascade — at a very simple level, this means that the order of CSS rules
matters; when two rules apply that have equal specificity, the one that comes last in
the CSS is the one that will be used.
p {
color: brown;
}
p {
color: green;
}
We have two rules for the same element p. The paragraph will be green as it comes
last
Lists
In the previous chapter we have seen different types of lists. We have the two
common types of lists => order and unorder lists. In this section we will see how we
will go about styling lists.
Lists behave like any other text for the most part, but there are some CSS
properties specific to lists that you need to know about.
To start with let’s see the default styling of lists, which will surprise you when
designing lists. Here are some of the common default list stylings
- ul and ol element have a default top and bottom margin of 16px(1em) and a
padding left of 40px(2.5em)
- dl element has a top and bottom margin of 16px(1em), but no padding set
- dd elements have a margin-left of 40px(2.5em)
List specific styles
- list-style-types => Sets the type of bullets to use for the list, for example,
square or circle bullets for an unordered list, or numbers, letters, or roman
numerals for an ordered list.
Compiled by Computer Science and IT Department Staff
35
- list-style-position => Sets whether the bullets, at the start of each item,
appear inside or outside the lists.
- list-style-image => Allows you to use a custom image for the bullet, rather
than a simple square or circle.
We can also use the short hand list-style property for the above properties. The
values can be listed in any order, and you can use one, two, or all three (the default
values used for the properties that are not included are disc, none, and outside).
Display
The display CSS property sets whether an element is treated as a block or inline
element and the layout used for its children, such as flow layout, grid or flex.
Formally, the display property sets an element's inner and outer display types. The
If you run the above code and insepect it in your browser, in the style tab under the
source tab of the browser’s developer’s tool you we will see the default styling of <ul>
Now let’s make it look like a navigation bar by adding a background color to the
list like this
background-color: lightblue;
Flexbox
Flexbox is a one-dimensional layout method for arranging items in rows or
columns. Items flex (expand) to fill additional space or shrink to fit into smaller
spaces. There are two kinds of flex elements: the flex container and the flex items that
are placed within the container. All the direct children of the flex container element
are flex items.
To start with, we need to select which elements are to be laid out as flexible boxes.
To do this, we set a special value of display on the parent element of the elements you
want to affect.
When elements are laid out as flex items, they are laid out along two axes:
Grid
CSS Grid Layout excels at dividing a page into major regions or defining the
relationship in terms of size, position, and layer, between parts of a control built from
HTML primitives. Using Grid we can align items into rows and columns.
To use grid in your site, you have to set the wrapper(container) of the items display
property to grid or inline-grid. Next we define the number of columns and rows using
grid-template-columns, grid-template-rows. The values for the two propeties
represent track-size and line-name
Positioning
Positioning allows us to produce interesting results by overriding normal document
flow. There are a number of different types of positioning that you can put into effect
on HTML elements. To make a specific type of positioning active on an element, we
use the position property.
Static Positioning:
Static positioning is the default that every element gets. It just means "put the element
into its normal position in the document flow — nothing special to see here."
div {
position: static;
}
Relative Positioning
This is very similar to static positioning, except that once the positioned element has
taken its place in the normal flow, you can then modify its final position, including
making it overlap other elements on the page. top, bottom, left, and right are used
alongside position to specify exactly where to move the positioned element to.
div {
position: relative;
top: 50%;
left: 50%;
}
Absolute Positioning
An absolutely positioned element no longer exists in the normal document flow.
Instead, it sits on its own layer separate from everything else. This is very useful: it
means that we can create isolated UI features that don't interfere with the layout of
Compiled by Computer Science and IT Department Staff
42
other elements on the page. For example, popup information boxes, control menus,
rollover panels, UI features that can be dragged and dropped anywhere on the page,
and so on. In order for absolute positioning property to work as we want it, we have to
set its container to position relative. If we don’t do that it uses the documents body as
its relative.
div {
position: absolute;
top: 0;
left: 50%;
}
</script>
- Internal JavaScript is one way of including JavaScript using the script tag
inside our HTML document. We can use the above syntax to include it
anywhere in our document. The best place to include a JavaScript file is before
the end of body tag </body>.
- <script>
console.log(“Hello world”)
</script>
- We can also include JavaScript as an external file. We can use a similar syntax
like the internal and add the src attribute. Here is how
The defer attribute (Boolean attribute) is set to indicate to a browser that the
script is meant to be executed after the document has been parsed, but before
firing DOMContentLoaded.
Scripts with the defer attribute will prevent the DOMContentLoaded event from
firing until the script has loaded and finished evaluating. This attribute must not
be used if the src attribute is absent (i.e., for inline scripts), in this case it would
have no effect.
We can also use the async attribute. This is a Boolean attribute indicating that
the browser should, if possible, load the script asynchronously. This attribute
must not be used if the src attribute is absent (i.e., for inline scripts). If it is
included in this case, it will have no effect. Browsers usually assume the worst-
case scenario and load scripts synchronously, (i.e., async="false") during
HTML parsing.
As a rule, only the simplest scripts are put into HTML. More complex ones reside
in separate files.
The benefit of a separate file is that the browser will download it and store it in its
cache.
One other important thing to know is if src is set, the script content is ignored. A
single <script> tag can’t have both the src attribute and code inside.
➢ Prompt will show a modal windows with a text message, an input field for the
visitor, and the buttons OK/Cancel
➢ We can also use confirm to get information from a user:- the function confirm
shows a modal window with a question and two buttons: OK and Cancel
Usage:
document.write(expr)
Logical Operators:
In JavaScript, the logical operators are used to combine two or more conditions.
JavaScript provides the following logical operators.
Loops
Loops are a way to repeat the same code multiple times.
- While loop → while loop has the following syntax
while (condition) {
//"loop body"
}
- Do-while loop → do while loops are very similar to that of while loops, but
in do while even if the condition is false there is always on execution
do{
//"loop body"
} while (condition);
- the length property can be used to get the total counts of elements in the array
- Arrays can store elements of any type
Methods
- Push → appends an element to the end
- Pop → takes an element from the end.
- Shift → Extracts the first element of the array and returns it
- Unshift → Add the element to the beginning of the array:
element = document.querySelector(selectors);
Accessing an element with the class of “myclass”
var el = document.querySelector(".myclass");
A more Complex Selector
var el = document.querySelector("div.myclass”)
element.style.backgroundColor = “red”;
Here’s a list of the most useful DOM events, just to take a look at:
Event Handlers
To react on events we can assign a handler – a function that runs in case of an event.
Handlers are a way to run JavaScript code in case of user actions.
There are several ways to assign a handler. Let’s see them, starting from the simplest
one.
addEventListener
The fundamental problem of the aforementioned ways to assign handlers – we can’t
assign multiple handlers to one event. To add an event in an element we can use
addEventListener function.
event
Event name, e.g. "click".
handler
The handler function.
options
An additional optional object with properties:
// code...
} catch (err) {
// error handling
In order to start working with forms with JavaScript we need to intercept the
submit event on the form element:
})
Now inside the submit event handler function we call the event.preventDefault()
method to prevent the default behavior and avoid a form submit to reload the page,
this gives us control. After we gain control over the submit event we can all kind of
stuff, like form validation
Form Validation
<html>
<head>
<title>Form Validation</title>
document.myForm.Name.focus() ;
return false;
</script>
</head>
<body>
</form>
</body>
</html>
document.getElementById("header");
Window Size
Two properties can be used to determine the size of the browser window.
A global variable, window, representing the window in which the script is running,
is exposed to JavaScript code.
In a tabbed browser, each tab is represented by its own Window object; the global
window seen by JavaScript code running within a given tab always represents the tab
in which the code is running. That said, even in a tabbed browser, some properties and
methods still apply to the overall window that contains the tab, such as resizeTo() and
innerHeight. Generally, anything that can't reasonably pertain to a tab
Window Location
Some examples:
When a web server has sent a web page to a browser, the connection is shut down,
and the server forgets everything about the user. Cookies were invented to solve the
problem "how to remember information about the user":
When a user visits a web page, his/her name can be stored in a cookie.
Next time the user visits the page, the cookie "remembers" his/her name.
When a browser requests a web page from a server, cookies belonging to the page
are added to the request. This way the server gets the necessary data to "remember"
information about users.
JavaScript can create, read, and delete cookies with the document.cookie property.
You can also add an expiry date (in UTC time). By default, the cookie is deleted
when the browser is closed:
With a path parameter, you can tell the browser what path the cookie belongs to.
By default, the cookie belongs to the current page.
The Document property cookie lets you read and write cookies associated with the
document. It serves as a getter and setter for the actual values of the cookies.
By default, PHP documents end with the extension .php. When a web server encounters
this extension in a requested file, it automatically passes it to the PHP processor. At its
very simplest, a PHP document will output only HTML.
<?php
//php script
?>
If you use this style, you can be positive that your tags will always be correctly
interpreted. The way you use this tag is quite flexible. Some programmers enclose
everything between this opening and closing tag. Others, however, choose to insert only
wherever dynamic scripting is required, leaving the rest of the document in standard
HTML.
Unless you have a very, very strong reason to prefer one of the other styles, use this
Compiled by Computer Science and IT Department Staff
60
one. Some
or all of the other styles of PHP tag may be phased out in the future—only this one is
certain to be safe.
Short-open (SGML-style) tags
Short or short-open tags look like this:
<?
//php script
?>
Those who escape into and out of HTML frequently in each script will be attracted by
the prospect of fewer keystrokes; however, the price of shorter tags is pretty high.
Additional adjustment in the php.ini file is required to enable PHP to recognize the
tags. PHP code written with short-open tags is less portable because you can‘t be sure
another machine will have enabled them in the php.ini file.
When you need multiple-line comments, there’s a second type of comment. PHP
multi-line line comment begins with /* , and ends with */.
<?php
?>
- In PHP, a variable does not need to be declared before adding a value to it.
PHP automatically converts the variable to the correct data type, depending on
its value.
- After declaring a variable, it can be reused throughout the code.
- The assignment operator (=) used to assign value to a variable.
- In php there are two types of variables Predefined and user defined
PHP provides a large number of predefined variables to any script which it runs.
PHP provides an additional set of predefined arrays containing variables from the web
server the environment, and user input. These new arrays are called superglobals −
All the following variables are automatically available in every scope.
- $GLOBALS → Contains a reference to every variable which is currently
available within the global scope of the script. The keys of this array are the
names of the global variables.
- $_SERVER → This is an array containing information such as headers, paths,
and script locations. The entries in this array are created by the web server.
There is no guarantee that every web server will provide any of these. See next
section for a complete list of all the SERVER variables.
- $_GET → An associative array of variables passed to the current script via the
HTTP GET method.
- $_POST → An associative array of variables passed to the current script via
the HTTP POST method.
You can also give multiple arguments to the unparenthesized version of echo,
separated by commas, as in:
echo “This will print in the “, “user‟s browser window.”;
The parenthesized version, however, will not accept multiple arguments:
echo (“This will produce a “, “PARSE ERROR!”);
Print
The command print is very similar to echo, with two important differences:
✦ unlike echo, print can accept only one argument.
✦ unlike echo, print returns a value, which represents whether the print
statement succeeded. The value returned by print will be 1 if the
printing was successful and 0 if unsuccessful.
Example: the following program will add two numbers and display the result in the
page
<HTML>
<HEAD>
<title>some title</title>
</HEAD>
<BODY>
<?php
$first=6;
$second=5;
$result=$first+$second;
Echo $result;
Compiled by Computer Science and IT Department Staff
64
?>
</BODY>
</html>
Arithmetic Operators:
Arithmetic operators do what you would expect. They are used to perform
mathematics. You can use them for the main four operations (plus, minus, multiply, and
divide) as well as to find a modulus (the remainder after a division) and to increment or
decrement a value.
Logical Operators:
As a rule, if something has a TRUE or FALSE value, it can be input to a logical
operator. A logical operator takes two true-or-false inputs and produces a true-
or-false result. The PHP logical operators are sued to combine conditional statements.
The if Statement
- if statement: Executes a block of code if the given condition is true.
- if-else statement: Executes a block of code if a condition is true or another
block of code if that condition is false.
- if elseif else statement: Used to test more than one condition with different
blocks of code.
- switch statement: Alternative for If-elseif statement.
Compiled by Computer Science and IT Department Staff
65
Syntax:
if (condition) {
//code to be executed(condition is true);
} elseif (condition) {
//code to be executed (elseif condition is true)
} else {
//code to be executed
}
E.g.
Let’s write a program that checks the time in your local machine and prints
something depending on what the time its
<?php
$t = date("H");
Ternary Operators
The Ternary operators are a form of Shorthand Technique for the If-else
statement. It uses a question mark (?) and a colon (:) with three operands: a
condition which will be evaluated, an action for TRUE and an action for FALSE.
Look at the syntax and things will get cleared
Switch
Use the switch statement to select one of many blocks of code to be executed.
Syntax
1. for loop:
This type of loops is used when the user knows in advance, how many times
the block needs to execute. That is, the number of iterations is known
beforehand. These types of loops are also known as entry-controlled loops.
There are three main parameters to the code, namely the initialization, the test
condition and the counter.
Syntax:
<?php
for($y = 0; $y <= 10; $y++){
echo "The value of Y is: $x <br>";
2. while loop: The while loop is also an entry control loop like for loops i.e., it
first checks the condition at the start of the loop and if its true then it enters the
loop and executes the block of statements, and goes on executing it as long as
the condition holds true.
while (if the condition is true) {
// code is executed
}
3. do-while loop: This is an exit control loop which means that it first enters the
loop, executes the statements, and then checks the condition. Therefore, a
statement is executed at least once on using the do…while loop. After
executing once, the program is executed as long as the condition holds true.
do {
//code is executed
} while (if condition is true);
<?php
$y = 1;
do {
echo "The value of Y is: $y <br>";
$y++;
} while ($y <= 5);
?>
4. foreach loop: This loop is used to iterate over arrays. For every counter of
loop, an array element is assigned and the next counter is shifted to the next
element.
foreach(array_element as value) {
//code to be executed
}
Syntax
An array can be created using the array() language construct. It takes any number
of comma-separated key => value pairs as arguments.
array(
key => value,
key2 => value2,
key3 => value3,
...
)
E.g.
<?php
$array1 = array("Item 1", "Item 2", "Item 3", "Item 4");
?>
The use of => is similar to the regular = assignment operator, except that you are
assigning a value to an index and not to a variable.
print_r($sample);
?>
In the example above, each time you assign a value to the array $sample, the first empty
location within that array is used to store the value, and a pointer internal to PHP is
incremented to point to the next free location, ready for future insertions.
We have also used the print_r function (which prints out the contents of a variable,
array, or object) is used to verify that the array has been correctly populated.
print_r($sample);
?>
Iterating arrays
We can use any of the loop statements we have seen above to iterate through arrays. In
the next example we will add items to an array and retrieve them
<?php
$sample[] = "sample 1";
$sample [] = "sample 2";
$sample [] = "sample 3";
$sample [] = "sample 4";
The problem with the example above is that we don’t always know the size of the array ahead of time. In this case
we case use the count and sizeof php functions to get the number of items in the array instead of hard coding it.
The modified version the example above is shown here
<?php
$sample[] = "sample 1";
$sample [] = "sample 2";
$sample [] = "sample 3";
$sample [] = "sample 4";
Associative Arrays
Associative arrays unlike normal arrays enable has to reference items in an array by
name rather than by number. Adding items to associative array and retrieving them
<?php
$sample[index1] = "sample 1";
print_r($sample);
?>
This very powerful feature of PHP is often used when you are extracting information
from XML and HTML. For example HTML parsers uses associative arrays whose
name reflect the page’s structure
<?php
$j = 0;
foreach($array1 as $item)
{
echo "$j: $item<br>";
++$j;
}
?>
PHP comes with hundreds of ready-made functions. You have seen some of them
like print, echo, count, sizeof
Compiled by Computer Science and IT Department Staff
71
print(“hello world”)
The parenthesis tells php that you are referring to a function. Otherwise, PHP
thinks you are referencing to a constant. Functions can take any number of arguments,
including zero
Declaring functions
Function definitions have the following form:
function function_name([parameter [, ...]])
{
// Statements
}
That is, function definitions have four parts:
- A definition starts with the word function.
- A name follows, which must start with a letter or underscore, followed by
any number of letters, numbers, or underscores.
- The parentheses are required.
- One or more parameters, separated by commas, are optional
Example:
function info($name,$age,$salary){
echo “name:”.$name.”<br>”;
echo “age:”.$age.”<br>”;
echo “salary:”.$salary.”<br>”; }
Form Validation:
{
$error = "*" . "Please fill all the required fields";
}
else
{
$firstname = $_POST['firstname'];
}
}
?>
<html>
<head>
<title>Simple Form Processing</title>
</head>
<body>
FirstName:
<input type="text" name="firstname"/>
<span style="color:red;">*</span>
<br>
<br>
<input type="submit" value="Submit"
name="submit" />
</form>
</fieldset>
</body>
</html>
<?php
$target_dir = "uploads/";
$target_file = $target_dir .
basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType
= strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check =
getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
$_SESSION['views']=1;
echo "Views=". $_SESSION['views']; ?>
Destroying a Session
If you wish to delete some session data, you can use the unset() or the
session_destroy() function. The unset() function is used to free the specified session
variable:
<?php
unset($_SESSION['views']);
?>
You can also completely destroy the session by calling the session_destroy() function:
<?php
session_destroy();
?>
session_destroy() will reset your session and you will lose all your stored session data.
What is a Cookie?
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.
How to Create a Cookie?
The setcookie() function is used to set a cookie.
Note: The setcookie() function must appear BEFORE the <html> tag.
Syntax
setcookie(name, value, expire, path, domain);
Example
In the example below, we will create a cookie named "user" and assign the value
"Alex Porter" to it. We also specify that the cookie should expire after one hour:
In the example below, we retrieve the value of the cookie named "user" and display it
on a page:
<?php
// Print a cookie
echo $_COOKIE["user"];
// A way to view all cookies
print_r($_COOKIE);
?>
- The MySQL Database Server is very fast, reliable, scalable, and easy to use.
Open Source means that it is possible for anyone to use and modify the
software. Anybody can download the MySQL software from the Internet and
use it without paying anything.
$resultvar – is an optional result variable. This is used when the query is a select
statement.
Query – is any valid insert, delete, update, select, create table or drop table
statement enclosed by quotes. It is a good habit to hold the query in a separate variable
to add flexibility to your code.
Link identifier-is an optional link identifier
The result of a query returned by the mysql_query() function is an interger showing the
success or failure of the function not the desired data. So you have to use one of the
mysql_fetch_..() functions to get the actual result. There are many functions to do so, but
the most commonly used ones are- Mysql_fetch_row($result) – this function takes the
result of the mysql_query() function as an argument and returns the data as an
enumerated array.
Example: assume the student table has three attrubutes - id,name and department.
$query=”select * from student”;
$result=mysql_query($query);
while($row=mysql_fetch_row($result)){
echo “$row[0].$row[1].$row[2]”;//counting
starts from 0 not 1
}
mysql_fetch_object($result) - this function takes the result of the
mysql_query() function as an argument and returns the data as an object.
Example:
$query=”select * from student”;
}
Mysql_fetch_array($result) - this function takes the result of the mysql_query() function
as an argument and returns the data as an enumerated or associative array. This is the
most widely used fetching function since results are displayed in association to their
column values.
Example:
$query=”select * from student”;
$result=mysql_query($query);
While($row=mysql_fetch_array($result)){
Echo “$row[„id‟] . $row-[„name‟] . $row[„department‟]”;
//mysql_fetch_array() could be used with the enumerated type just
//like the mysql_fetch_row function.
}
5. Closing the connection
After you have finished the mysql query the last thing you have to do is close the
connection.
Syntax: MySQL-close([link identifier]);
5.14 Input-Output
PHP has several functions for creating, reading, uploading, and editing files. The
fopen() function is used to open files in PHP.
Opening a file
The first parameter of this function contains the name of the file to be opened and
the second parameter specifies in which mode the file should be opened: Example
<html>
<body>
<?php
?>
</body>
</html>
Modes Description
Note: If the fopen() function is unable to open the specified file, it returns 0
(false).
readfile() Function
The readfile() function reads a file and writes it to the output buffer.
Assume we have a text file called "hello.txt", stored on the server, that looks like
this:
<?php
echo readfile("webdictionary.txt");
?>
$file = fopen("test.txt","r");
fclose($file);?>
?>
Time zone management has become more prominent in recent years with the onset of
web portals and social web communities like Facebook and Twitter.
There are a total of four interrelated classes for handling dates and times. The Date
Time class handles dates themselves; the DateTimeZone class handles time zones; the
DateTimeInterval class handles spans of time between two DateTime instances; and
finally, the DatePeriod class handles traversal over regular intervals of dates and times.
The constructor of the DateTime class is naturally where it all starts. This method
takes
two parameters, the timestamp and the time zone. For example:
$dt = new DateTime("2010-02-12 16:42:33", new DateTimeZone("America/Halifax"));
Now obviously we are assigning hardcoded values to these classes, and this type of
The diff() method of DateTime does what you might expect—it returns the difference
between two dates. The return value of the method is an instance of the DateInterval
class.
$tz = ini_get('date.timezone');
$dtz = new DateTimeZone($tz);
The math functions can handle values within the range of integer and float types.The PHP
math functions are part of the PHP core. No installation is required to use these functions.
Here are some PHP math functions, you can get the whole list from the internet
cos — Cosine
Example
<?php
echo abs(-4.2); // 4.2 (double/float)
echo abs(5); // 5 (integer)
echo abs(-5); // 5 (integer)
?>
OOP Case
Let's assume we have a class named Fruit. A Fruit can have properties like name,
color, weight, etc. We can define variables like $name, $color, and $weight to hold the
values of these properties.
When the individual objects (apple, banana, etc.) are created, they inherit all the
properties and behaviors from the class, but each object will have different values for
the properties.
Creating Objects
To create an object of a given class, use the keyword new
Compiled by Computer Science and IT Department Staff
85
$object = new Class;
Assuming that a Fruit class has been defined, here’s how to create a Fruit object:
Some classes permit you to pass arguments to the new call. The class’s documentation
should say whether it accepts arguments. If it does, you’ll create objects like this:
of the object:
$object->propertyname $object->methodname([arg, … ])
Methods act the same as functions (only specifically to the object in question), so they
can take arguments and return a value. Within a class’s definition, you can specify
which methods and properties are publicly accessible and which are accessible only
from within the class itself using the public and private access modifiers.
Declaring a Class
A class definition includes the class name and the properties and methods of the class.
Class names are case-insensitive and must conform to the rules for PHP identifiers.
The class name stdClass is reserved. Here’s the syntax for a class definition:
Declaring Methods
Within a method, the $this variable contains a reference to the object on which the
method was called. For instance, if you call $apple->getWeight(), inside the
getWeight() method, $this holds the same value as $apple. Methods use the $this
variable to access the properties of the current object and to call other methods on that
object. Here’s a simple class definition of the Fruit class that shows the $this variable
in action:
class Fruit
{
public $weight = '';
function getWeight()
{
return $this->weight;
}
function setWeight($newWeight)
{
$this->weight = $newWeight;
}
}
To declare a method as a static method, use the static keyword. Inside of static
methods
the variable $this is not defined. If you declare a method using the final keyword,
subclasses cannot override that method.
Declaring Properties
Property declarations are optional and are simply a courtesy to whomever maintains
your program. It’s good PHP style to declare your properties, but you can add new
Compiled by Computer Science and IT Department Staff
87
properties at any time. Here’s a version of the Person class that has an undeclared
$name property:
class Fruit
{
public $weight = '';
function setWeight($newWeight)
{
$this->weight = $newWeight;
}
}
open() takes three parameters, the first is the HTTP request method and the second
is the URL. The optional third parameter sets whether the request is asynchronous.
Compiled by Computer Science and IT Department Staff
89
6.4 Handling Response from Server
Before making a request to the server we have to write a callback function which
will handle the response. But Because Ajax calls are asynchronous, we can't be sure
when the response will come, so we must write code to wait for the response and
handle it when it arrives. That is what the callback function is used for
httpRequest.onreadystatechange = nameOfTheFunction;
a. Bootstrap
Now a days the website you build has to support all browser types and all sizes
of screen (Desktop, Tablets, Phones etc..). To make that possible we use
different frameworks. This part of the chapter will introduce you to the
Bootstrap framework.
Bootstrap is a free front end framework for faster and easier web development.
It is s an open-source tool collection for creating responsive websites and web
applications. It is the most popular HTML, CSS, and JavaScript framework for
developing responsive, mobile-first websites.
Bootstrap solves many problems that we face when using HTML,CSS and
vanilla JavaScript.
To add bootstrap you can either use the bootstrapCDN or you can download it and
use it locally. Here are the steps to add the bootstrapCDN to our project,
1. Copy-paste the stylesheet <link> into your <head> before all other stylesheets
to load our CSS.
- JQuery
- then boostrap
b. Node.js
Node is an open source, cross platform runtime environment that allows developers to
create server-side tools and applications in JavaScript. As an asynchronous event-
driven JavaScript runtime, Node.js is designed to build scalable network applications.
To use Node, We first have to install Node in our system. You can follow the
installation process from the official Node website.
After the installation you can start building a web server using Node. To create a
node application follow the following steps
res.statusCode = 200;
Compiled by Computer Science and IT Department Staff
92
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
});
server.listen(port, () => {
});
Assignment: Write a simple node server that accepts a message from a client
c. Angular.js
Angular is a development platform, built on TypeScript. As a platform, Angular
includes:
1. A component-based framework for building scalable web applications
2. A collection of well-integrated libraries that cover a wide variety of features,
including routing, forms management, client-server communication, and more
3. A suite of developer tools to help you develop, build, test, and update your
code
The fastest and recommended way to develop angular application is using angular
CLI(Command line interface). The CLI makes a number of task easy. Here are some
of the commands
ng
Generates or modifies files based on a schematic.
generate
ng e2e Builds and serves an Angular application, then runs end-to-end tests.
Assignment: Write a simple hello world angular app using angular cli
d. React.js
React can also be use to create mobile application using React Native, you can
read more about this and how to set it up from the official website.
We can create a React app using the create-react-app. Create React App is the best
way to start building a new single-page application in React. It sets up your
development environment so that you can use the latest JavaScript features, provides a
nice developer experience, and optimizes your app for production.
React does not enforce strict rules around code conventions or file organization.
React also utilizes features of modern JavaScript for many of its patterns. React allows
us to include HTML codes into our JavaScript code by using JSX. JSX is a syntax
extension of JavaScript. Here is an example of JSX syntax
The above code doesn’t work with normal JavaScript, you can check this by
running the following code in the developers tool console.
use npm start to run the application (Make sure you cd to the the folder created by
the create-react-app command)
Reading Assignment
1. Componnets
2. Props
3. State