You are on page 1of 66

C:\Users\TechStratus\Desktop\cdac\Complete.

html Thursday, November 5, 2015 10:02 AM

o Introduction to basic HTML Aligning the Headings

The DOCTYPE declaration defines the document type to be HTML


The text between <html> and </html> describes an HTML
document
The text between <head> and </head> provides information
about the document

The text between <title> and </title> provides a title for


the document

The text between <body> and </body> describes the visible


page content
The text between <h1> and </h1> describes a heading
The text between <p> and </p> describes a paragraph

<tagname>content</tagname>

HTML tags normally come in pairs like <p> and </p>


The first tag in a pair is the start tag, the second tag
is the end tag
The end tag is written like the start tag, but with a slash
before the tag name
 
Common Declarations

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

How To create a HTML PAGE

Step 1. Open Notepad


Step 2: Write Some HTML
Step 3: Save the HTML Page

--Select File > Save as in the Notepad menu


--Name the file "index.html" or any other name ending with
html or htm.

Step 4: View HTML Page in Your Browser

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

The <frameset> tag is not supported in HTML5.

HTML Links - The target Attribute

The target attribute specifies where to open the linked document.

<a href="http://www.google.com/ " target="_blank">


Visit Google!
</a>

_blank Opens the linked document in a new window or tab


_self Opens the linked document in the same frame as
it was clicked (this is default)

framename Opens the linked document in a named frame

HTML Links - Create a Bookmark

HTML bookmarks are used to allow readers to jump


to specific parts of a Web page.

<h2 id="tips">Useful Tips Section </h2>

<a href="#tips">Visit the Useful Tips Section </a>

Or, add a link to the bookmark ("Useful Tips Section"), from another page:

<a href="html_tips.htm#tips" >Visit the Useful Tips Section </a>


-3-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM

---- html style--


<body style="background-color:lightgrey" >

<h1>This is a heading </h1>


<p>This is a paragraph. </p>

</body>

HTML Text Color


<h1 style="color:blue">This is a heading </h1>
<p style="color:red">This is a paragraph. </p>

HTML Fonts
<h1 style="font-family:verdana" >This is a heading </h1>
<p style="font-family:courier" >This is a paragraph. </p>

HTML Text Size


<h1 style="font-size:40px" >This is a heading </h1>
<p style="font-size:60px" >This is a paragraph. </p>

HTML Text Alignment


<h1 style="text-align:center" >Centered Heading </h1>
<p>This is a paragraph. </p>

Use the style attribute for styling HTML elements


Use background-color for background color
Use color for text colors
Use font-family for text fonts
Use font-size for text sizes
Use text-align for text alignment

HTML Bold and Strong Formatting


<p>This text is normal. </p>

<p><b>This text is bold </b>.</p>

HTML Italic and Emphasized Formatting


<p>This text is normal. </p>

<p><i>This text is italic </i>.</p>

HTML Small Formatting


<h2>HTML <small>Small</small> Formatting</h2>

HTML Subscript and Superscript Formatting


<p>This is <sup>superscripted</sup> text.</p>
<p>This is <sub>superscripted</sub> text.</p>

-4-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM

HTML <abbr> for Abbreviations


The HTML <abbr> element defines an abbreviation or an acronym.

Marking abbreviations can give useful information to browsers,


translation systems and search-engines

The HTML <abbr> element defines an abbreviation or an acronym.

Marking abbreviations can give useful information to browsers,


translation systems and search-engines
<p>The <abbr title="World Health Organization" >WHO</abbr>
was founded in 1948. </p>

HTML <address> for Contact Information


The HTML <address> element defines contact information
(author/owner) of a document or article.

The <address> element is usually displayed in italic.


Most browsers will add a line break before and after the element.

<address>
Written by Jon Doe. <br>
Visit us at:<br>
Example.com<br>
Box 564, Disneyland <br>
USA
</address>

The HTML <code> element defines programming code:


<code>
var person = { firstName:"John", lastName:"Doe", age:50, eyeColor:"blue" }
</code>

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

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

<h1>This is a heading </h1>


<p>This is a paragraph. </p>

</body>
</html>

CSS stands for Cascading Style Sheets

Styling can be added to HTML elements in 3 ways:

Inline - using a style attribute in HTML elements


Internal - using a <style> element in the HTML <head> section
External - using one or more external CSS files

element { property:value; property:value }

Inline Styling (Inline CSS)


Inline styling uses the style attribute.
<h1 style="color:blue">This is a Blue Heading </h1>

Internal Styling (Internal CSS)


Internal styling is defined in the <head> section of an HTML page,
using a <style> element:

<html>
<head>
<style>
body {background-color:lightgrey}
h1 {color:blue}
p {color:green}
</style>
</head>
<body>

<h1>This is a heading </h1>


