HTML - CSS - Part1 - Part3
HTML - CSS - Part1 - Part3
o Introduction to basic HTML Aligning the Headings
<tagname>content</tagname>
HTML5
<!DOCTYPE html>
HTML 4.01
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
XHTML 1.0
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
HTML 1991
HTML 2.0 1995
HTML 3.2 1997
HTML 4.01 1999
XHTML 2000
HTML5 2014
-1-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
o Anchor Tag
<a href="http://www.google.com ">This is a link</a>
o Paragraph
<p>This is a paragraph. </p>
<p>This is another paragraph. </p>
o Images and Pictures
<img src="blog.jpg" alt="blog photo" width="300" height="300">
o Tables
---------task
<!DOCTYPE html>
<html>
<head>
<title>Demo page</title>
</head>
<body>
<table border="1">
<tr>
<td rowspan="2">
1
</td>
<td colspan="2">
2
</td>
</tr>
<tr>
<td >
5
</td>
<td rowspan="2">
6
</td>
</tr>
<tr>
<td colspan="2">
7
</td>
</tr>
</table>
</body>
</html>
-2-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
Framesets
<frameset cols="25%,25%,50*">
<frame src="a.html">
<frame src="b.html">
<frame src="c.html">
</frameset>
Or, add a link to the bookmark ("Useful Tips Section"), from another page:
</body>
HTML Fonts
<h1 style="font-family:verdana" >This is a heading </h1>
<p style="font-family:courier" >This is a paragraph. </p>
-4-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
<address>
Written by Jon Doe. <br>
Visit us at:<br>
Example.com<br>
Box 564, Disneyland <br>
USA
</address>
Comments
Conditional Comments
<!--[if IE 8]>
<style>
some style
</style>
<![endif]-->
<!--[if IE 7]>
.... some HTML here ....
<![endif]-->
<!--[if IE 6]>
.... some HTML here ....
<![endif]-->
<html>
<head>
<style>
body {background-color:lightgray}
h1 {color:blue}
-5-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
p {color:green}
</style>
</head>
<body>
</body>
</html>
<html>
<head>
<style>
body {background-color:lightgrey}
h1 {color:blue}
p {color:green}
</style>
</head>
<body>
</body>
</html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
-6-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
</body>
</html>
body {background-color:lightgrey}
h1 {color:blue}
p {color:green}
p {
border:1px solid black;
}
p {
border:1px solid black;
padding:10px;
}
or
p {
border:1px solid black;
padding:2px 5px 10px 20px;
}
p {
border:1px solid black;
padding:10px;
margin:30px;
}
margin-left
margin-right
margin-bottom
margin-top
The id Attribute
to define a special style for one special element,
first add an id attribute to the element:
p#p01 {
color:blue;
}
Example
Cascading style sheet
Linking a style to an HTML document
In line style
External style sheet
Internal style sheet
Multiple styles
Introduction to DHTML
or
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
Cell padding specifies the space between the cell content and its borders.
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 15px;
}
-10-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Points</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
</table>
<br>
<table id="t01">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Points</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
</table>
</body>
</html>
HTML Lists
Unordered HTML Lists
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
-11-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
Style Description
list-style-type:disc The list items will be marked with bullets (default)
list-style-type:circle The list items will be marked with circles
list-style-type:square The list items will be marked with squares
list-style-type:none The list items will not be marked
<ul style="list-style-type:square" >
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
<ol type="1">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
<dl>
<dt>Coffee</dt>
<dd>- black hot drink </dd>
<dt>Milk</dt>
<dd>- white cold drink </dd>
</dl>
Horizontal Lists
<html>
<head>
<style>
ul#menu li {
display:inline;
}
</style>
</head>
<body>
<ul id="menu">
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
<li>PHP</li>
</ul>
</body></html>
<div>
<h1> - <h6>
<p>
<form>
Inline Elements
<span>
<a>
<img>
Inline Elements
-13-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
An inline element does not start on a new line and only takes up as much width as necessary.
<span>
<a>
<img>
<h2>London</h2>
<p>London is the capital city of England. It is the most populous city in the United
Kingdom, with a metropolitan area of over 13 million inhabitants. </p>
</div>
The <span> element is an inline element that is often used as a container for some text.
HTML Layouts
<style>
#header {
background-color:black;
color:white;
text-align:center;
padding:5px;
}
#nav {
line-height:30px;
background-color:#eeeeee;
height:300px;
width:100px;
float:left;
padding:5px;
}
#section {
width:350px;
float:left;
padding:10px;
}
#footer {
background-color:black;
-14-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
color:white;
clear:both;
text-align:center;
padding:5px;
}
</style>
<body>
<div id="header">
<h1>City Gallery</h1>
</div>
<div id="nav">
London<br>
Paris<br>
Tokyo<br>
</div>
<div id="section">
<h1>London</h1>
<p>
London is the capital city of England. It is the most populous city in the United Kingdom,
with a metropolitan area of over 13 million inhabitants.
</p>
<p>
Standing on the River Thames, London has been a major settlement for two millennia,
its history going back to its founding by the Romans, who named it Londinium.
</p>
</div>
<div id="footer">
Copyright
</div>
</body>
layout.png
<style>
header {
background-color:black;
color:white;
text-align:center;
padding:5px;
}
-15-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
nav {
line-height:30px;
background-color:#eeeeee;
height:300px;
width:100px;
float:left;
padding:5px;
}
section {
width:350px;
float:left;
padding:10px;
}
footer {
background-color:black;
color:white;
clear:both;
text-align:center;
padding:5px;
}
<body>
<header>
<h1>City Gallery</h1>
</header>
<nav>
London<br>
Paris<br>
Tokyo<br>
</nav>
<section>
<h1>London</h1>
<p>
London is the capital city of England. It is the most populous city in the United Kingdom,
with a metropolitan area of over 13 million inhabitants.
</p>
<p>
Standing on the River Thames, London has been a major settlement for two millennia,
its history going back to its founding by the Romans, who named it Londinium.
</p>
</section>
<footer>
Copyright
</footer>
</body>
HTML Iframes
An iframe is used to display a web page within a web page.
Iframe Syntax
-16-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
HTML colors
#FF0000 rgb(255,0,0) Red
#00FF00 rgb(0,255,0) Green
#0000FF rgb(0,0,255) Blue
style="color:#FF0000"
style="color:red"
o Microdata
Microdata lets you define your own customized elements
and start embedding custom properties in your web pages.
At a high level, microdata
consists of a group of name-value pairs.
<html>
<body>
<div itemscope>
<p>My name is <span itemprop="name">Zara</span>.</p>
</div>
<div itemscope>
<p>My name is <span itemprop="name">Nuha</span>.</p>
</div>
</body>
</html>
-17-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
o ARIA accessibility
<ul role="menubar">
What is Multimedia?
Multimedia comes in many different formats. It can be almost anything you can hear or see.
Examples: Pictures, music, sound, videos, records, films, animations, and more.
HTML5 Video
-18-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
o 2D and 3D drawing Support
Canvas Examples
A canvas is a rectangular area on an HTML page. By default, a canvas has no border and no
content.
Assignment – Lab:
Create your bio‐data in an HTML Page.
Divide it into following sections –
Personal information,
Family Background,
Academic Qualifications,
and Experience.
Now divide a HTML page into
three frames as upper,
left and right (main) frames.
Write a Heading in the upper frame and
put the bio‐data sections links in the left frame
and on click the section links the respective detail
information should be displayed into the right main frame.
Session 2: HTML (Cont…)
Lecture:
Forms
HTML Forms
-19-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
<form>
.
form elements
.
</form>
HTML Controls
o INPUT
The <input> Element
<form>
First name:<br>
<input type="text" name="firstname">
<br>
Last name:<br>
<input type="text" name="lastname">
</form>
o Text Area
o Radio Button
<form>
<input type="radio" name="gender" value="male" checked>Male
<br>
<input type="radio" name="gender" value="female">Female
</form>
o Check Box
o Dropdown
Create a drop-down list with four options:
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
o Submit button
<input type="submit">
defines a button for submitting a form to a form-handler.
o Button
HTML <button> Tag
<button type="button">Click Me!</button>
-21-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
Two button elements that act as one submit button and one reset button (in a form):
<form action="demo_form.php" method="get">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<button type="submit" value="Submit">Submit</button>
<button type="reset" value="Reset">Reset</button>
</form>
Assignment 1– Lab:
Write a CSS rule
that changes the color of all the elements with attribute CLASS =”Green‐Move”
to green and shift them down 25 pixels and right 15 pixels.
Assignment 2– Lab:
Create a form to submit a resume
Session 3: JavaScript
Lecture
Introduction to JavaScript
What is JavaScript?
JavaScript Can Change HTML Content
Advantages of using Java Script on client side over VB Script
vb script is not supported by all the browsers and it
is one of the oldest methods of scripting
How to embed JavaScript in HTML Page?
External JavaScript
<script src="myScript.js"></script>
How it works?
one the html file is loaded on the Browser,
it executes the javascript code from the html file
-22-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
How to handle events?
HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.
Example
<button onclick="alert('monday')" >The day is?</button>
Variables in Java Script
var x;
x = 6;
1001
'John Doe'
javaScript uses an
assignment operator ( = ) to assign values to variables:
var x = 5;
var y = 6;
Array in Java Script
Using array methods (length, reverse,
sort etc)
var x = cars.length; // The length property returns the number of elements in cars
var y = cars.sort(); // The sort() method sort cars in alphabetical order
Sorting an Array
The sort() method sorts an array alphabetically:
Reversing an Array
Assignment – Lab:
Implement factorial in Java Script.
Session 4: JavaScript (Cont…)
Lecture:
Creating Objects in Java Script
Object Methods
Methods are actions that can be performed on objects.
-24-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
or
objectName["propertyName"]
objectName.methodName()
Example
name = person.fullName();
Local variables have local scope: They can only be accessed within the function.
Example
// code here can not use carName
function myFunction() {
var carName = "Volvo";
function myFunction() {
Automatically Global
If you assign a value to a variable that has not been declared, it will automatically
become a GLOBAL variable.
This code example will declare carName as a global variable, even if it is executed inside
a function.
Example
// code here can use carName
function myFunction() {
-25-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
carName = "Volvo";
o Date
Date();
new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
<script>
var d = new Date(87,5,12,11,33,30,0);
document.getElementById("demo").innerHTML = d;
</script>
o String
JavaScript Strings
A JavaScript string simply stores a series of characters like "John Doe".
A string can be any text inside quotes. You can use single or double quotes:
String Length
The length of a string is found in the built in
property length:
Example
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
-26-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
Special Characters
var x = 'It's alright';
\ escape character.
Operators
o Arithmetic
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement
o Logical
== 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
Boolean Values
Very often, in programming, you will need a data type that
can only have one of two values, like
YES / NO
ON / OFF
TRUE / FALSE
o Bitwise
| OR x = 5 | 1
eg: 0101 | 0001 //result 0101 (5)
~ NOT x = ~ 5
eg: ~0101 // result = 1010 (10)
^ XOR x = 5 ^ 1
eg:0101 ^ 0001 // result = 0100 (4)
o this
this keyword points to the current element/object
o delete
the purpose of the delete operator is to completely
remove a property from an object,
Control and Looping Statements
Use if to specify a block of code to be executed,
if a specified condition is true
if (condition) {
block of code to be executed if the condition is true
}
if (condition) {
block of code to be executed if the condition is true
} else {
block of code to be executed if the condition is false
}
} else {
greeting = "Good evening";
}
Syntax
switch(expression) {
case n:
code block
break;
case n:
code block
break;
default:
default code block
}
Assignment – Lab:
Write a program to sort input strings.
Display a complete date with the name of the
Session and name of the month
Session 5: JavaScript (Conti.)
Lecture: Functions
A JavaScript function is a block of code designed to perform a particular task.
function myFunction(a, b) {
res=a*b;
alert(res);
}
var x = myFunction(4, 3);
or
-29-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
function myFunction(a, b) {
return a * b; // Function returns the product of a and b
}
Common Events
An HTML event can be something the browser does, or something a user does.
o onClick
Mouse Event
onclick The event occurs when the user clicks on an element
o onLoad
Frame/Object Event
onload The event occurs when an object has loaded
<body onload="myFunction()">
o onMouseOver
Mouse Event
onmouseover The event occurs when the pointer
is moved onto an element, or onto one of its children
o onReset
Form Event
onreset The event occurs when a form is reset
<form onreset="myFunction()">
Enter name: <input type="text">
<input type="reset">
</form>
o onSubmit
Form Event
onsubmit The event occurs when a form is submitted
<form onsubmit="myFunction()">
Enter name: <input type="text">
<input type="submit">
</form>
Different functions:
-30-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
o alert(), prompt(), confirm().
Alert Box
An alert box is often used if you want to
make sure information comes through to the user.
Confirm Box
A confirm box is often used if you want the user to
verify or accept something.
When a confirm box pops up, the user will have to click
either "OK" or "Cancel" to proceed.
window.confirm("sometext");
Example
var r = confirm("Press a button");
if (r == true) {
x = "You pressed OK!";
} else {
x = "You pressed Cancel!";
}
Prompt Box
A prompt box is often used if you want the user to input
a value before entering a page.
When a prompt box pops up, the user will have to click
either "OK" or "Cancel" to proceed after
entering an input value.
If the user clicks "OK" the box returns the input value.
If the user clicks "Cancel" the box returns null.
o eval
The eval() function evaluates or executes an argument.
var a = eval("x * y");
o isFinite
The isFinite() function determines
whether a number is a finite, legal number.
var a = isFinite(123);
var b = isFinite(-1.23);
var c = isFinite(5-2);
var d = isFinite(0);
var e = isFinite("123");
-31-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
var f = isFinite("Hello");
var g = isFinite("2005/12/12");
o isNaN
the isNaN() function determines
whether a value is an illegal number (Not-a-Number).
var a = isNaN(123)
var f = isNaN("Hello")
o parseInt and parseFloat
o Number and String
o escape and unescape
The escape() function encodes a string.
Need%20tips%3F%20Visit%20us%21
document.write(unescape(a))
DOM
In the HTML DOM (Document Object Model),
everything is a node:
var x = document.forms.length;
var x = document.doctype;
document.getElementById("myH1").style.color = "red";
Object hierarchy in Java Script
Working With
o Window
o Form
o Document
o Frame
-32-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
Assignment – Lab:
Validate the above resume form using the Java Script
Session 6:
Introducing to jQuery
jQuery
<head>
<script src="jquery.js"></script>
</head>
Selecting the elements
Basic syntax is: $(selector).action()
A $ sign to define/access jQuery
A (selector) to "query (or find)" HTML elements
A jQuery action() to be performed on the element(s)
AJAX
Examples:
Bringing pages to life with jQuery
Session 7:
JQuery Events
The Document Ready Event
$(document).ready(function(){
});
click
dblclick
mouseenter
mouseleave
keypress
keydown
-33-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
keyup
submit
load
change
resize
focus
scroll
blur
unload
$("p").click(function(){
// action goes here!!
});
Energizing pages with animations and effects
$(selector).hide(speed,callback);
//milliseconds speed
$("#hide").click(function(){
$("p").hide();
});
$("#show").click(function(){
$("p").show();
});
$("button").click(function(){
$("p").toggle();
});
DOM with jQuery utility functions
Commonly Used jQuery Event Methods
click()
The function is executed when the user clicks on the HTML element.
$("p").click(function(){
$(this).hide();
});
dblclick()
mouseleave()
$("#p1").mouseleave(function(){
alert("Bye! You now leave p1!");
});
mousedown()
-34-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
hover()
$("#flip").click(function(){
$("#panel").slideDown();
});
slideUp()
$("#flip").click(function(){
$("#panel").slideUp();
});
slideToggle()
$("#flip").click(function(){
$("#panel").slideToggle();
});
$(selector).animate({params},speed,callback);
$("button").click(function(){
$("div").animate({left: '250px'});
});
$("button").click(function(){
$("div").animate({
left: '250px',
opacity: '0.5',
height: '150px',
width: '150px'
});
});
$("#btn1").click(function(){
alert("Text: " + $("#test").text());
});
$("#btn2").click(function(){
alert("HTML: " + $("#test").html());
});
$("#btn1").click(function(){
alert("Value: " + $("#test").val());
});
$("#btn1").click(function(){
$("#test1").text("Hello world!");
});
$("#btn2").click(function(){
$("#test2").html(" <b>Hello world!</b>");
});
$("#btn3").click(function(){
$("#test3").val("Dolly Duck");
});
$("button").click(function(){
$("#w").attr("href", "a.html");
});
$("button").click(function(){
$("#w3s").attr({
"href" : "http://www.google.com/jquery",
"title" : "cdac jQuery Tutorial"
});
-36-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
});
.important {
font-weight: bold;
font-size: xx-large;
}
.blue {
color: blue;
}
$("button").click(function(){
$("h1, h2, p").addClass("blue");
$("div").addClass("important");
});
$("button").click(function(){
$("#div1").addClass("important blue");
});
$("button").click(function(){
$("h1, h2, p").removeClass("blue");
});
$("button").click(function(){
$("h1, h2, p").toggleClass("blue");
});
Accessing DOM
DOM.PNG
ancestor - descendant
parent - child - siblings
parent()
The parent() method returns the direct parent
element of the selected element.
$(document).ready(function(){
var sel="span";
$(sel).parent();
});
parents()
The parents() method returns all ancestor elements of the selected element,
all the way up to the document's root element ( <html>).
$(document).ready(function(){
$("span").parents();
});
You can also use an optional parameter to filter the search for ancestors.
$(document).ready(function(){
$("span").parents("ul");
});
parentsUntil()
The parentsUntil() method returns all ancestor elements between two given arguments.
$(document).ready(function(){
$("span").parentsUntil("body");
});
$(document).ready(function(){
$("div").children();
});
find()
$(document).ready(function(){
$("div").find("ul");
});
Session 8:
Introduction of UI Scripting Framework
-38-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
Bootstrap is the most popular HTML, CSS, and JavaScript framework for developing
responsive, mobile-first web sites.
Bootstrap is a free front-end framework for faster and easier web development
Bootstrap includes HTML and CSS based design templates for typography,
forms, buttons, tables, navigation, modals, image carousels and many other,
as well as optional JavaScript plugins
Bootstrap also gives you the ability to easily create responsive designs
Advantages of Bootstrap:
Easy to use: Anybody with just basic knowledge of HTML and CSS can start using Bootstrap
Responsive features: Bootstrap's responsive CSS adjusts to phones, tablets, and desktops
Mobile-first approach: In Bootstrap 3, mobile-first styles are part of the core framework
Browser compatibility: Bootstrap is compatible with all modern browsers
(Chrome, Firefox, Internet Explorer, Safari, and Opera)
Session 9: PHP
Lecture:
PHP is a server scripting language, and a powerful tool for
making dynamic and interactive Web pages.
Basic rule of PHP
PHP scripts are executed on the server.
PHP is an acronym for "PHP: Hypertext Preprocessor"
PHP is a widely-used, open source scripting language
PHP scripts are executed on the server
PHP is free to download and use
PHP files can contain text, HTML, CSS, JavaScript, and PHP code
PHP code are executed on the server, and the result is returned
to the browser as plain HTML
PHP files have extension ".php"
Why PHP?
PHP runs on various platforms
(Windows, Linux, Unix, Mac OS X, etc.)
PHP is compatible with almost all servers used today
(Apache, IIS, etc.)
PHP supports a wide range of databases
What Do I Need?
To start using PHP, you can:
PHP in action
-40-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
EXAMPLE:
<!DOCTYPE html>
<html>
<body>
<?php
echo "Hello World!";
?>
</body>
</html>
Working with text, variable and numbers
In PHP, a variable starts with the $ sign, followed by the name of the variable:
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
local
global
static
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>
myTest();
myTest();
myTest();
?>
<?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
?>
Display Variables
<?php
$txt1 = "Learn PHP";
$txt2 = "cdac.com";
$x = 5;
$y = 4;
echo "<h2>$txt1</h2>";
echo "Study PHP at $txt2<br>";
echo $x + $y;
?>
<?php
print "<h2>PHP is Fun!</h2>";
print "Hello world!<br>";
print "I'm about to learn PHP!";
?>
-42-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
<?php
$txt1 = "Learn PHP";
$txt2 = "cdac.com";
$x = 5;
$y = 4;
print "<h2>$txt1</h2>";
print "Study PHP at $txt2<br>";
print $x + $y;
?>
PHP String
A string is a sequence of characters, like "Hello world!".
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
PHP Integer
<?php
$x = 5985;
?>
PHP Boolean
$x = true;
$y = false;
PHP Array
<?php
$cars = array("Volvo","BMW","Toyota");
?>
<?php
echo str_word_count ("Hello world!"); // outputs 2
?>
Reverse a String
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
PHP Constants
A constant is an identifier (name) for a simple value.
The value cannot be changed during the script.
Syntax
define(name, value, case-insensitive)
<?php
define("GREETING", "Welcome to cdac!");
echo GREETING;
?>
function myTest() {
echo GREETING;
}
myTest();
?>
Comments in PHP
<!DOCTYPE html>
<html>
<body>
<?php
// This is a single-line comment
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
-44-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
?>
</body>
</html>
PHP Case Sensitivity
In PHP, all 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 Operators
Operators are used to perform operations on variables and values.
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators
-45-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
Making decisions and repeating yourself
PHP Conditional Statements
if statement - executes some code only if a specified condition is true
if...else statement - executes some code if a condition is true and another code if the
condition is false
if...elseif....else statement - specifies a new condition to test, if the first condition
is false
switch statement - selects one of many blocks of code to be executed
Arrays
<?php
$t = 20;
<?php
$t = 20;
<?php
$t = 20;
<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
PHP Loops
while - loops through a block of code as long as the specified condition is true
do...while - loops through a block of code once, and then repeats the loop as long as the
specified condition is true
for - loops through a block of code a specified number of times
foreach - loops through a block of code for each element in an array
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
<?php
$x = 6;
do {
echo "The number is: $x <br>";
$x++;
} while ($x<=5);
?>
-47-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
<?php
$colors = array("red", "green", "blue", "yellow");
Working with Arrays
In PHP, the array() function is used to create an array:
array();
PHP Arrays
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
Looping through array
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
Sorting arrays
-49-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
?>
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);
?>
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
arsort($age);
?>
Functions
function functionName() {
code to be executed;
}
<?php
function writeMsg() {
echo "Hello world!";
}
<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
<?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}
familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
?>
<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // will use the default value of 50
-50-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
setHeight(135);
setHeight(80);
?>
<?php
function sum($x, $y) {
$z = $x + $y;
return $z;
}
$res=sum(5, 10);
echo $res;
Assignment –
Lab:
Write a simple program in PHP.
Write a program in PHP that uses the increment operator (++)
and combined multiplication (*=)
operator to print out the numbers from 1 to 5 and powers of 2 from 2(2^1) to 32(2^5)
Session 10: PHP
Lecture:
Making web forms
PHP Global Variables - Superglobals
Superglobals were introduced in PHP 4.1.0,
and are built-in variables that are always available in all scopes.
$GLOBALS
PHP $GLOBALS
$GLOBALS is a PHP super global variable which is used to access global variables
from anywhere in the PHP script (also from within functions or methods).
<?php
$x = 75;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;
?>
$_SERVER
PHP $_SERVER
-51-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
<?php
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
?>
$_REQUEST
PHP $_REQUEST is used to collect data after submitting an HTML form.
<html>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_REQUEST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>
$_POST
PHP $_POST
PHP $_POST is widely used to collect form data after submitting an HTML
form with method="post". $_POST is also widely used to pass variables.
<html>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
-52-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
</html>
$_GET
PHP $_GET
PHP $_GET can also be used to collect form data after submitting an HTML form with
method="get".
$_GET can also collect data sent in the URL.
<html>
<body>
</body>
</html>
$_FILES
$_ENV
$_COOKIE
$_SESSION
Form processing with functions
<html>
<body>
</body>
</html>
<html>
<body>
</body>
</html>
Validating data
empty() - checks if the variable contains any value or not.
-53-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
Sanitize a String
The following example uses the filter_var() function to remove all HTML tags from a string:
<?php
$str = "<h1>Hello World!</h1>";
$newstr = filter_var($str, FILTER_SANITIZE_STRING );
echo $newstr;
?>
Validate an Integer
The following example uses the filter_var() function to check if the variable $int is an
integer.
<?php
$int = 100;
// Validate e-mail
if (!filter_var($email, FILTER_VALIDATE_EMAIL ) === false) {
echo("$email is a valid email address");
} else {
echo("$email is not a valid email address");
}
?>
// Validate url
if (!filter_var($url, FILTER_VALIDATE_URL ) === false) {
echo("$url is a valid URL");
} else {
echo("$url is not a valid URL");
}
-54-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
?>
Display default value
value attriblute helps in fetching default values
Working with cookies and Sessions
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
<?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
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>
-55-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the past:
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 1);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
<?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
session_start();
-56-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>
<?php
print_r($_SESSION);
?>
</body>
</html>
Modify a PHP Session Variable
To change a session variable, just overwrite it:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>
</body>
</html>
<?php
// remove all session variables
session_unset();
-57-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
</body>
</html>
Login and User Identification
How does it work? How does it know it's me?
Parsing, display date and times
The PHP date() function is used to format a date and/or a time.
Syntax
date(format,timestamp)
Parameter Description
Here are some characters that are commonly used for dates:
Example
<?php
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y.m.d") . "<br>";
echo "Today is " . date("Y-m-d") . "<br>";
echo "Today is " . date("l");
?>
The example below outputs the current time in the specified format:
Example
<?php
echo "The time is " . date("h:i:sa");
?>
Assignment – Lab:
Write a simple program to remembering user with cookies and Sessions
Session 11: PHP
Lecture:
Storing information with databases
PHP MySQL Database
MySQL is the most popular database system used with PHP.
MySQL is a database system used on the web
MySQL is a database system that runs on a server
MySQL is ideal for both small and large applications
MySQL is very fast, reliable, and easy to use
MySQL uses standard SQL
MySQL compiles on a number of platforms
MySQL is free to download and use
MySQL is developed, distributed, and supported by Oracle Corporation
MySQL is named after co-founder Monty Widenius's daughter: My
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.
Databases are useful for storing information categorically. A company may have a database
with the following tables:
Employees
Products
Customers
Orders
Connection to database
PHP Connect to MySQL
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error ());
}
echo "Connected successfully";
?>
-59-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error ());
}
// Create database
$sql = "CREATE DATABASE myDB";
mysqli_query($conn, $sql);
mysqli_close($conn);
?>
Create a table
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error ());
}
mysqli_query($conn, $sql)
mysqli_close($conn);
?>
Inserting and retrieving data from database
The INSERT INTO statement is used to add new records to a MySQL table:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error ());
}
mysqli_query($conn, $sql);
mysqli_close($conn);
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error ());
}
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
Assignment – Lab:
-61-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
Write a program to implement various databases queries.
Session 12: PHP
Lecture:
?>
Modes Description
r Open a file for read only.
File pointer starts at the beginning of the file
-62-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
<!DOCTYPE html>
<html>
<body>
</body>
</html>
attribute: enctype="multipart/form-data".
<?php
Checking for errors
Assignment – Lab:
Write a program to implement various file operation.
Write a program in PHP for Sending mails
Session 13:
-63-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
XML
What is XML?
The XML language is a way to structure data for sharing across websites.
XML is easy to create. It looks a lot like HTML, except that you make up your own tags.
Assume we have an XML file called "note.xml", that looks like this:
<?php
$xml=simplexml_load_file("note.xml") or die("Error: Cannot create object");
print_r($xml);
?>
SimpleXMLElement Object
( [to] => Tove [from] => Jani [heading] => Reminder
[body] => Don't forget me this weekend! )
Tove
Jani
Reminder
Don't forget me this weekend!
Assignment – Lab:
Create some basic XML documents and check them out in the IE browser for validity.
Session 14: DTD
Lecture
Creating Document Type Declarations.
Creating Document Type
Definition.
Internal and External DTD’s
Associating DTD’s with XML documents. (The XML Declaration and DOCTYPE declaration.)
Validating documents against a DTD
Internal and External General Entities.
Element Type (ELEMENT) Declarations.
Attribute (ATTLIST) Declarations.
Using INCLUDE and IGNORE.
Session 15: W3C DOM and Data Binding
Lecture
- discussed in javascript and jquery
Session 16:
Lecture
json
Session 17:
Ajax
Introduction to Ajax
Ajax using HTML, CSS, JavaScript and DOM
XMLHttpRequest
Ajax Architecture
Introduction to the JavaScript Object Notation (JSON)
Session 18: Web Services
Creating a windows web services
Web services and Ajax
Session 19: Ajax Framework
JPSpan
DWR
Assignment
– Lab:
A Login and Registration system using Ajax
Session 20: Web security
SQL Injection
Cross‐Site Scripting (XSS)
Session 21: Joomla
Introduction to Joomla
-65-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM
Planning Your Website.
A Domain Name and Web Hosting.
Installing Joomla
Introduction to Joomla Administrator Interface.
Section and Category Structure, editing & deleting
Articles in Joomla
Session 22: Joomla
Menu
Templates and Modules
Components( Contacts and Web Links)
Session 23: Joomla
Installing and Configuring Simple Image Gallery.
Users and Permissions.
Assignment – Lab:
Create a simple website using Joomla
with all above features
-66-