<p>This is a paragraph. </p>

</body>
</html>

External Styling (External CSS)


External styles are defined in an external CSS file,
and then linked to in the <head> section of an HTML page:

<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

<h1>This is a heading </h1>


<p>This is a paragraph. </p>

</body>
</html>

---style.css file content

body {background-color:lightgrey}
h1 {color:blue}
p {color:green}

The CSS Box Model

Every HTML element has a box around it,


even if you cannot see it.

The CSS border property defines a visible border


around an HTML element:

p {
border:1px solid black;
}

The CSS padding property defines a padding (space)


inside the border:

p {
border:1px solid black;
padding:10px;
}

or

p {
border:1px solid black;
padding:2px 5px 10px 20px;
}

The CSS margin property defines a margin (space)


outside the border:
-7-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM

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 id="p01">I am different</p>

p#p01 {
color:blue;
}

To define a style for a special type (class) of elements,


add a class attribute to the element:

Example

<p class="error">I am different</p>


p.error {
color:red;
}

Use id to address single elements.


Use class to address groups of elements.

Deprecated Tags and Attributes in HTML5

In older HTML versions, several tags and attributes were


used to style documents.

These tags and attributes are not supported in HTML5!

Avoid using the <font>, <center>, and <strike> elements.

Avoid using the color and bgcolor attributes.

Use the HTML style attribute for inline styling


Use the HTML <style> element to define internal CSS
Use the HTML <link> element to refer to an external CSS file
Use the HTML <head> element to store <style> and <link>
elements

Use the CSS color property for text colors


Use the CSS font-family property for text fonts
Use the CSS font-size property for text sizes
-8-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM

Use the CSS border property for visible element borders


Use the CSS padding property for space inside the border
Use the CSS margin property for space outside the border

 Cascading style sheet 
 Linking a style to an HTML document 
 In line style 
 External style sheet 
 Internal style sheet 
 Multiple styles 
 Introduction to DHTML 

Use the HTML <a> element to define a link


Use the HTML href attribute to define the link address
Use the HTML target attribute to define where to open the
linked document

Use the HTML <img> element (inside <a>) to use an image as a


link

Use the HTML id attribute (id="value") to define bookmarks in a


page

Use the HTML href attribute (href="#value") to link to the


bookmark

An HTML Table with a Border Attribute


<table border="1" style="width:100%">
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>

To add borders, use the CSS border property:


Example
table, th, td {
border: 1px solid black;
}

or

table, th, td {
border: 1px solid black;
border-collapse: collapse;
}

An HTML Table with Cell Padding


-9-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM

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

HTML Table Headings


Table headings are defined with the <th> tag.
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Points</th>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>

An HTML Table with Border Spacing


table {
border-spacing: 5px;
}
<!DOCTYPE html>
<html>
<head>
<style>
table {
width:100%;
}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
text-align: left;
}
table#t01 tr:nth-child(even) {
background-color: #eee;
}
table#t01 tr:nth-child(odd) {
background-color:#fff;
}
table#t01 th {
background-color: black;
color: white;
}
</style>
</head>
<body>

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

Ordered HTML Lists

<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>

Ordered HTML Lists - The Type Attribute


type="1" The list items will be numbered with numbers (default)
type="A" The list items will be numbered with uppercase letters
type="a" The list items will be numbered with lowercase letters
type="I" The list items will be numbered with uppercase roman numbers
type="i" The list items will be numbered with lowercase roman numbers

<ol type="1">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>

HTML Description Lists

HTML also supports description lists.

A description list is a list of terms, with a description of each term.

The <dl> tag defines the description list,


the <dt> tag defines the term (name), and the <dd> tag describes each term:

<dl>
<dt>Coffee</dt>
<dd>- black hot drink </dd>
<dt>Milk</dt>
<dd>- white cold drink </dd>
</dl>

Horizontal Lists

HTML lists can be styled in many different ways with CSS.

One popular way, is to style a list to be displayed horizontally:


-12-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM

<html>

<head>
<style>
ul#menu li {
display:inline;
}
</style>
</head>

<body>

<h2>Horizontal List </h2>

<ul id="menu">
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
<li>PHP</li>
</ul>

</body></html>

HTML Block and Inline Elements


Block-level Elements

A block-level element always starts on a new


line and takes up the full width available
(stretches out to the left and right as far as it can).

Examples of block-level elements:

<div>
<h1> - <h6>
<p>
<form>

Inline Elements

An inline element does not start on a new line


and only takes up
as much width as necessary.

This is an inline <span> element inside a paragraph.

Examples of 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.

This is an inline <span> element inside a paragraph.

Examples of inline elements:

<span>
<a>
<img>

The <div> Element

The <div> element is a block-level element that is


often used as a container for other HTML elements.

<div style="background-color:black; color:white; padding:20px;" >

<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

The <span> element is an inline element that is often used as a container for some text.

<h1>My <span style="color:red">Important</span> Heading</h1>

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>

Website Layout Using HTML5

layout.png

header Defines a header for a document or a section


nav Defines a container for navigation links
section Defines a section in a document
article Defines an independent self-contained article
aside Defines content aside from the content (like a sidebar)
footer Defines a footer for a document or a section
details Defines additional details
summary Defines a heading for the details element

<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

The syntax for adding an iframe is:


<iframe src="URL"></iframe>

-16-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM

Iframe - Set Height and Width

Use the height and width attributes to specify the size.

The attribute values are specified in pixels by default,


but they can also be in percent (like "80%").
Example
<iframe src="iframe.htm" width="200" height="200"></iframe>

Iframe - Remove the Border


style="border:none"

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.

The groups are called items,


and each name-value pair is a property.
Items and properties are represented by regular elements.

To create an item, the itemscope attribute is used.

To add a property to an item,


the itemprop attribute is used on one of the item's descendants.

<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 

WAI-ARIA is a spec defining support for accessible web apps.


It defines bunch of markup extensions (mostly as attributes on HTML5 elements),
which can be used by the web app developer to provide additional information
about the semantics of the various elements to assistive technologies like screen readers.
Of course, for ARIA to work, the HTTP user agent that interprets the markup
needs to support ARIA, but the spec is created in such a way,
as to allow down-level user agents to ignore the ARIA-specific markup
safely without affecting the web app's functionality.

Here's an example from the ARIA spec:

<ul role="menubar">

<!-- Rule 2A: "File" label via aria-labelledby -->


<li role="menuitem" aria-haspopup="true" aria-labelledby="fileLabel">
<span id="fileLabel">File</span>
<ul role="menu">

<!-- Rule 2C: "New" label via Namefrom:contents -->


<li role="menuitem" aria-haspopup="false">New</li>
<li role="menuitem" aria-haspopup="false">Open…</li>

</ul>
</li>

</ul>
o Multimedia
HTML Multimedia

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

<video width="320" height="240" controls>


<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>

HTML <video> Autoplay


<video width="320" height="240" autoplay>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>

-18-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM

The HTML <audio> Element


to play an audio file in HTML, use the <audio> element: 
<audio controls>
<source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>

o 2D and 3D drawing Support 

What is HTML Canvas?

The HTML <canvas> element is used to draw graphics, on the fly,


via scripting (usually JavaScript).

Canvas Examples

A canvas is a rectangular area on an HTML page. By default, a canvas has no border and no
content.

The markup looks like this:


<canvas id="myCanvas" width="200" height="100"></canvas>

Basic Canvas Example


<canvas id="myCanvas" width="200" height="100"
style="border:1px solid #000000;" >
</canvas>

 
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

The <form> Element

-19-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM

HTML forms are used to collect user input.

The <form> element defines an HTML form:

<form>
.
form elements
.
</form>

 HTML Controls 
o INPUT 
The <input> Element

The <input> element is the most important form element.

The <input> element has many variations,


depending on the type attribute

text Defines normal text input


radio Defines radio button input (for selecting one of many choices)
submit Defines a submit button (for submitting the form)

<form>
First name:<br>
<input type="text" name="firstname">
<br>
Last name:<br>
<input type="text" name="lastname">
</form>

o Text Area

The <textarea> tag defines a multi-line text input control.

<textarea rows="4" cols="50">


sample data
</textarea>  

o Radio Button 

<input type="radio"> defines a radio button.

Radio buttons let a user select ONE of a limited number of choices:


-20-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM

<form>
<input type="radio" name="gender" value="male" checked>Male
<br>
<input type="radio" name="gender" value="female">Female
</form>

o Check Box

<form action="#" method="get">


<input type="checkbox" name="vehicle" value="Bike">
I have a bike<br>
<input type="checkbox" name="vehicle" value="Car" checked>
I have a car<br>
<input type="submit" value="ok">
</form>  

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 

The Submit Button

<input type="submit">
defines a button for submitting a form 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="action_page.php" >


First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" value="Submit">
</form>

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

HTML <button> type Attribute

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>

button The button is a clickable button


submit The button is a submit button (submits form-data)
reset The button is a reset button (resets the form-data to its initial values)

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

JavaScript is the programming language of HTML and the Web.

Programming makes computers do what you want them to do.

JavaScript is easy to learn.

 What is JavaScript? 
JavaScript Can Change HTML Content

JavaScript Can Change HTML Attributes

JavaScript Can Change HTML Styles (CSS)

JavaScript Can Validate Data

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

The <script> </script> Tag

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? 

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.

With single quotes:

<some-HTML-element some-event='some JavaScript'>

Example
<button onclick="alert('monday')" >The day is?</button>

 Variables in Java Script 

var x;

x = 6;

Numbers are written with or without decimals:


10.50

1001

Strings are text, written within double or single quotes:


"John Doe"

'John Doe'

javaScript uses an
assignment operator ( = ) to assign values to variables:
var x = 5;
var y = 6;

JavaScript uses arithmetic operators ( + - * / )


to compute values:

var res=(5 + 6) * 10;


alert(res);

JavaScript is Case Sensitive


All JavaScript identifiers are case sensitive.

The variables lastName and lastname, are two different variables.


-23-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM

JavaScript - Display data


Writing into an alert box, using window.alert().
Writing into the HTML output using document.write().
Writing into an HTML element, using innerHTML.
Writing into the browser console, using console.log().

 Array in Java Script 

var cars = ["Saab", "Volvo", "BMW"];


document.getElementById("demo").innerHTML = cars;

Access the Elements of an Array


var cars = ["Saab", "Volvo", "BMW"];
var name = cars[0];

 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

The length Property

The length property of an array returns the


length of an array (the number of array elements).

Sorting an Array
The sort() method sorts an array alphabetically:

Reversing an Array

The reverse() method reverses the elements in an array.

You can use it to sort an array in descending order:

Assignment – Lab: 
 Implement factorial in Java Script. 
 
Session 4: JavaScript (Cont…)  
Lecture:  
 Creating Objects in Java Script

A car has properties like weight and color,


and methods like start and stop:
var car = {type:"Fiat", model:500, color:"white"};

The values are written as name:value pairs


(name and value separated by a colon).

The name:values pairs (in JavaScript objects)


are called properties.

Object Methods
Methods are actions that can be performed on objects.

Methods are stored in properties as function definitions.

-24-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM

Accessing Object Properties


objectName.propertyName

or

objectName["propertyName"]

Accessing Object Methods

You access an object method with the following syntax:

objectName.methodName()

Example
name = person.fullName();

Local JavaScript Variables


Variables declared within a JavaScript function, become LOCAL to the function.

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

// code here can use carName

Global JavaScript Variables

A variable declared outside a function, becomes GLOBAL.

A global variable has global scope:


All scripts and functions on a web page can access it.
var carName = " Volvo";

// code here can use carName

function myFunction() {

// code here can use carName

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

// code here can use carName

 
o Date

Date();

Creating Date Objects

The Date object lets us work with dates.

A date consists of a year, a month, a day, an hour, a minute,


a second, and milliseconds.

Date objects are created with the new Date() constructor.

There are 4 ways of initiating a 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:

var carname = "Volvo XC60";


var carname = 'Volvo XC60';
var answer = "It's alright";
var answer = "He is called 'Johnny'";
var answer = 'He is called "Johnny"';

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.

var x = 'It\'s alright';

\' single quote


\" double quote
\\ backslash
\n new line

 Operators 
o Arithmetic 

+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement

JavaScript String Operators


The + operator can also be used to add (concatenate) strings.

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

Boolean(10 > 9) // returns true

o Bitwise 

& AND x = 5 & 1


-27-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM

eg: 0101 & 0001 // result = 1

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

<< Left shift x = 5 << 1


0101 << 1 // result 1010

>> Right shift x = 5 >> 1


0101 >> 1 //result 0010

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

Use else to specify a block of code to be executed,


if the same condition is false

Use else if to specify a new condition to test,


if the first condition is false

Use switch to specify many alternative blocks of code to be executed

if (condition) {
block of code to be executed if the condition is true
}

if (hour < 18) {


greeting = "Good day";
}

The else Statement

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
}

if (hour < 18) {


greeting = "Good day";
-28-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM

} else {
greeting = "Good evening";
}

 The else if Statement


if (condition1) {
block of code to be executed if condition1 is true
} else if (condition2) {
block of code to be executed if the condition1 is false and condition2 is true
} else {
block of code to be executed if the condition1 is false and condition2 is false
}

if (time < 10) {


greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}

The JavaScript Switch Statement


Use the switch statement to select one of many blocks of code to be executed.

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
}

var x = myFunction(4, 3);

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

<some-HTML-element some-event='some JavaScript'>

o onClick 
Mouse Event
onclick The event occurs when the user clicks on an element

<button onclick="myFunction()">Click me</button>

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

<img onmouseover="Myfunction();" src="smiley.gif" alt="Smiley">

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.

alert("I am an alert box!");

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.

If the user clicks "OK", the box returns true. If


the user clicks "Cancel", the box returns false.

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.

var person = prompt("Please enter your name", "Harry Potter");


if (person != null) {
document.getElementById("demo").innerHTML =
"Hello " + person + "! How are you today?";
}

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.

This function makes a string portable, so it can be transmitted


across any network to any computer that supports ASCII characters.

document.write(escape("Need tips? Visit us"));


The output of the code above will be:

Need%20tips%3F%20Visit%20us%21

the unescape() function decodes an encoded string.


var a="Need%20tips%3F%20Visit%20us%21";

document.write(unescape(a))

 DOM 
In the HTML DOM (Document Object Model),
everything is a node:

The document itself is a document node


All HTML elements are element nodes
All HTML attributes are attribute nodes
Text inside HTML elements are text nodes
Comments are comment nodes

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:

$(this).hide() - hides the current element.

$("p").hide() - hides all <p> elements.

$(".test").hide() - hides all elements with class="test".

$("#test").hide() - hides the element with id="test".

 Bringing pages to life with jQuery  
 
Session 7: 
 JQuery Events 
The Document Ready Event
$(document).ready(function(){

// jQuery methods go here...

});

The element Selector


The #id Selector
The .class Selector

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 click() method attaches an event handler function to an HTML element.

The function is executed when the user clicks on the HTML element.

$("p").click(function(){
$(this).hide();
});

dblclick()

The dblclick() method attaches an event handler function to an HTML element


$("p").dblclick(function(){
$(this).hide();
});

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

The mousedown() method attaches an event handler function to an HTML element.


$("#p1").mousedown(function(){
alert("Mouse down over p1!");
});

hover()

The hover() method takes two functions and is a


combination of the mouseenter() and mouseleave() methods.

$("#p1").hover(function(){alert("You entered p1!");},


function(){alert("Bye! You now leave p1!");});

jQuery Sliding Methods


jQuery slideDown() Method
$(selector).slideDown(speed,callback);

$("#flip").click(function(){
$("#panel").slideDown();
});

slideUp()

$("#flip").click(function(){
$("#panel").slideUp();
});

slideToggle()
$("#flip").click(function(){
$("#panel").slideToggle();
});

jQuery Animations - The animate() Method

$(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'
});
});

Get Content - text(), html(), and val()


-35-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM

text() - Sets or returns the text content of selected elements


html() - Sets or returns the content of selected elements (including HTML markup)
val() - Sets or returns the value of form fields

$("#btn1").click(function(){
alert("Text: " + $("#test").text());
});

$("#btn2").click(function(){
alert("HTML: " + $("#test").html());
});

$("#btn1").click(function(){
alert("Value: " + $("#test").val());
});

Get Attributes - attr()


$("button").click(function(){
alert($("#w").attr("href"));
});

Set Content - text(), html(), and val()


text() - Sets or returns the text content of selected elements
html() - Sets or returns the content of selected elements (including HTML markup)
val() - Sets or returns the value of form fields

$("#btn1").click(function(){
$("#test1").text("Hello world!");
});
$("#btn2").click(function(){
$("#test2").html(" <b>Hello world!</b>");
});
$("#btn3").click(function(){
$("#test3").val("Dolly Duck");
});

Set Attributes - attr()

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

});

jQuery Manipulating CSS

addClass() - Adds one or more classes to the selected elements


removeClass() - Removes one or more classes from the
selected elements

toggleClass() - Toggles between adding/removing classes


from the selected elements

css() - Sets or returns the style attribute

.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");
});

jQuery - css() Method


$("p").css("background-color", "yellow");

$("p").css({"background-color": "yellow", "font-size": "200%"});

Accessing DOM

DOM.PNG

ancestor - descendant
parent - child - siblings

An ancestor is a parent, grandparent, great-grandparent, and so on.


A descendant is a child, grandchild, great-grandchild, and so on.
-37-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM

Siblings share the same parent.

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.

The following example returns all


ancestors of all <span> elements that are <ul> elements:

$(document).ready(function(){
$("span").parents("ul");
});

parentsUntil()
The parentsUntil() method returns all ancestor elements between two given arguments.

$(document).ready(function(){
$("span").parentsUntil("body");
});

jQuery Traversing - Descendants


The children() method returns all direct children of the selected element.
children()

$(document).ready(function(){
$("div").children();
});

find()

The find() method returns descendant elements of the selected


element, all the way down to the last descendant.

$(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 completely free to download and use!

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

What is Responsive Web Design?

Responsive web design is about creating web sites which automatically


adjust themselves to look good on all devices, from small phones to large desktops.

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)
 

GET BOOTSTRAP Files 


<!-- Latest compiled and minified CSS -->
<link rel="stylesheet"
href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css ">

<!-- jQuery library -->


<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js "></script>

<!-- Latest compiled JavaScript -->


<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js "></script>

Session 9:  PHP 
Lecture: 
PHP is a server scripting language, and a powerful tool for
making dynamic and interactive Web pages.

PHP is a widely-used, free, and efficient alternative to


competitors such as Microsoft's ASP.

 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

What is a PHP File?


-39-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM

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"

What Can PHP Do?


PHP can generate dynamic page content
PHP can create, open, read, write, delete,
and close files on the server

PHP can collect form data


PHP can send and receive cookies
PHP can add, delete, modify data in your database
PHP can be used to control user-access
PHP can encrypt data

With PHP you are not limited to output HTML.


You can output images, PDF files, and even Flash movies.
You can also output any text, such as XHTML and XML.
 

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

PHP is free. Download it from the official PHP resource: www.php.net


PHP is easy to learn and runs efficiently on the server side

What Do I Need?
To start using PHP, you can:

Find a web host with PHP and MySQL support


Install a web server on your own PC,
and then install PHP and MySQL

Set Up PHP on Your Own PC


However, if your server does not support PHP, you must:

install a web server


install PHP
install a database, such as MySQL

 PHP in action  

Basic PHP Syntax


A PHP script can be placed anywhere in the document.

A PHP script starts with <?php and ends with ?>:


<?php
// PHP code goes here
?>

-40-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM

EXAMPLE:

<!DOCTYPE html>
<html>
<body>

<h1>My first PHP page </h1>

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

PHP Variables Scope


PHP has three different variable scopes:

local
global
static

Global and Local Scope


<?php
$x = 5; // global scope

function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();

echo "<p>Variable x outside function is: $x</p>";


?>

<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();

// using x outside the function will generate an error


echo "<p>Variable x outside function is: $x</p>";
?>
-41-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM

PHP The global Keyword


<?php
$x = 5;
$y = 10;

function myTest() {
global $x, $y;
$y = $x + $y;
}

myTest();
echo $y; // outputs 15
?>

PHP The static Keyword


<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}

myTest();
myTest();
myTest();
?>

PHP 5 echo and print Statements


In PHP there are two basic ways to get output: echo and print.

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

Get The Length of a String


The PHP strlen() function returns the length of a string.
<?php
echo strlen("Hello world!"); // outputs 12
?>

Count The Number of Words in a String


The PHP str_word_count() function counts the number of words in a string:

<?php
echo str_word_count ("Hello world!"); // outputs 2
?>

Reverse a String
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>

Search For a Specific Text Within a String


The PHP strpos() function searches for a specific text within a string.
<?php
-43-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM

echo strpos("Hello world!", "world"); // outputs 6


?>

Replace Text Within a String


The PHP str_replace() function replaces some characters with some other characters in a
string.
<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
?>

PHP Constants
A constant is an identifier (name) for a simple value.
The value cannot be changed during the script.

Create a PHP Constant


To create a constant, use the define() function.

Syntax
define(name, value, case-insensitive)

name: Specifies the name of the constant


value: Specifies the value of the constant

case-insensitive: Specifies whether the constant name


should be case-insensitive. Default is false

<?php
define("GREETING", "Welcome to cdac!");
echo GREETING;
?>

Constants are Global


<?php
define("GREETING", "Welcome to cdac.com!");

function myTest() {
echo GREETING;
}

myTest();
?>

Comments in PHP

<!DOCTYPE html>
<html>
<body>

<?php
// 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
*/
-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.

PHP divides the operators in the following groups:

Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators

PHP Arithmetic Operators


Operator Name Example
+ Addition $x + $y
- Subtraction $x - $y
* Multiplication $x * $y
/ Division $x / $y
% Modulus $x % $y
** Exponentiation $x ** $y

PHP Assignment Operators


x = y

PHP Comparison Operators


Operator Name Example
== Equal $x == $y
=== Identical $x === $y
!= Not equal $x != $y
<> Not equal $x <> $y
!== Not identical $x !== $y
> Greater than $x > $y
< Less than $x < $y
>= Greater than or
equal to $x >= $y
<= Less than or
equal to $x <= $y

PHP Increment / Decrement Operators


++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one

-45-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM

PHP Logical Operators


Operator Name Example Result
and And $x and $y True if both $x and $y are true
or Or $x or $y True if either $x or $y is true
xor Xor $x xor $y True if either $x or $y is true, but not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true

PHP String Operators


. Concatenation $txt1 . $txt2
Concatenation of $txt1 and $txt2

.= Concatenation assignment $txt1 .= $txt2


Appends $txt2 to $txt1

PHP Array Operators


Operator Name Example Result
+ Union $x + $y Union of $x and $y
== Equality $x == $y Returns true if $x and $y have the same key/value pairs
=== Identity $x === $y Returns true if $x and $y have the same key/value pairs in
the same order and of the same types
!= Inequality $x != $y Returns true if $x is not equal to $y
<> Inequality $x <> $y Returns true if $x is not equal to $y
!== Non-identity$x !== $y Returns true if $x is not identical to $y

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

if ($t < "20") {


echo "Have a good day!";
}
?>

<?php
$t = 20;

if ($t < "20") {


echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
-46-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM

<?php
$t = 20;

if ($t < "10") {


echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>

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

foreach ($colors as $v) {


echo "$v <br>";
}
?>

 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] . ".";
?>

In PHP, there are three types of arrays:

Indexed arrays - Arrays with a numeric index


Associative arrays - Arrays with named keys
Multidimensional arrays - Arrays containing one or more arrays

PHP Indexed Arrays


$cars = array("Volvo", "BMW", "Toyota");
or
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";

<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>

Get The Length of an Array - The count() Function


<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>

PHP Associative Arrays


Associative arrays are arrays that use named keys that you assign to them.

There are two ways to create an associative array:

$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");


or:
-48-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM

$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";

 Looping through array 
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);

for($x = 0; $x < $arrlength; $x++) {


echo $cars[$x];
echo "<br>";
}
?>

Loop Through an Associative Array


To loop through and print all the values of an associative array, you could use a foreach
loop, like this:

Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

foreach($age as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>

 Sorting arrays 

PHP - Sort Functions For Arrays


In this chapter, we will go through the following PHP array sort functions:

sort() - sort arrays in ascending order


rsort() - sort arrays in descending order
asort() - sort associative arrays in ascending order,
according to the value
ksort() - sort associative arrays in ascending order,
according to the key
arsort() - sort associative arrays in descending order,
according to the value
krsort() - sort associative arrays in descending order,
according to the key

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

writeMsg(); // call the function


?>

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

echo "7 + 13 = " . sum(7, 13) . "<br>";


echo "2 + 4 = " . sum(2, 4);
?>

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.

The PHP superglobal variables are:

$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

$_SERVER is a PHP super global variable which holds


information about headers, paths, and script locations.

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

<form method="post" action="#">


Name: <input type="text" name="fname">
<input type="submit">
</form>

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

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">


Name: <input type="text" name="fname">
<input type="submit">
</form>

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

<a href="get.php?subject=PHP&web=cdac.com&name=okhla" >Test $GET</a>

</body>
</html>
$_FILES
$_ENV
$_COOKIE
$_SESSION

 Form processing with functions
<html>
<body>

<form action="get.php" method="get">


Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html>

<html>
<body>

Welcome <?php echo $_GET["name"]; ?><br>


Your email address is: <?php echo $_GET["email"]; ?>

</body>
</html>
 
 Validating data
empty() - checks if the variable contains any value or not.

Validating data = Determine if the data is in proper form.

Sanitizing data = Remove any illegal character from the data.

PHP filters are used to validate and sanitize external input.


PHP filter_var() Function
The filter_var() function filters a single variable with a specified filter. It takes two
pieces of data:

The variable you want to check


The type of check to use

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

if (filter_var($int, FILTER_VALIDATE_INT ) === true) {


echo("Integer is valid");
} else {
echo("Integer is not valid");
}
?>
  
Validate an IP Address
The following example uses the filter_var() function to check if the variable $ip is a
valid IP address:

Sanitize and Validate an Email Address


The following example uses the filter_var() function to first remove all illegal characters
from the $email variable, then check if it is a valid email address:
<?php
$email = "john.doe@example.com";

// Remove all illegal characters from email


$email = filter_var($email, FILTER_SANITIZE_EMAIL );

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

Sanitize and Validate a URL


The following example uses the filter_var() function to first remove all illegal characters
from a URL, then check if $url is a valid URL:
<?php
$url = "http://www.cdac.com";

// Remove all illegal characters from a url


$url = filter_var($url, FILTER_SANITIZE_URL );

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

Create Cookies With PHP


A cookie is created with the setcookie() function.
Syntax
setcookie(name, value, expire, path, domain, secure, httponly);

PHP Create/Retrieve a Cookie


$cookie_name = "user";
$cookie_value = "John";
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>

Modify a Cookie Value


<?php
$n = "user";
$v = "Alex Porter";
setcookie("user", "Alex", time() + (86400 * 30));
?>
<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>
-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>

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 users computer.

Session variables store user information to be used


multiple pages
(e.g. username, favorite color, etc).

By default, session variables last until the user


closes the browser.

Start a PHP Session


A session is started with the session_start() function.

Session variables are set with the PHP global


variable: $_SESSION.

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

get session variables

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

print all session values


<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

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

Destroy a PHP Session


To remove all global session variables and destroy the session, use session_unset() and
session_destroy():
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// remove all session variables
session_unset();
-57-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM

// destroy the session


session_destroy();
?>

</body>
</html>

 Login and User Identification  
How does it work? How does it know it's me?

Most sessions set a user-key on the user's computer that looks


something like this: 765487cf34ert8dede5a562e4f3a7e12.
Then, when a session is opened on another page, it scans the computer for a user-key.
If there is a match, it accesses that session, if not, it starts a new session.

 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

format Required. Specifies the format of the timestamp

timestamp Optional. Specifies a timestamp.


Default is the current date and time

Get a Simple Date


The required format parameter of the date()
function specifies how to format the date (or time).

Here are some characters that are commonly used for dates:

d - Represents the day of the month (01 to 31)


m - Represents a month (01 to 12)
Y - Represents a year (in four digits)
l (lowercase 'L') - Represents the day of the week
Other characters, like"/", ".", or "-" can also be
inserted between the characters to add additional formatting.

The example below formats today's date in three different ways:

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

Get a Simple Time


Here are some characters that are commonly used for times:

h - 12-hour format of an hour with leading zeros (01 to 12)


i - Minutes with leading zeros (00 to 59)
s - Seconds with leading zeros (00 to 59)
a - Lowercase Ante meridiem and Post meridiem (am or pm)
-58-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM

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

CREATE TABLE MyGuests (


id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50)); 

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

// sql to create table


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

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:

INSERT INTO table_name (column1, column2, column3,...)


-60-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM

VALUES (value1, value2, value3,...)

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

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


VALUES ('John', 'Doe', 'john@example.com')";

mysqli_query($conn, $sql);

mysqli_close($conn);
?>

SELECT * FROM table_name

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

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


$result = mysqli_query($conn, $sql);

if (mysqli_num_rows ($result) > 0) {


// output data of each row
while($row = mysqli_fetch_assoc ($result)) {
echo "id: " . $row["id"];
echo "<br>";
echo " - Name: " . $row["firstname"];

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

 Working with files , File permissions  and Reading and writing files 

PHP Open File - fopen()


<?php
$myfile = fopen("web.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);

?>

Modes Description
r Open a file for read only.
File pointer starts at the beginning of the file

w Open a file for write only.


Erases the contents of the file or creates a new file
if it doesn't exist. File pointer starts at the beginning of the file

a Open a file for write only.


The existing data in file is preserved.
File pointer starts at the end of the file.
Creates a new file if the file doesn't exist

x Creates a new file for write only.


Returns FALSE and an error if file already exists

r+ Open a file for read/write.


File pointer starts at the beginning of the file

w+ Open a file for read/write. Erases the contents of the file or


creates a new file if it doesn't exist.
File pointer starts at the beginning of the file

a+ Open a file for read/write. The existing data in file is preserved.


File pointer starts at the end of the file.
Creates a new file if the file doesn't exist

x+ Creates a new file for read/write.


Returns FALSE and an error if file already exists

PHP Read File - fread()


The fread() function reads from an open file.

PHP Close File - fclose()


The fclose() function is used to close an open file.

PHP 5 File Create/Write

PHP Create File - fopen()


The fopen() function is also used to create a file.
Maybe a little confusing, but in PHP, a file is created using the
same function used to open files.

-62-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM

$myfile = fopen("testfile.txt", "w")

PHP Write to File - fwrite()


The fwrite() function is used to write to a file.
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>

file upload using php

Create The HTML Form

<!DOCTYPE html>
<html>
<body>

<form action="upload.php" method="post" enctype="multipart/form-data" >


Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>

</body>
</html>

Make sure that the form uses method="post"

The form also needs the following

attribute: enctype="multipart/form-data".

It specifies which content-type to use when submitting the form

<?php

move_uploaded_file ($_FILES["fileToUpload"]["tmp_name"], "upload/a.jpg");


?>

 Working with CSV Files  and php mail

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

What is an XML Parser?


To read and update, create and manipulate an XML document, you will need an XML parser.

PHP SimpleXML - Read From File


The PHP simplexml_load_file() function is used to read XML data from a file.

Assume we have an XML file called "note.xml", that looks like this:

<?xml version="1.0" encoding="UTF-8"?>


<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend! </body>
</note>

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

PHP SimpleXML - Get Node/Attribute Values


<?php
$xml=simplexml_load_file("note.xml") or die("Error: Cannot create object");
echo $xml->to . "<br>";
echo $xml->from . "<br>";
echo $xml->heading . "<br>";
echo $xml->body;
?>
The output of the code above will be:

Tove
Jani
Reminder
Don't forget me this weekend!

Look at the following XML document fraction:

<?xml version="1.0" encoding="UTF-8"?>


<from>Jani</from>
he DOM sees the XML above as a tree structure:

Level 1: XML Document


Level 2: Root element: <from>
-64-
C:\Users\TechStratus\Desktop\cdac\Complete.html Thursday, November 5, 2015 10:02 AM

Level 3: Text element: "Jani"

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-

You might also like