PHP_BOOKs - WordPress.com

advertisement
SZABIST jstc Shaheed Benazirabad
Contents
Introducing HTML ..................................................................................................................................... 32
Creating HTML Document: ..................................................................................................................... 32
HTML Document Structure: .................................................................................................................... 33
HTML Tags and Elements: ....................................................................................................................... 33
The <html> Element:............................................................................................................................... 34
The <head> Element: .............................................................................................................................. 34
Example: ................................................................................................................................................ 34
The <title> Element: ................................................................................................................................ 35
Example: ................................................................................................................................................ 35
The <body> Element: .............................................................................................................................. 35
Example: ................................................................................................................................................ 35
Putting all together: .............................................................................................................................. 35
Adding Meta Tags to Your Documents: .................................................................................................. 36
Meta Tag Examples: .................................................................................................................................... 36
Specifying Keywords: .............................................................................................................................. 36
Document Description: ........................................................................................................................... 36
Document Revision date: ........................................................................................................................ 37
Document Refreshing: ............................................................................................................................ 37
Page Redirection: .................................................................................................................................... 37
Setting Cookies: ...................................................................................................................................... 37
Setting Author Name: ............................................................................................................................. 37
Core Attributes: .......................................................................................................................................... 38
The id Attribute: ...................................................................................................................................... 38
The title Attribute: .................................................................................................................................. 38
The class Attribute: ................................................................................................................................. 39
The style Attribute: ................................................................................................................................. 39
Whitespace and Flow:................................................................................................................................. 39
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 1
SZABIST jstc Shaheed Benazirabad
Create Headings - The <hn> Elements: ................................................................................................... 39
This is heading 1 .......................................................................................................................................... 40
This is heading 2 ...................................................................................................................................... 40
This is heading 3 .................................................................................................................................. 40
Create Paragraph - The <p> Element: ......................................................................................................... 40
Create Line Breaks - The <br /> Element: ............................................................................................... 40
Centring Content - The <center> Element: ............................................................................................. 41
Nonbreaking Spaces: .................................................................................................................................. 41
Presentational Tags:................................................................................................................................ 41
Bold Text - The <b> Element: .................................................................................................................. 41
Italic Text - The <i> Element: ...................................................................................................................... 42
Strong Text - The <strong> Element: .......................................................................................................... 42
Text Abbreviation - The <abbr> Element : .................................................................................................. 43
Quoting Text - The <blockquote> Element : ............................................................................................... 43
Short Quotations - The <q> Element : ........................................................................................................ 43
Citations - The <cite> Element : .................................................................................................................. 43
Multiline Comments: .................................................................................................................................. 44
Conditional Comments : ............................................................................................................................. 44
Using Comment tag .................................................................................................................................... 45
Commenting Scripts and Style Sheets: ....................................................................................................... 45
Font Size: ..................................................................................................................................................... 45
Font Face:.................................................................................................................................................... 46
Specify alternate font faces: ................................................................................................................... 47
Font Color: .................................................................................................................................................. 47
The <basefont> Element: ............................................................................................................................ 47
Example:...................................................................................................................................................... 47
Example of the <basefont> Element....................................................................................................... 48
Syntax:......................................................................................................................................................... 48
Attrubutes: .................................................................................................................................................. 48
Examples: .................................................................................................................................................... 49
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 2
SZABIST jstc Shaheed Benazirabad
Insert Image - The <img> Element: ............................................................................................................. 49
Image Attributes: ........................................................................................................................................ 49
A Simple Example:................................................................................................................................... 50
Linking Documents - The <a> Element: ...................................................................................................... 50
Anchor Attributes: ...................................................................................................................................... 50
A Simple Example:................................................................................................................................... 50
Example:.................................................................................................................................................. 50
Table Heading - The <th> Element: ............................................................................................................ 51
Table Cellpadding and Cellspacing:............................................................................................................. 52
Colspan and Rowspan Attributes:............................................................................................................... 52
Tables Backgrounds .................................................................................................................................... 53
Table height and width: .............................................................................................................................. 54
Using Table Caption: ................................................................................................................................... 54
Using a Header, Body, and Footer: ............................................................................................................. 55
Nested Tables: ............................................................................................................................................ 56
HTML Unordered Lists: ............................................................................................................................... 57
Movie List ................................................................................................................................................ 57
HTML Ordered Lists: ................................................................................................................................... 58
Movie List ................................................................................................................................................ 58
Movie List ................................................................................................................................................ 59
HTML Definition Lists: ................................................................................................................................. 59
Appropriate List Usage: .............................................................................................................................. 59
HTML Layout - Using Tables:....................................................................................................................... 60
This is Web Page Main title......................................................................................................................... 61
Multiuple Columns Layouts - Using Tables ................................................................................................. 61
HTML Layouts - Using DIV, SPAN ................................................................................................................ 62
HTML Color Coding Methods: ..................................................................................................................... 63
HTML Colors - Color Names: ....................................................................................................................... 63
W3C Standard 16 Colors: ........................................................................................................................ 63
HTML Forms - Text Input Controls: ............................................................................................................. 64
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 3
SZABIST jstc Shaheed Benazirabad
Single-line text input controls: .................................................................................................................... 64
Password input controls:: ........................................................................................................................... 65
Multiple-Line Text Input Controls: .............................................................................................................. 65
HTML Forms - Creating Button: .................................................................................................................. 66
HTML Forms - Checkboxes Control:............................................................................................................ 67
HTML Forms - Raido box Control: ............................................................................................................... 67
HTML Forms - Select box Control: .............................................................................................................. 68
HTML Forms - File Select Boxes: ................................................................................................................. 68
HTML Forms - Hidden Controls:.................................................................................................................. 68
HTML Forms - Submit and Reset Button: ................................................................................................... 69
Patterned & Transparent Backgrounds: ..................................................................................................... 69
HTML Uniform Resource Locators .............................................................................................................. 70
URL - Uniform Resource Locator ....................................................................................................... 70
Common URL Schemes ........................................................................................................................ 70
URL Encoding ....................................................................................................................................... 71
URL Encoding Examples ..................................................................................................................... 71
HTML Useful Character Entities ........................................................................................................ 71
CSS Basic.................................................................................................................................................. 73
CSS Introduction ......................................................................................................................................... 73
What is CSS? ......................................................................................................................................... 73
Styles Solved a Big Problem ................................................................................................................. 73
CSS Saves a Lot of Work! .................................................................................................................... 73
CSS Syntax ................................................................................................................................................... 73
CSS Example ......................................................................................................................................... 73
Example ................................................................................................................................................. 74
CSS Comments ...................................................................................................................................... 74
The id and class Selectors ..................................................................................................................... 74
The id Selector ....................................................................................................................................... 75
Example ................................................................................................................................................. 75
The class Selector .................................................................................................................................. 75
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 4
SZABIST jstc Shaheed Benazirabad
Example ................................................................................................................................................. 75
Three Ways to Insert CSS ........................................................................................................................ 75
External Style Sheet ................................................................................................................................ 75
Internal Style Sheet ................................................................................................................................. 76
Inline Styles ............................................................................................................................................. 76
Multiple Style Sheets .............................................................................................................................. 76
Multiple Styles Will Cascade into One .................................................................................................... 77
Cascading order .................................................................................................................................. 77
CSS Styling ............................................................................................................................................ 77
CSS Background .......................................................................................................................................... 77
Background Color................................................................................................................................. 77
Example ................................................................................................................................................. 77
Example ................................................................................................................................................... 78
Background Image ................................................................................................................................ 78
Example ................................................................................................................................................. 78
Example ................................................................................................................................................. 78
Background Image - Repeat Horizontally or Vertically ................................................................... 78
Example ................................................................................................................................................. 78
Example ................................................................................................................................................. 78
Background Image - Set position and no-repeat ................................................................................ 78
Example ................................................................................................................................................. 78
Example ................................................................................................................................................. 79
Background - Shorthand property ...................................................................................................... 79
Example ................................................................................................................................................. 79
CSS Text....................................................................................................................................................... 79
Text Color ................................................................................................................................................ 79
Example ................................................................................................................................................... 79
Text Alignment ...................................................................................................................................... 80
Example ................................................................................................................................................. 80
Text Decoration ..................................................................................................................................... 80
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 5
SZABIST jstc Shaheed Benazirabad
Example ................................................................................................................................................. 80
Example ................................................................................................................................................. 80
Text Transformation ............................................................................................................................ 80
Example ................................................................................................................................................. 80
Text Indentation .................................................................................................................................... 80
Example ................................................................................................................................................. 80
CSS Font ...................................................................................................................................................... 80
Font Family............................................................................................................................................ 80
Example ................................................................................................................................................. 81
Font Style ............................................................................................................................................... 81
Example ................................................................................................................................................. 81
Font Size................................................................................................................................................. 81
Set Font Size With Pixels ...................................................................................................................... 81
Example ................................................................................................................................................. 81
Set Font Size With Em .......................................................................................................................... 82
Example ................................................................................................................................................. 82
Use a Combination of Percent and Em ............................................................................................... 82
Example ................................................................................................................................................. 82
CSS Links...................................................................................................................................................... 82
Styling Links .......................................................................................................................................... 82
Example ................................................................................................................................................. 82
Common Link Styles............................................................................................................................. 83
Text Decoration ..................................................................................................................................... 83
Example ................................................................................................................................................. 83
Background Color................................................................................................................................. 83
Example ................................................................................................................................................. 83
CSS Lists....................................................................................................................................................... 83
List .......................................................................................................................................................... 83
Different List Item Markers................................................................................................................. 83
Example ................................................................................................................................................. 83
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 6
SZABIST jstc Shaheed Benazirabad
An Image as The List Item Marker ..................................................................................................... 84
Example ................................................................................................................................................. 84
Crossbrowser Solution.......................................................................................................................... 84
Example ................................................................................................................................................. 84
List - Shorthand property .................................................................................................................... 85
Example ................................................................................................................................................. 85
CSS Tables ................................................................................................................................................... 85
Table Borders ........................................................................................................................................ 85
Example ................................................................................................................................................. 85
Collapse Borders ................................................................................................................................... 86
Example ................................................................................................................................................. 86
Table Width and Height ....................................................................................................................... 86
Example ................................................................................................................................................. 86
Table Text Alignment ........................................................................................................................... 86
Example ................................................................................................................................................. 86
Example ................................................................................................................................................. 87
Table Padding........................................................................................................................................ 87
Example ................................................................................................................................................. 87
Table Color ............................................................................................................................................ 87
Example ................................................................................................................................................. 87
CSS Box Model...................................................................................................................................... 87
The CSS Box Model .............................................................................................................................. 87
Width and Height of an Element ......................................................................................................... 88
Example ................................................................................................................................................. 89
Browsers Compatibility Issue .............................................................................................................. 89
CSS Border................................................................................................................................................... 89
Border Style ........................................................................................................................................... 89
border-style values:............................................................................................................................... 89
Border Width ........................................................................................................................................ 89
Example ................................................................................................................................................. 90
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 7
SZABIST jstc Shaheed Benazirabad
Border Color.......................................................................................................................................... 90
Example ................................................................................................................................................. 90
Border - Individual sides ...................................................................................................................... 90
Example ................................................................................................................................................. 90
Example ................................................................................................................................................. 91
Border - Shorthand property ............................................................................................................... 91
Example ................................................................................................................................................. 91
CSS Outlines ................................................................................................................................................ 91
CSS Outline ........................................................................................................................................... 91
All CSS Outline Properties ....................................................................................................................... 92
CSS Margin .................................................................................................................................................. 93
Margin.................................................................................................................................................... 93
Possible Values ...................................................................................................................................... 93
Margin - Individual sides ..................................................................................................................... 93
Example ................................................................................................................................................. 93
Margin - Shorthand property .............................................................................................................. 93
Example ................................................................................................................................................. 93
CSS Padding................................................................................................................................................. 94
Padding .................................................................................................................................................. 94
Possible Values ...................................................................................................................................... 94
Padding - Individual sides .................................................................................................................... 94
Example ................................................................................................................................................. 94
Padding - Shorthand property ............................................................................................................. 94
Example ................................................................................................................................................. 94
CSS Grouping and Nesting Selectors........................................................................................................... 95
Grouping Selectors................................................................................................................................ 95
Example ................................................................................................................................................. 95
Nesting Selectors ................................................................................................................................... 96
Example ................................................................................................................................................. 96
CSS Display and Visibility ............................................................................................................................ 96
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 8
SZABIST jstc Shaheed Benazirabad
Hiding an Element - display:none or visibility:hidden ...................................................................... 96
Example ................................................................................................................................................. 96
CSS Display - Block and Inline Elements ........................................................................................... 96
Changing How an Element is Displayed ............................................................................................. 97
Example ................................................................................................................................................. 97
Example ................................................................................................................................................. 97
CSS Positioning ............................................................................................................................................ 97
Positioning ............................................................................................................................................. 97
Static Positioning................................................................................................................................... 97
Fixed Positioning ................................................................................................................................... 97
Example ................................................................................................................................................. 97
Relative Positioning .............................................................................................................................. 98
Example ................................................................................................................................................. 98
Example ................................................................................................................................................. 98
Absolute Positioning ............................................................................................................................. 98
Example ................................................................................................................................................. 98
Overlapping Elements .......................................................................................................................... 99
Example ................................................................................................................................................. 99
All CSS Positioning Properties ................................................................................................................. 99
What is CSS Float? ............................................................................................................................. 100
How Elements Float ............................................................................................................................ 100
Example ............................................................................................................................................... 100
Floating Elements Next to Each Other ............................................................................................. 101
Example ............................................................................................................................................... 101
Turning off Float - Using Clear ......................................................................................................... 101
Example ............................................................................................................................................... 101
All CSS Float Properties ......................................................................................................................... 101
CSS Horizontal Align .................................................................................................................................. 101
Aligning Block Elements .................................................................................................................... 101
Center Aligning Using the margin Property .......................................................................................... 102
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 9
SZABIST jstc Shaheed Benazirabad
Example ................................................................................................................................................. 102
Left and Right Aligning Using the position Property ...................................................................... 102
Example ............................................................................................................................................... 102
Crossbrowser Compatibility Issues ................................................................................................... 102
Example ............................................................................................................................................... 102
Left and Right Aligning Using the float Property ............................................................................ 103
Example ............................................................................................................................................... 103
Crossbrowser Compatibility Issues ................................................................................................... 103
Example ............................................................................................................................................... 103
CSS Pseudo-classes ................................................................................................................................... 104
Syntax ................................................................................................................................................... 104
Anchor Pseudo-classes ........................................................................................................................ 104
Example ............................................................................................................................................... 104
Pseudo-classes and CSS Classes ............................................................................................................ 104
CSS - The :first-child Pseudo-class......................................................................................................... 104
Match the first <p> element ................................................................................................................. 105
Example ................................................................................................................................................. 105
Match the first <i> element in all <p> elements ............................................................................... 105
Example ............................................................................................................................................... 105
Match all <i> elements in all first child <p> elements ..................................................................... 105
Example ............................................................................................................................................... 106
CSS - The :lang Pseudo-class ................................................................................................................. 106
Example ................................................................................................................................................. 106
All CSS Pseudo Classes/Elements .......................................................................................................... 106
CSS Pseudo-elements................................................................................................................................ 107
Syntax ................................................................................................................................................... 107
The :first-line Pseudo-element ........................................................................................................... 107
Example ............................................................................................................................................... 107
The :first-letter Pseudo-element ........................................................................................................ 108
Example ............................................................................................................................................... 108
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 10
SZABIST jstc Shaheed Benazirabad
Pseudo-elements and CSS Classes ..................................................................................................... 108
Multiple Pseudo-elements .................................................................................................................. 108
Example ............................................................................................................................................... 108
CSS - The :before Pseudo-element .................................................................................................... 109
Example ............................................................................................................................................... 109
CSS - The :after Pseudo-element ....................................................................................................... 109
Example ............................................................................................................................................... 109
All CSS Pseudo Classes/Elements .......................................................................................................... 109
Navigation Bars ................................................................................................................................... 110
Navigation Bar = List of Links .......................................................................................................... 110
Example ............................................................................................................................................... 110
Example ............................................................................................................................................... 110
Vertical Navigation Bar ...................................................................................................................... 110
Example ............................................................................................................................................... 110
Horizontal Navigation Bar ..................................................................................................................... 111
Inline List Items ..................................................................................................................................... 111
Example ................................................................................................................................................. 111
Floating List Items ................................................................................................................................. 111
Example ................................................................................................................................................. 111
Example ............................................................................................................................................... 112
CSS Image Opacity / Transparency ........................................................................................................... 113
Creating a Transparent Image .......................................................................................................... 113
Example 2 - Image Transparency - Hover Effect ............................................................................ 114
Example 3 - Text in Transparent Box ............................................................................................... 115
CSS Attribute Selectors ............................................................................................................................. 116
Style HTML Elements With Specific Attributes .............................................................................. 116
Attribute Selector ................................................................................................................................ 116
Example ............................................................................................................................................... 116
Attribute and Value Selector ............................................................................................................. 116
Example ............................................................................................................................................... 116
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 11
SZABIST jstc Shaheed Benazirabad
Attribute and Value Selector - Multiple Values ............................................................................... 116
Example ............................................................................................................................................... 116
Example ............................................................................................................................................... 117
Styling Forms ...................................................................................................................................... 117
Example ............................................................................................................................................... 117
CSS Selectors ......................................................................................................................................... 117
CSS3 Introduction ..................................................................................................................................... 120
CSS3 Modules...................................................................................................................................... 120
CSS3 Recommendation ...................................................................................................................... 120
CSS3 Borders ............................................................................................................................................. 120
CSS3 Borders ...................................................................................................................................... 120
CSS3 Rounded Corners ...................................................................................................................... 121
Example ............................................................................................................................................... 121
CSS3 Box Shadow ............................................................................................................................... 121
Example ............................................................................................................................................... 121
CSS3 Border Image ............................................................................................................................ 121
Example ............................................................................................................................................... 122
New Border Properties ......................................................................................................................... 122
CSS3 Backgrounds ..................................................................................................................................... 122
CSS3 Backgrounds.............................................................................................................................. 122
CSS3 The background-size Property ................................................................................................ 123
Example 1 ............................................................................................................................................ 123
Example 2 ............................................................................................................................................ 123
CSS3 The background-origin Property ............................................................................................ 123
Example ............................................................................................................................................... 124
CSS3 Multiple Background Images .................................................................................................. 124
Example ............................................................................................................................................... 124
New Background Properties ................................................................................................................. 124
CSS3 Text Effects ....................................................................................................................................... 124
CSS3 Text Effects................................................................................................................................ 124
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 12
SZABIST jstc Shaheed Benazirabad
CSS3 Text Shadow .............................................................................................................................. 125
Example ............................................................................................................................................... 125
CSS3 Word Wrapping ........................................................................................................................ 125
Example ............................................................................................................................................... 125
New Text Properties ............................................................................................................................. 125
CSS3 Fonts ................................................................................................................................................. 126
The CSS3 @font-face Rule ................................................................................................................. 126
Browser Support ................................................................................................................................. 126
Using The Font You Want ................................................................................................................. 126
Example ............................................................................................................................................... 127
Using Bold Text ................................................................................................................................... 127
Example ............................................................................................................................................... 127
CSS3 Font Descriptors ....................................................................................................................... 127
CSS3 2D Transforms .................................................................................................................................. 128
CSS3 Transforms ................................................................................................................................ 128
How Does it Work? ............................................................................................................................. 128
Browser Support ................................................................................................................................. 128
2D Transforms .................................................................................................................................... 129
Example ............................................................................................................................................... 129
The translate() Method ....................................................................................................................... 129
Example ............................................................................................................................................... 129
The rotate() Method ............................................................................................................................ 129
Example ............................................................................................................................................... 130
The scale() Method.............................................................................................................................. 130
Example ............................................................................................................................................... 130
The skew() Method ............................................................................................................................. 130
Example ............................................................................................................................................... 131
The matrix() Method .......................................................................................................................... 131
Example ............................................................................................................................................... 131
New Transform Properties .................................................................................................................... 131
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 13
SZABIST jstc Shaheed Benazirabad
2D Transform Methods ......................................................................................................................... 132
CSS3 3D Transforms .................................................................................................................................. 132
3D Transforms ....................................................................................................................................... 132
Browser Support ................................................................................................................................... 132
The rotateX() Method ........................................................................................................................... 132
Example ................................................................................................................................................. 133
The rotateY() Method ......................................................................................................................... 133
Example ............................................................................................................................................... 133
Transform Properties ............................................................................................................................ 133
3D Transform Methods ......................................................................................................................... 133
CSS3 Transitions ........................................................................................................................................ 134
CSS3 Transitions................................................................................................................................. 134
Browser Support ................................................................................................................................. 134
How does it work?............................................................................................................................... 134
Example ............................................................................................................................................... 135
Example ............................................................................................................................................... 135
Multiple changes ................................................................................................................................. 135
Example ............................................................................................................................................... 135
Transition Properties ............................................................................................................................ 135
Example ................................................................................................................................................. 136
Example ............................................................................................................................................... 136
CSS3 Animations ................................................................................................................................ 136
CSS3 @keyframes Rule ...................................................................................................................... 136
Browser Support ................................................................................................................................. 136
Example ............................................................................................................................................... 137
CSS3 animation ................................................................................................................................... 137
Example ............................................................................................................................................... 137
What are Animations in CSS3? ......................................................................................................... 137
Example ............................................................................................................................................... 138
Example ............................................................................................................................................... 138
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 14
SZABIST jstc Shaheed Benazirabad
CSS3 Animation Properties ................................................................................................................... 139
Example ................................................................................................................................................. 139
Example ............................................................................................................................................... 140
CSS3 Multiple Columns ............................................................................................................................. 140
CSS3 Multiple Columns ..................................................................................................................... 140
CSS3 Create Multiple Columns ......................................................................................................... 140
Example ............................................................................................................................................... 140
CSS3 Specify the Gap Between Columns ......................................................................................... 140
Example ............................................................................................................................................... 141
CSS3 Column Rules ............................................................................................................................ 141
Example ............................................................................................................................................... 141
New Multiple Columns Properties ........................................................................................................ 141
CSS3 User Interface................................................................................................................................... 141
CSS3 Resizing ...................................................................................................................................... 142
Example ............................................................................................................................................... 142
CSS3 Box Sizing .................................................................................................................................. 142
Example ............................................................................................................................................... 142
CSS3 Outline Offset ............................................................................................................................ 142
Example ............................................................................................................................................... 143
New User-interface Properties ............................................................................................................. 143
Measurement Values .......................................................................................................................... 143
What is JavaScript ? ............................................................................................................................... 145
Advantages of JavaScript: ......................................................................................................................... 145
Limitations with JavaScript: ...................................................................................................................... 145
Your First JavaScript Script: ................................................................................................................ 146
Whitespace and Line Breaks: .................................................................................................................... 146
Semicolons are Optional: ....................................................................................................................... 146
Case Sensitivity: ........................................................................................................................................ 147
Comments in JavaScript: ........................................................................................................................... 147
Example:................................................................................................................................................ 147
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 15
SZABIST jstc Shaheed Benazirabad
JavaScript in Internet Explorer: ........................................................................................................... 147
JavaScript in Firefox: ............................................................................................................................. 147
JavaScript in Opera: .............................................................................................................................. 148
Warning for Non-JavaScript Browsers: ............................................................................................... 148
JavaScript in <head>...</head> section: ............................................................................................... 149
JavaScript in <body>...</body> section: ............................................................................................... 149
JavaScript in <body> and <head> sections: .......................................................................................... 150
JavaScript in External File : .................................................................................................................... 150
JavaScript DataTypes: ........................................................................................................................... 151
JavaScript Variables: ............................................................................................................................. 151
Declaring (Creating) JavaScript Variables ............................................................................................. 152
Example ................................................................................................................................................. 152
JavaScript Variable Scope: .................................................................................................................... 152
JavaScript Variable Names: .................................................................................................................. 153
JavaScript Reserved Words: ................................................................................................................. 153
JavaScript Data Types............................................................................................................................ 154
String, Number, Boolean, Array, Object, Null, Undefined ........................................................................ 154
JavaScript Has Dynamic Types .............................................................................................................. 154
Example ................................................................................................................................................. 154
JavaScript Strings .................................................................................................................................. 154
Example ................................................................................................................................................. 154
Example ................................................................................................................................................. 154
JavaScript Numbers............................................................................................................................... 154
Example ................................................................................................................................................. 154
Example ................................................................................................................................................. 154
JavaScript Booleans............................................................................................................................... 154
JavaScript Arrays ................................................................................................................................... 154
Example ................................................................................................................................................. 155
JavaScript Objects ................................................................................................................................. 155
Example ................................................................................................................................................. 155
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 16
SZABIST jstc Shaheed Benazirabad
Undefined and Null ............................................................................................................................... 155
Example ................................................................................................................................................. 155
Declaring Variable Types....................................................................................................................... 155
JavaScript Objects .................................................................................................................................. 156
Properties and Methods ....................................................................................................................... 156
A Real Life Object. A Car: ...................................................................................................................... 156
Properties:............................................................................................................................................. 156
Methods: ............................................................................................................................................... 156
Objects in JavaScript: ............................................................................................................................ 156
Properties:............................................................................................................................................. 156
Methods: ............................................................................................................................................... 156
Creating JavaScript Objects................................................................................................................... 157
Example ................................................................................................................................................. 157
Accessing Object Properties ................................................................................................................. 157
Accessing Object Methods .................................................................................................................... 157
What is an operator? ................................................................................................................................ 158
The Arithmatic Operators: ........................................................................................................................ 158
The Comparison Operators:...................................................................................................................... 158
The Logical Operators: .............................................................................................................................. 159
The Bitwise Operators: ............................................................................................................................. 159
The Assignment Operators: ...................................................................................................................... 160
Miscellaneous Operator ........................................................................................................................... 161
The Conditional Operator (? :) .............................................................................................................. 161
The typeof Operator ............................................................................................................................. 161
JavaScript Functions.................................................................................................................................. 162
JavaScript Function Syntax ............................................................................................................... 162
Calling a Function with Arguments .................................................................................................. 162
Example ............................................................................................................................................... 162
Example ............................................................................................................................................... 163
Functions With a Return Value ............................................................................................................. 163
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 17
SZABIST jstc Shaheed Benazirabad
Syntax ................................................................................................................................................ 163
Example ................................................................................................................................................. 163
Local JavaScript Variables ................................................................................................................ 164
Global JavaScript Variables .............................................................................................................. 164
The Lifetime of JavaScript Variables ............................................................................................... 164
Assigning Values to Undeclared JavaScript Variables.................................................................... 164
Conditional Statements ........................................................................................................................ 164
If Statement .......................................................................................................................................... 165
Syntax ................................................................................................................................................ 165
Example ................................................................................................................................................. 165
If...else Statement ................................................................................................................................. 165
Syntax ................................................................................................................................................ 165
Example ................................................................................................................................................. 165
If...else if...else Statement .................................................................................................................... 166
Syntax ................................................................................................................................................ 166
Example ................................................................................................................................................. 166
The JavaScript Switch Statement .......................................................................................................... 166
Syntax ................................................................................................................................................ 167
Example ................................................................................................................................................. 167
The default Keyword........................................................................................................................... 168
Example ............................................................................................................................................... 168
JavaScript Loops................................................................................................................................. 168
Instead of writing: ............................................................................................................................... 168
You can write: ..................................................................................................................................... 168
Different Kinds of Loops .................................................................................................................... 168
The For Loop ....................................................................................................................................... 169
Example ............................................................................................................................................... 169
Statement 1 .......................................................................................................................................... 169
Example: .............................................................................................................................................. 169
Example: .............................................................................................................................................. 169
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 18
SZABIST jstc Shaheed Benazirabad
Statement 2 .......................................................................................................................................... 170
Statement 3 .......................................................................................................................................... 170
Example: .............................................................................................................................................. 170
The For/In Loop .................................................................................................................................. 170
Example ............................................................................................................................................... 170
The While Loop ..................................................................................................................................... 170
Syntax ................................................................................................................................................ 170
Example ............................................................................................................................................. 171
Example ................................................................................................................................................. 171
The Do/While Loop ............................................................................................................................... 171
Syntax ................................................................................................................................................ 171
Example ............................................................................................................................................. 171
Example ................................................................................................................................................. 171
Comparing For and While ................................................................................................................. 171
Example ............................................................................................................................................... 171
Example ............................................................................................................................................... 172
The Break Statement .......................................................................................................................... 172
Example ............................................................................................................................................... 172
The Continue Statement ..................................................................................................................... 172
Example ............................................................................................................................................... 172
JavaScript Labels ................................................................................................................................ 173
Example ............................................................................................................................................... 173
JavaScript Errors - Throw and Try to Catch .................................................... Error! Bookmark not defined.
Errors Will Happen!............................................................................................................................... 173
JavaScript Throws Errors ....................................................................................................................... 174
JavaScript try and catch ........................................................................................................................ 174
Syntax ................................................................................................................................................ 174
Examples ............................................................................................................................................... 174
Example ................................................................................................................................................. 174
The Throw Statement ........................................................................................................................... 175
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 19
SZABIST jstc Shaheed Benazirabad
Syntax ................................................................................................................................................ 175
Example ................................................................................................................................................. 175
Example ................................................................................................................................................. 175
JavaScript Form Validation............................................................................................................... 176
Required Fields ................................................................................................................................... 176
Example ............................................................................................................................................... 176
E-mail Validation ................................................................................................................................ 176
Example ............................................................................................................................................... 177
JS HTML DOM .................................................................................................................................. 177
The HTML DOM (Document Object Model) .................................................................................. 177
The HTML DOM Tree ....................................................................................................................... 177
Finding HTML Elements ................................................................................................................... 178
Finding HTML Elements by Id ......................................................................................................... 178
Example ............................................................................................................................................... 178
Finding HTML Elements by Tag Name ........................................................................................... 178
Example ............................................................................................................................................... 178
HTML DOM Tutorial ........................................................................................................................ 178
Changing the HTML Output Stream................................................................................................ 178
Example ............................................................................................................................................... 178
Changing HTML Content .................................................................................................................. 179
Example ............................................................................................................................................... 179
Example ............................................................................................................................................... 179
Changing an HTML Attribute........................................................................................................... 180
Example ............................................................................................................................................... 180
Changing HTML Style ....................................................................................................................... 180

Example ....................................................................................................................................... 180
Example ............................................................................................................................................... 181
Example ............................................................................................................................................... 181
Reacting to Events............................................................................................................................... 181
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 20
SZABIST jstc Shaheed Benazirabad
Example ............................................................................................................................................... 182
Example ............................................................................................................................................... 182
HTML Event Attributes ..................................................................................................................... 182
Example ............................................................................................................................................... 182
Assign Events Using the HTML DOM .............................................................................................. 182
Example ............................................................................................................................................... 182
The onload and onunload Events ...................................................................................................... 183
Example ............................................................................................................................................... 183
The onchange Event............................................................................................................................ 183
Example ............................................................................................................................................... 183
The onmouseover and onmouseout Events ....................................................................................... 183
The onmousedown, onmouseup and onclick Events ........................................................................ 183
Creating New HTML Elements ......................................................................................................... 183
Example ............................................................................................................................................... 183
Example Explained ............................................................................................................................. 183
Removing Existing HTML Elements ................................................................................................ 184
Example ............................................................................................................................................... 184
Example Explained ............................................................................................................................. 184
HTML DOM Tutorial ........................................................................................................................ 185
Creating JavaScript Objects .............................................................................................................. 185
JS Objects ............................................................................................................................................ 186
JavaScript toExponential() Method .......................................................................................................... 186
Syntax ................................................................................................................................................... 186
Example ............................................................................................................................................... 186
JavaScript toFixed() Method ..................................................................................................................... 186
JavaScript toPrecision() Method ............................................................................................................... 186
Example ............................................................................................................................................... 186
JavaScript toString() Method .................................................................................................................... 187
Example ............................................................................................................................................... 187
JavaScript valueOf() Method .................................................................................................................... 187
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 21
SZABIST jstc Shaheed Benazirabad
Example ............................................................................................................................................... 187
JavaScript Strings Methods ............................................................................................................... 187
String Length....................................................................................................................................... 187
var txt="Hello World!"; document.write(txt.length); var txt="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.write(txt.length); ................................................................................................................. 187
Finding a String in a String................................................................................................................ 187
Example ............................................................................................................................................... 187
Matching Content ............................................................................................................................... 187
Example ............................................................................................................................................... 187
Replacing Content............................................................................................................................... 187
Example ............................................................................................................................................... 188
Upper Case and Lower Case .............................................................................................................. 188
Example ............................................................................................................................................... 188
Convert a String to an Array ............................................................................................................. 188
Example ............................................................................................................................................... 188
Math Object......................................................................................................................................... 188
Mathematical Methods ....................................................................................................................... 188
What is an Array?............................................................................................................................... 189
Create an Array .................................................................................................................................. 189
Access an Array................................................................................................................................... 189
What is RegExp? ................................................................................................................................. 190
Syntax ................................................................................................................................................... 190
RegExp Modifiers ............................................................................................................................... 190
Example 1 ............................................................................................................................................ 190
Example 2 ............................................................................................................................................ 191
Example 3 ............................................................................................................................................ 191
test() ...................................................................................................................................................... 192
Example ............................................................................................................................................... 192
exec() .................................................................................................................................................... 192
Example 1 ............................................................................................................................................ 192
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 22
SZABIST jstc Shaheed Benazirabad
Regular Expressions and RegExp Object ................................................................................................... 193
Syntax:....................................................................................................................................................... 193
Brackets:................................................................................................................................................ 193
Quantifiers: ....................................................................................................................................... 194
Examples: .......................................................................................................................................... 194
Literal characters: ............................................................................................................................. 194
Metacharacters ................................................................................................................................. 195
Modifiers ........................................................................................................................................... 195
RegExp Properties: .................................................................................................................................... 196
RegExp Methods: ...................................................................................................................................... 196
What is an Event ? .................................................................................................................................... 196
onclick Event Type: ................................................................................................................................... 197
Example:................................................................................................................................................ 197
onsubmit event type: ................................................................................................................................ 197
Example:................................................................................................................................................ 197
onmouseover and onmouseout: .............................................................................................................. 198
Example:................................................................................................................................................ 198
HTML 4 Standard Events ........................................................................................................................... 198
What is page redirection ? .................................................................................................................... 199
How Page Re-direction works ? ............................................................................................................ 199
Example 1: ............................................................................................................................................. 199
Example 2: ............................................................................................................................................. 200
Example 3: ............................................................................................................................................. 200
JavaScript - Dialog Boxes........................................................................................................................... 201
Alert Dialog Box: ....................................................................................................................................... 201
Confirmation Dialog Box: .......................................................................................................................... 201
Prompt Dialog Box: ................................................................................................................................... 202
JavaScript - Void Keyword......................................................................................................................... 202
Example 1: ............................................................................................................................................. 202
Example 2: ............................................................................................................................................. 203
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 23
SZABIST jstc Shaheed Benazirabad
Example 3: ............................................................................................................................................. 203
Javascript - Page Printing .......................................................................................................................... 204
How to print a page: ................................................................................................................................. 204
JavaScript - Errors & Exceptions Handling ................................................................................................ 204
Syntax errors: ............................................................................................................................................ 204
Runtime errors: ......................................................................................................................................... 205
Logical errors: ........................................................................................................................................... 205
The try...catch...finally Statement: ........................................................................................................... 205
Examples: .............................................................................................................................................. 206
The throw Statement: ............................................................................................................................... 207
The onerror() Method ............................................................................................................................... 208
JavaScript - Form Validation ..................................................................................................................... 209
Basic Form Validation: .............................................................................................................................. 211
Data Format Validation: ............................................................................................................................ 211
PHP Introduction....................................................................................................................................... 213
Common uses of PHP: ........................................................................................................................ 213
Characteristics of PHP ....................................................................................................................... 213
"Hello World" Script in PHP: ........................................................................................................... 213
PHP Environment Setup............................................................................................................................ 214
PHP Parser Installation:......................................................................................................................... 214
Apache Configuration: .......................................................................................................................... 215
PHP.INI File Configuration:.................................................................................................................... 215
Windows IIS Configuration: .................................................................................................................. 215
PHP Syntax Overview ................................................................................................................................ 215
Escaping to PHP: ................................................................................................................................... 215
Canonical PHP tags:........................................................................................................................... 215
Short-open (SGML-style) tags: .......................................................................................................... 215
ASP-style tags: ................................................................................................................................... 215
HTML script tags: .............................................................................................................................. 216
Commenting PHP Code: ........................................................................................................................ 216
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 24
SZABIST jstc Shaheed Benazirabad
PHP is whitespace insensitive: .............................................................................................................. 217
PHP is case sensitive: ............................................................................................................................ 217
Statements are expressions terminated by semicolons: ...................................................................... 217
Expressions are combinations of tokens: ............................................................................................. 217
Braces make blocks: .............................................................................................................................. 217
Running PHP Script from Command Prompt: ....................................................................................... 218
PHP Variable Types ................................................................................................................................... 218
Integers: ................................................................................................................................................ 219
Doubles: ................................................................................................................................................ 219
Boolean: ................................................................................................................................................ 219
Interpreting other types as Booleans: .............................................................................................. 219
NULL: ..................................................................................................................................................... 220
Strings: .................................................................................................................................................. 220
Here Document: ................................................................................................................................ 221
Variable Scope: ..................................................................................................................................... 222
Variable Naming:................................................................................................................................... 222
PHP Constants ........................................................................................................................................... 222
constant() function: ............................................................................................................................. 222
constant() example: ............................................................................................................................. 222
Differences between constants and variables are:............................................................................ 222
Valid and invalid constant names: .................................................................................................... 223
PHP Magic constants:......................................................................................................................... 223
PHP Operator Types .................................................................................................................................. 224
Arithmatic Operators: ........................................................................................................................... 224
Comparison Operators:......................................................................................................................... 224
Logical Operators: ................................................................................................................................. 225
Assignment Operators: ......................................................................................................................... 226
Conditional Operator ............................................................................................................................ 226
Operators Categories: ........................................................................................................................... 227
Precedence of PHP Operators: ............................................................................................................. 227
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 25
SZABIST jstc Shaheed Benazirabad
PHP Decision Making ................................................................................................................................ 227
The If...Else Statement .......................................................................................................................... 228
Syntax ................................................................................................................................................ 228
Example ............................................................................................................................................. 228
The ElseIf Statement ............................................................................................................................. 229
Syntax ................................................................................................................................................ 229
Example ............................................................................................................................................. 229
The Switch Statement ........................................................................................................................... 229
Syntax ................................................................................................................................................ 229
Example ............................................................................................................................................. 229
PHP Loop Types......................................................................................................................................... 230
The for loop statement ............................................................................................................................. 230
Syntax .................................................................................................................................................... 231
Example ................................................................................................................................................. 231
The while loop statement ......................................................................................................................... 231
Syntax .................................................................................................................................................... 231
Example ................................................................................................................................................. 231
The do...while loop statement .................................................................................................................. 232
Syntax .................................................................................................................................................... 232
Example ................................................................................................................................................. 232
The foreach loop statement ..................................................................................................................... 233
Syntax .................................................................................................................................................... 233
Example ................................................................................................................................................. 233
The break statement................................................................................................................................. 233
Example ................................................................................................................................................. 233
The continue statement............................................................................................................................ 234
Example ................................................................................................................................................. 234
PHP Arrays ................................................................................................................................................ 234
Numeric Array ....................................................................................................................................... 235
Example ............................................................................................................................................. 235
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 26
SZABIST jstc Shaheed Benazirabad
Associative Arrays ................................................................................................................................. 236
Example ............................................................................................................................................. 236
Multidimensional Arrays ....................................................................................................................... 236
Example ................................................................................................................................................. 237
PHP Strings ................................................................................................................................................ 237
String Concatenation Operator............................................................................................................. 238
Using the strlen() function .................................................................................................................... 239
Using the strpos() function ................................................................................................................... 239
PHP Web Concepts ................................................................................................................................... 239
Identifying Browser & Platform ............................................................................................................ 239
Display Images Randomly ..................................................................................................................... 240
Using HTML Forms ................................................................................................................................ 241
Browser Redirection ............................................................................................................................. 241
Displaying "File Download" Dialog Box ................................................................................................. 242
PHP GET and POST Methods..................................................................................................................... 243
The GET Method ................................................................................................................................ 243
The POST Method .............................................................................................................................. 243
The $_REQUEST variable ................................................................................................................. 244
PHP File Inclusion ...................................................................................................................................... 245
The include() Function .......................................................................................................................... 245
The require() Function .......................................................................................................................... 245
PHP Files & I/O .......................................................................................................................................... 246
Opening and Closing Files ..................................................................................................................... 246
Reading a file......................................................................................................................................... 247
Writing a file.......................................................................................................................................... 248
PHP Functions ........................................................................................................................................... 249
Creating PHP Function: ......................................................................................................................... 249
PHP Functions with Parameters: .......................................................................................................... 250
Passing Arguments by Reference: ........................................................................................................ 250
PHP Functions retruning value: ............................................................................................................ 251
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 27
SZABIST jstc Shaheed Benazirabad
Setting Default Values for Function Parameters: ................................................................................. 252
Dynamic Function Calls: ........................................................................................................................ 252
PHP Cookies .............................................................................................................................................. 253
The Anatomy of a Cookie: ................................................................................................................. 253
Setting Cookies with PHP: ................................................................................................................. 254
Accessing Cookies with PHP .............................................................................................................. 254
Deleting Cookie with PHP .................................................................................................................. 255
PHP Sessions ............................................................................................................................................. 255
Starting a PHP Session: ...................................................................................................................... 256
Destroying a PHP Session: ................................................................................................................. 257
Turning on Auto Session: ................................................................................................................... 257
Sessions without cookies: .................................................................................................................... 257
PHP - Sending Emails................................................................................................................................. 258
Sending plain text email: .................................................................................................................... 258
Example: .............................................................................................................................................. 259
Sending HTML email: ........................................................................................................................ 259
Example: .............................................................................................................................................. 259
Sending attachments with email: ....................................................................................................... 260
PHP File Uploading .................................................................................................................................... 262
Creating an upload form: ................................................................................................................... 262
Creating an upload script: ................................................................................................................. 263
PHP File Handling ...................................................................................................................................... 264
Opening a File ....................................................................................................................................... 264
Example ............................................................................................................................................. 264
Closing a File ......................................................................................................................................... 265
Check End-of-file ................................................................................................................................... 265
Reading a File Line by Line .................................................................................................................... 265
Example ............................................................................................................................................. 265
Reading a File Character by Character .................................................................................................. 265
Example ............................................................................................................................................. 265
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 28
SZABIST jstc Shaheed Benazirabad
PHP - Coding Standard .............................................................................................................................. 266
PHP Date and Time ................................................................................................................................... 267
Getting the Time Stamp with time(): .................................................................................................... 267
Converting a Time Stamp with getdate(): ............................................................................................. 268
Example:................................................................................................................................................ 268
Converting a Time Stamp with date(): .................................................................................................. 269
Example:................................................................................................................................................ 270
PHP and MySQL Tutorial ........................................................................................................................... 271
Object Oriented Programming in PHP ...................................................................................................... 271
Object Oriented Concepts: ................................................................................................................... 271
Defining PHP Classes: ............................................................................................................................ 272
Example:............................................................................................................................................ 272
Creating Objects in PHP ........................................................................................................................ 272
Calling Member Functions .................................................................................................................... 273
Constructor Functions:.......................................................................................................................... 273
Destructor: ............................................................................................................................................ 274
Inheritance: ........................................................................................................................................... 274
Function Overriding: ............................................................................................................................. 275
Public Members: ................................................................................................................................... 275
Private members: .................................................................................................................................. 275
Protected members: ............................................................................................................................. 276
Interfaces: ............................................................................................................................................. 276
Constants: ............................................................................................................................................. 276
Abstract Classes: ................................................................................................................................... 277
Static Keyword: ..................................................................................................................................... 277
Final Keyword:....................................................................................................................................... 277
Calling parent constructors: .................................................................................................................. 278
PHP Database ...................................................................................................................................... 280
PHP MySQL Introduction .......................................................................................................................... 280
What is MySQL? .................................................................................................................................... 280
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 29
SZABIST jstc Shaheed Benazirabad
PHP + MySQL......................................................................................................................................... 280
Queries .................................................................................................................................................. 280
Download MySQL Database.................................................................................................................. 280
Facts About MySQL Database ............................................................................................................... 281
PHP Connect to the MySQL Server ........................................................................................................... 281
Open a Connection to the MySQL Server ............................................................................................. 281
Syntax ................................................................................................................................................ 281
Close a Connection................................................................................................................................ 281
PHP Create Database and Tables .............................................................................................................. 282
Create a Database ................................................................................................................................. 282
Create a Table ....................................................................................................................................... 282
Primary Keys and Auto Increment Fields .............................................................................................. 283
PHP MySQL Insert Into .............................................................................................................................. 284
Insert Data Into a Database Table......................................................................................................... 284
Syntax ................................................................................................................................................ 284
Example ............................................................................................................................................. 284
Insert Data From a Form Into a Database............................................................................................. 285
PHP MySQL Select ..................................................................................................................................... 286
Select Data From a Database Table ...................................................................................................... 286
Syntax ................................................................................................................................................ 286
Example ............................................................................................................................................. 286
Display the Result in an HTML Table..................................................................................................... 287
PHP MySQL The Where Clause ................................................................................................................. 287
The WHERE clause ................................................................................................................................ 287
Syntax ................................................................................................................................................ 288
Example ............................................................................................................................................. 288
PHP MySQL Order By Keyword ................................................................................................................. 288
The ORDER BY Keyword ........................................................................................................................ 288
Syntax ................................................................................................................................................ 288
Example ............................................................................................................................................. 288
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 30
SZABIST jstc Shaheed Benazirabad
PHP MySQL Update................................................................................................................................... 289
Update Data In a Database ................................................................................................................... 289
Syntax ................................................................................................................................................ 289
Example ............................................................................................................................................. 289
PHP MySQL Delete .................................................................................................................................... 290
Delete Data In a Database .................................................................................................................... 290
Syntax ................................................................................................................................................ 290
Example ............................................................................................................................................. 290
PHP Database ODBC ................................................................................................................................. 291
Create an ODBC Connection ................................................................................................................. 291
Connecting to an ODBC......................................................................................................................... 291
Example ............................................................................................................................................. 291
Retrieving Records ................................................................................................................................ 291
Retrieving Fields from a Record ............................................................................................................ 292
Closing an ODBC Connection ................................................................................................................ 292
An ODBC Example ................................................................................................................................. 292
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 31
SZABIST jstc Shaheed Benazirabad
Introducing HTML
HTML stands for Hypertext Markup Language, and it is the most widely used language to write
Web Pages. As its name suggests, HTML is a markup language.
 Hypertext refers to the way in which Web pages (HTML documents) are linked together.
When you click a link in a Web page, you are using hypertext.
 Markup Language describes how HTML works. With a markup language, you simply
"mark up" a text document with tags that tell a Web browser how to structure it to
display.
Originally, HTML was developed with the intent of defining the structure of documents like
headings, paragraphs, lists, and so forth to facilitate the sharing of scientific information between
researchers.
All you need to do to use HTML is to learn what type of markup to use to get the results you
want.
Creating HTML Document:
Creating an HTML document is easy. To begin coding HTML you need only two things: a
simple-text editor and a web browser.
 Open Notepad or another text editor.
 At the top of the page type <html>.
 On the next line, indent five spaces and now add the opening header tag: <head>.
 On the next line, indent ten spaces and type <title> </title>.
 Go to the next line, indent five spaces from the margin and insert the closing header tag:
</head>.
 Five spaces in from the margin on the next line, type<body>.
 Now drop down another line and type the closing tag right below its mate: </body>.
 Finally, go to the next line and type </html>.
 In the File menu, choose Save As.
 In the Save as Type option box, choose All Files.
 Name the file template.htm.
 Click Save.
You have basic HTML document now, to see some result put the following code in title and
body tags.
<html>
<head>
<title>This is document title</title>
</head>
<body>
<h1>This is a heading</h1>
<p>Document description goes here.....</p>
</body>
</html>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 32
SZABIST jstc Shaheed Benazirabad
Now you have created one HTML page and you can use a Web Browser to open this HTML file
to see the result. Hope you understood that Web Pages are nothing but they are simple HTML
files with some content which can be rendered using Web Browsers.
Here <html>, <head>,...<p>, <h1> etc. are called HTML tags. HTML tags are building blocks of
an HTML document nd we will learn all the HTML tags in subsequent chapters.
NOTE: One HTML file can have extension as .htm or .html. So you can use either of them
based on your comfort.
HTML Document Structure:
An HTML document starts and ends with <html> and >/html> tags. These tags tell the browser
that the entire document is composed in HTML. Inside these two tags, the document is split into
two sections:
 The <head>...</head> elements, which contain information about the document such as
title of the document, author of the document etc. Information inside this tag does not
display outside.
 The <body>...</body> elements, which contain the real content of the document that you
see on your screen.
HTML Tags and Elements:
HTML language is a markup language and we use many tags to markup text. In the above
example you have seen <html>, <body> etc. are called HTML tags or HTML elements.
Every tag consists of a tag name, sometimes followed by an optional list of tag attributes , all
placed between opening and closing brackets (< and >). The simplest tag is nothing more than a
name appropriately enclosed in brackets, such as <head> and <i>. More complicated tags contain
one or more attributes , which specify or modify the behavior of the tag.
According to the HTML standard, tag and attribute names are not case-sensitive. There's no
difference in effect between <head>, <Head>, <HEAD>, or even <HeaD>; they are all
equivalent. But with XHTML, case is important: all current standard tag and attribute names are
in lowercase.
The basic structure for all HTML documents is simple and should include the following
minimum elements or tags:
 <html> - The main container for HTML pages
 <head> - The container for page header information
 <title> - The title of the page
 <body> - The main body of the page
Remember that before an opening <html> tag, an XHTML document can contain the optional
XML declaration, and it should always contain a DOCTYPE declaration indicating which
version of XHTML it uses.
Now we will explain each of these tags one by one. In this tutorial you will find the terms
element and tag are used interchangeably.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 33
SZABIST jstc Shaheed Benazirabad
The <html> Element:
The <html> element is the containing element for the whole HTML document. Each HTML
document should have one <html> and each document should end with a closing </html> tag.
Following two elements appear as direct children of an <html> element:
 <head>
 <body>
As such, start and end HTML tags enclose all the other HTML tags you use to describe the Web
page.
The <head> Element:
The <head> element is just a container for all other header elements. It should be the first thing
to appear after the opening <html> tag.
Each <head> element should contain a <title> element indicating the title of the document,
although it may also contain any combination of the following elements, in any order:
 The <base> tag is used to create a "base" url for all links on the page. Check HTML Base
tag.
 The <object> tag is designed to include images, JavaScript objects, Flash animations,
MP3 files, QuickTime movies and other components of a page. Check HTML Object tag.
 The <link> tag is used to link to an external file, such as a style sheet or JavaScript file.
Check HTML Link tag.
 The <style> tag is used to include CSS rules inside the document. Check HTML Style
tag.
 The <script> tag is used to include JAVAScript or VBScript inside the document. Check
HTML Script tag.
 The <meta> tag includes information about the document such as keywords and a
description, which are particularly helpful for search applications. Check HTML Meta
tag.
Example:
Following is the example of head tag.
<head>
<title>HTML Basic tags</title>
<meta name="Keywords" content="HTML, Web Pages" />
<meta name="description" content="HTML Basic Tags" />
<base href="http://www.tutorialspoint.com" />
<link rel="stylesheet" type="text/css" href="tp.css" />
<script type="text/javascript">
_uacct = "UA-232293";
urchinTracker();
</script>
</head>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 34
SZABIST jstc Shaheed Benazirabad
The <title> Element:
You should specify a title for every page that you write inside the <title> element. This element
is a child of the <head> element). It is used in several ways:
 It displays at the very top of a browser window.
 It is used as the default name for a bookmark in browsers such as IE and Netscape.
 Its is used by search engines that use its content to help index pages.
Therefore it is important to use a title that really describes the content of your site. The <title>
element should contain only the text for the title and it may not contain any other elements.
Example:
Here is the example of using title tag.
<head>
<title>HTML Basic tags</title>
</head>
The <body> Element:
The <body> element appears after the <head> element and contains the part of the Web page
that you actually see in the main browser window, which is sometimes referred to as body
content.
A <body> element may contain anything from a couple of paragraphs under a heading to more
complicated layouts containing forms and tables.
Most of what you will be learning in this and the following five chapters will be written between
the opening <body> tag and closing </body> tag.
Example:
Here is the example of using body tag.
<body>
<p>This is a paragraph tag.</p>
</body>
Putting all together:
Now if we will put all these tags together, it will constitute a complete HTML document as
follows:
<html>
<head>
<title>HTML Basic tags</title>
<meta name="Keywords" content="HTML, Web Pages" />
<meta name="description" content="HTML Basic Tags" />
<base href="http://www.tutorialspoint.com" />
<link rel="stylesheet" type="text/css" href="tp.css" />
<script type="text/javascript">
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 35
SZABIST jstc Shaheed Benazirabad
_uacct = "UA-232293";
urchinTracker();
</script>
</head>
<body>
<p>This is a paragraph tag.</p>
</body>
</html>
Adding Meta Tags to Your Documents:
You can add metadata to your web pages by placing <meta> tags between the <head> and
</head> tags. The can include the following attributes:
Attribute
Description
Name
Name for the property. Can be anything. Examples include, keywords, description, author,
revised, generator etc.
content
Specifies the property's value.
scheme
Specifies a scheme to use to interpret the property's value (as declared in the content
attribute).
httpequiv
Used for http response message headers. For example http-equiv can be used to refresh the
page or to set a cookie. Values include content-type, expires, refresh and set-cookie.
NOTE: Core attributes for all the elements are discussed in next chapter.
Meta Tag Examples:
Let's see few important usage of Meta Tags.
Specifying Keywords:
We specify keywords which will be used by the search engine to search a web page. So using
following tag you can specify important keywords related to your page.
<head>
<meta name="keywords" content="HTML, meta tags, metadata" />
</head>
Document Description:
This is again important information and many search engine use this information as well while
searching a web page. So you should give an appropriate description of the page.
<head>
<meta name="description" content="Learn about Meta Tags." />
</head>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 36
SZABIST jstc Shaheed Benazirabad
Document Revision date:
This information tells about last time the document was updated.
<head>
<meta name="revised" content="Tutorialspoint, 6/12/2006" />
</head>
Document Refreshing:
You can specify a duration after which your web page will keep refreshing. If you want your
page keep refreshing after every 10 seconds then use the following syntax.
<head>
<meta http-equiv="refresh" content="10" />
</head>
Page Redirection:
You can specify a page redirection using Meta Tag. Following is an example of redirecting
current page to another page. You can specify a duration after which page will be redirected.
<head>
<meta http-equiv="refresh"
content="10; url=http://www.tutorialspoint.com" />
</head>
If you don't provide a duration then page will be redirected immediately.
Setting Cookies:
You can use Meta Tag to store cookies on client side later information can be used by then Web
Server to track a site visitor.
<head>
<meta http-equiv="cookie" content="userid=xyz;
expires=Wednesday, 08-Aug-00 23:59:59 GMT; />
</head>
If you do not include the expiration date and time, the cookie is considered a session cookie and
will be deleted when the user exits the browser.
Setting Author Name:
You can set an author name in a web page using Meta Tag. See an example below:
<head>
<meta name="author" content="Mahnaz Mohtashim" />
</head>
Attributes are another important part of HTML markup. An attribute is used to define the
characteristics of an element and is placed inside the element's opening tag. All attributes are
made up of two parts: a name and a value:
 The name is the property you want to set. For example, the <font> element in the
example carries an attribute whose name is face, which you can use to indicate which
typeface you want the text to appear in.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 37
SZABIST jstc Shaheed Benazirabad

The value is what you want the value of the property to be. The first example was
supposed to use the Arial typeface, so the value of the face attribute is Arial.
The value of the attribute should be put in double quotation marks, and is separated from the
name by the equals sign. You can see that a color for the text has been specified as well as the
typeface in this <font> element:
<font face="arial" color="#CC0000">
Many HTML tags have a unique set of their own attributes. These will be discussed as each tag
is introduced throughout the tutorial. Right now we want to focus on a set of generic attributes
that can be used with just about every HTML Tag in existence.
Core Attributes:
The four core attributes that can be used on the majority of HTML elements (although not all)
are:




id
title
class
style
The id Attribute:
The id attribute can be used to uniquely identify any element within a page ( or style sheet ).
There are two primary reasons that you might want to use an id attribute on an element:
 If an element carries an id attribute as a unique identifier it is possible to identify just that
element and its content.
 If you have two elements of the same name within a Web page (or style sheet), you can
use the id attribute to distinguish between elements that have the same name.
We will discuss style sheet in separate tutorial. For now, the id attribute could be used to
distinguish between two paragraph elements, like so:
<p id="html">This para explains what is HTML</p>
<p id="css">This para explains what is Casecading Style Sheet</p>
Note that there are some special rules for the value of the id attribute, it must:
 Begin with a letter (A.Z or a.z) and can then be followed by any number of letters, digits
(0.9), hyphens, underscores, colons, and periods.
 Remain unique within that document; no two attributes may have the same value within
that HTML document.
The title Attribute:
The title attribute gives a suggested title for the element. They syntax for the title attribute is
similar as explained for id attribute:
The behavior of this attribute will depend upon the element that carries it, although it is often
displayed as a tooltip or while the element is loading.
For example:
<h4 title="Hello HTML!">Titled Heading Tag Example</h4>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 38
SZABIST jstc Shaheed Benazirabad
Above code will generate following result:
Titled Heading Tag Example
Now try to bring your cursor over "Titled Heading Tag Example" and see the result.
The class Attribute:
The class attribute is used to associate an element with a style sheet, and specifies the class of
element. You learn more about the use of the class attribute when you will learn Casecading
Style Sheet (CSS). So for now you can avoid it.
The value of the attribute may also be a space-separated list of class names. For example:
class="className1 className2 className3"
The style Attribute:
The style attribute allows you to specify CSS rules within the element. For example:
<p style="font-family:arial; color:#FF0000;">Some text...</p>
Whitespace and Flow:
Before you start to mark up your text, it is best to understand what HTML does when it comes
across spaces and how browsers treat long sentences and paragraphs of text.
You might think that if you put several consecutive spaces between two words, the spaces would
appear between those words onscreen, but this is not the case; by default, only one space will be
displayed. This is known as white space collapsing. So you need to use special HTML tags to
create multiple spaces.
Similarly, if you start a new line in your source document, or you have consecutive empty lines,
these will be ignored and simply treated as one space. So you need to use special HTML tags to
create more number of empty lines.
Create Headings - The <hn> Elements:
Any documents starts with a heading. You use different sizes for your headings. HTML also
have six levels of headings, which use the elements <h1>, <h2>, <h3>, <h4>, <h5>, and <h6>.
While displaying any heading, browser adds one line before and after that heading.
Example:
<h1>This
<h2>This
<h3>This
<h4>This
<h5>This
<h6>This
is
is
is
is
is
is
heading
heading
heading
heading
heading
heading
1</h1>
2</h2>
3</h3>
4</h4>
5</h5>
6</h6>
This will display following result:
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 39
SZABIST jstc Shaheed Benazirabad
This is heading 1
This is heading 2
This is heading 3
This is heading 4
This is heading 5
This is heading 6
Create Paragraph - The <p> Element:
The <p> element offers a way to structure your text. Each paragraph of text should go in
between an opening <p> and closing </p> tag as shown below in the example:
<p>Here is a paragraph of text.</p>
<p>Here is a second paragraph of text.</p>
<p>Here is a third paragraph of text.</p>
This will produce following result:
Here is a paragraph of text.
Here is a second paragraph of text.
Here is a third paragraph of text.
You can use align attribute to align your paragraphs.
<p align="left">This is left aligned.</p>
<p align="center">This is center aligned.</p>
<p align="right">This is right aligned.</p>
<p align="justify">This is jutified. This works when you have multiple lines in your paragraph and you
want to justfy all the lines so that they can look more nice.</p>
This will produce following result:
This is left aligned.
This is center aligned.
This is right aligned.
This is jutified. This works when you have multiple lines in your paragraph and you want to
justfy all the lines so that they can look more nice.
Create Line Breaks - The <br /> Element:
Whenever you use the <br /> element, anything following it starts on the next line. This tag is an
example of an empty element, where you do not need opening and closing tags, as there is
nothing to go in between them.
Note: The <br /> element has a space between the characters br and the forward slash. If you
omit this space, older browsers will have trouble rendering the line break, while if you miss the
forward slash character and just use <br> it is not valid XHTML
Example:
Hello<br />
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 40
SZABIST jstc Shaheed Benazirabad
You come most carefully upon your hour.<br />
Thanks<br />
Mahnaz
This will produce following result:
Hello
You come most carefully upon your hour.
Thanks
Mahnaz
Centring Content - The <center> Element:
You can use <center> tag to put any content in the center of the page or any table cell.
Example:
<p>This is not in the center.</p>
<center>
<p>This is in the center.</p>
</center>
This will produce following result:
This is not in the center.
This is in the center.
Nonbreaking Spaces:
Suppose you were to use the phrase "12 Angry Men." Here you would not want a browser to
split the "12" and "Angry" across two lines:
A good example of this technique appears in the movie "12 Angry Men."
In cases where you do not want the client browser to break text, you should use a nonbreaking
space entity ( ) instead of a normal space. For example, when coding the "12 Angry Men"
paragraph, you would use something similar to the following code:
<p>A good example of this technique appears in the movie "12 Angry Men."</p>
Presentational Tags:
If you use a word processor, you are familiar with the ability to make text bold, italicized, or
underlined; these are just three of the ten options available to indicate how text can appear in
HTML and XHTML.
Bold Text - The <b> Element:
Anything that appears in a <b>...</b> element is displayed in bold, like the word bold here:
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 41
SZABIST jstc Shaheed Benazirabad
<p>The following word uses a <b>bold</b> typeface.</p>
This will produce following result:
The following word uses a bold typeface.
Italic Text - The <i> Element:
Anything that appears in a <i>...</i> element is displayed in italicized, like the word italicized
here:
<p>The following word uses a <i>italicized</i> typeface.</p>
Strong Text - The <strong> Element:
The <strong> element is intended to show strong emphasis for its content; stronger emphasis
than the <em> element. As with the <em> element, the <strong> element should be used only
when you want to add strong emphasis to part of a document.
<p>You <strong>must</strong> remember to close elements in XHTML.</p>
This will produce following result:
You must remember to close elements in XHTML.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 42
SZABIST jstc Shaheed Benazirabad
Text Abbreviation - The <abbr> Element :
You can indicate when you are using an abbreviated form by placing the abbreviation between
opening <abbr> and closing </abbr> tags.
<p>I have a friend called <abbr title="Abhishek">Abhy</abbr>.</p>
This will produce following result:
I have a friend called
Abhy.
TML.
Quoting Text - The <blockquote> Element :
When you want to quote a passage from another source, you should use the <blockquote>
element.
Text inside a <blockquote> element is usually indented from the left and right edges of the
surrounding text, and sometimes uses an italicized font.
<p>The following description of XHTML is taken from the W3C Web site:</p>
<blockquote> XHTML 1.0 is the W3C's first Recommendation for XHTML, following on from earlier
work on HTML 4.01, HTML 4.0, HTML 3.2 and HTML 2.0. </blockquote>
This will produce following result:
The following description of XHTML is taken from the W3C Web site:
XHTML 1.0 is the W3C's first Recommendation for XHTML, following on from earlier work on HTML
4.01, HTML 4.0, HTML 3.2 and HTML 2.0.
You can use the cite attribute on the <blockquote> element to indicate the source of the quote.
<p>The following description of XHTML is taken from the W3C Web site:</p>
<blockquote cite="http://www.w3.org/markup/"> XHTML 1.0 is the W3C's first Recommendation for
XHTML, following on from earlier work on HTML 4.01, HTML 4.0, HTML 3.2 and HTML 2.0.
</blockquote>
Short Quotations - The <q> Element :
The <q> element is intended to be used when you want to add a quote within a sentence rather
than as an indented block on its own.
<p>Amit is in Spain, <q>He is their at my home. I think I am wrong</q>.</p>
This will produce following result:
Amit is in Spain, He is their at my home. I think I am wrong.
Citations - The <cite> Element :
If you are quoting a text, you can indicate the source placing it between an opening <cite> tag
and closing </cite> tag
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 43
SZABIST jstc Shaheed Benazirabad
As you would expect in a print publication, the content of the <cite> element is rendered in
italicized text by default.
<p>This HTML Tutorial is derived from <cite>World Wide Web Standard for HTML</cite>.</p>
This will produce following result:
This HTML Tutorial is derived from World Wide Web Standard for HTML.
Comments
HTML Comment lines are indicated by the special beginning tag <!-- and ending tag --> placed
at the beginning and end of EVERY line to be treated as a comment.
Comments do not nest, and the double-dash sequence "--" may not appear inside a comment
except as part of the closing --> tag. You must also make sure that there are no spaces in the
start-of-comment string.
For example: Given line is a valid comment in HTML
<!--
This is commented out -->
But following line is not a valid comment and will be displayed by the borwser. This is because
there is a space between the left angle bracket and the exclamation mark.
< !--
This is commented out -->
Multiline Comments:
You have seen how to comment a single line in HTML. You can comment multiple lines by
the special beginning tag <!-- and ending tag --> placed before the first line and end of the
lastline to be treated as a comment.
For example:
<!-This is a multiline comment <br />
and can span through as many as lines you like.
-->
Conditional Comments :
Conditional comments only work in Explorer on Windows, and are thus excellently suited to
give special instructions meant only for Explorer on Windows. They are supported from
Explorer 5 onwards, and it is even possible to distinguish between 5.0, 5.5 and 6.0.
Conditional comments work as follows:
<!--[if IE 6]>
Special instructions for IE 6 here
<![endif]-->


Their basic structure is the same as an HTML comment (<!-- -->). Therefore all other
browsers will see them as normal comments and will ignore them entirely.
Explorer Windows, though, has been programmed to recognize the special <!--[if IE]>
syntax, resolves the if and parses the content of the conditional comment as if it were
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 44
SZABIST jstc Shaheed Benazirabad

normal page content.
Since conditional comments use the HTML comment structure, they can only be
included in HTML files, and not in CSS files.
Using Comment tag
There are few browsers who supports <comment> tag to comment a part of code.
<p>This is <comment>not</comment> Internet Explorer.</p>
Commenting Scripts and Style Sheets:
If you are using Java Script or VB Script in your HTML code then it is recommended to put
that script code inside proper HTML Comments to make old browser works properly.
For example:
<script>
<!-document.write("Hello World!")
//-->
</script>
Similarly if you are using Casecading Style Sheet in your HTML code then it is recommended
to put that style sheet code inside proper HTML Comments to make old browser works
properly.
For example:
<style>
<!-img{
border:0px;
}
//-->
</style>
Font Size:
You can set the size of your font with size attribute. The range of accepted values is from
1(smallest) to 7(largest). The default size of a font is 3.
Example:
<font
<font
<font
<font
<font
<font
<font
size="1">Font
size="2">Font
size="3">Font
size="4">Font
size="5">Font
size="6">Font
size="7">Font
size="1"</font>
size="2"</font>
size="3"</font>
size="4"</font>
size="5"</font>
size="6"</font>
size="7"</font>
This will produce following result:
Font size="1"
Font size="2"
Font size="3"
Font size="4"
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 45
SZABIST jstc Shaheed Benazirabad
Font size="5"
Font size="6"
Font size="7"
SPECIFY THE RELATIVE FONT SIZE. <font size="+n"> or <font size="-n">:
You can specify how many sizes larger or how many sizes smaller than the preset font size
should be.
Example:
<font
<font
<font
<font
<font
size="-1">Font
size="+1">Font
size="+2">Font
size="+3">Font
size="+4">Font
size="-1"</font>
size="+1"</font>
size="+2"</font>
size="+3"</font>
size="+4"</font>
This will produce following result:
Font size="-1"
Font size="+1"
Font size="+2"
Font size="+3"
Font size="+4"
Font Face:
You can set any font you like using face attribute but be aware that if the user viewing the
page doesn't have the font installed, they will not be able to see it. Instead they will default
to Times New Roman of your font with size attribute. See below few examples on using
different font face
Example:
<font
<font
<font
<font
<font
face="Times New Roman" size="5">Times New Roman</font>
face="Verdana" size="5">Verdana</font>
face="Comic sans MS" size="5">Comic Sans MS</font>
face="WildWest" size="5">WildWest</font>
face="Bedrock" size="5">Bedrock</font>
This will produce following result:
Times New Roman
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 46
SZABIST jstc Shaheed Benazirabad
Verdana
Comic Sans MS
WildWest
Bedrock
Specify alternate font faces:
A visitor will only be able to see your font if they have that font installed on their computer.
So, it is possible to specify two or more font face alternatives by listing the font face names,
separated by a comma.
Example:
<font face="arial,helvetica">
<font face="Lucida Calligraphy,Comic Sans MS,Lucida Console>
When your page is loaded, their browser will display the first font face that it has available.
If none of your selections are installed....then it will display the default font face Times New
Roman.
Check a complete list of HTML Standard Fonts.
Font Color:
You can set any font color you like using color attribute. You can specify the color that you
want by either the color name or hexadecimal code for that color. Check a complete list of
HTML Color Name with Codes.
Example:
<font color="#FF00FF">This text is hexcolor #FF00FF</font>
<font color="red">This text is red</font>
This will produce following result:
This text is hexcolor #FF00FF
This text is red
The <basefont> Element:
The <basefont> element is supposed to set a default font size, color, and typeface for any
parts of the document that are not otherwise contained within a <font> element. You can
then use the <font> elements to override the <basefont> settings.
The attributes that the <basefont> element takes are exactly the same as for the <font>
element. You can also set the size of fonts relative to the size of the <basefont> by giving
them a value of +1 for a size larger or -2 for two sizes smaller
NOTE: This element is deprecated in HTML 4 and will be removed from HTML, the
preferred option is to use CSS styles. Your browser may not have support for this tag.
Example:
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 47
SZABIST jstc Shaheed Benazirabad
<basefont face="arial, verdana, sans-serif" size="2" color="#ff0000">
<p>This is the page's default font.</p>
<h2>Example of the <basefont> Element</h2>
<p><font size="+2" color="darkgray">Here is some darkgray text
two sizes larger</font></p>
<p><font face="courier" size="-1" color="#000000">Here is a courier
font, a size smaller, in black</font></p>
This will produce following result:
This is the page's default font.
Example of the <basefont> Element
Here is some darkgray text
two sizes larger
Here is a courier
font, a size smaller, in black
As you can see, the default font now takes on the properties specified in the <basefont>
element. It is red, size 2, and uses the Arial typeface.
The paragraph after the <h2> element uses a font size two sizes larger than the default size
and is gray text, whereas the following paragraph uses a font one size smaller than the
default font. You can also see that the color of this font is black (overriding the default).
HTML Marquees
A HTML marquee is a scrolling piece of text displayed either horizontally across or
vertically down your web site page depending on the settings. This is created by using
HTML tag <marquees>.
NOTE: The HTML <marquee> is an MSIE extension, but is now supported by NS 7 also.
So please check if your browser supports this tag or not.
Syntax:
A simple syntax to use marquee is as follows:
<marquee attribute_name="attribute_value"....more attributes>
One or more lines or text message or image
</marquee>
Attrubutes:
A HTML marquee can have following attributes:
 width: how wide the marquee is. This will have a value like 10 or 20%etc.
 height: how tall the marquee is. This will have a value like 10 or 20% etc.
 direction: which direction the marquee should scroll. This will have value either up,
down, left or right.
 behavior: what type of scrolling. This will have value scroll, slid and alternate.
 scrolldelay: how long to delay between each jump. This will have a value like 10
etc.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 48
SZABIST jstc Shaheed Benazirabad





scrollamount: how far to jump. This will have a value like 10 etc.
loop: how many times to loop. The default value is INFINITE, which means that the
marquee loops endlessly.
bgcolor: background color. This will have any color name or color hex value.
hspace: horizontal space around the marquee. This will have a value like 10 or
20%etc.
vspace: vertical space around the marquee. This will have a value like 10 or 20%etc.
Examples:
Here are few examples to demonstrate the usage of marquee tag.
<marquee>This is basic example of marquee</marquee>
<marquee width="50%">This example will take only 50% width</marquee>
<marquee direction="right">This text will scroll from left to
right</marquee>
<marquee direction="up">This text will scroll from bottom to up</marquee>
Insert Image - The <img> Element:
You will insert any image in your web page by using <img> tag. Following is the simple
syntax to use this tag.
<img src="image URL" attr_name="attr_value"...more attributes />
Image Attributes:
Following are most frequently used attributes for <img> tag.
 width: sets width of the image. This will have a value like 10 or 20%etc.
 height: sets height of the image. This will have a value like 10 or 20% etc.
 border: sets a border around the image. This will have a value like 1 or 2 etc.
 src: specifies URL of the image file.
 alt: this is an alternate text which will be displayed if image is missing.
 align: this sets horizontal alignment of the image and takes value either left, right or
center.
 valign: this sets vertical alignment of the image and takes value either top, bottom or
center.
 hspace: horizontal space around the image. This will have a value like 10 or 20%etc.
 vspace: vertical space around the image. This will have a value like 10 or 20%etc.
 name: name of the image with in the document.
 id: id of the image with in the document.
 style: this will be used if you are using CSS.
 title: specifies a text title. The browser, perhaps flashing the title when the mouse
passes over the link.
 ismap and usemap: These attributes for the <img> tag tell the browser that the
image is a special mouse-selectable visual map of one or more hyperlinks, commonly
known as an image map. We will see how to use these attributes in Image Links
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 49
SZABIST jstc Shaheed Benazirabad
chapter.
A Simple Example:
<img src="http://www.tutorialspoint.com/images/html.gif" alt="HTML Tutorial" />
Linking Documents - The <a> Element:
Anchor Attributes:
Following are most frequently used attributes for <a> tag.
 href: specifies the URL of the target of a hyperlink. Its value is any valid document
URL, absolute or relative, including a fragment identifier or a JavaScript code
fragment.
 target: specify where to display the contents of a selected hyperlink. If set to
"_blank" then a new window will be opened to display the loaded page, if set to
"_top" or "_parent" then same window will be used to display the loaded document,
if set to "_self" then loads the new page in current window. By default its "_self".
 name & id: attributes places a label within a document. When that label is used in a
link to that document, it is the equivalent of telling the browser to goto that label.
 event: attributes like onClick, onMouseOver etc. are used to trigger any Javascript ot
VBscript code.
 title: attribute lets you specify a title for the document to which you are linking. The
value of the attribute is any string, enclosed in quotation marks. The browser might
use it when displaying the link, perhaps flashing the title when the mouse passes over
the link.
 accesskey: attribute attribute provides a keyboard shortcut that can be used to
activate a link. For example, you could make the T key an access key so that when
the user presses either the Alt or Ctrl key on his keyboard (depending on his
operating system) along with the T key, the link gets activated.
A Simple Example:
<a href="http://www.tutorialspoint.com/" target="_blank" >TP Home</a> |
<a href="http://www.amrood.com/" target="_self" >AMROOD Home</a> |
<a href="http://www.change-images.com/" target="_top" >Change Images Home</a>
Tables are very useful to arrange in HTML and they are used very frequently by almost all
web developers. Tables are just like spreadsheets and they are made up of rows and
columns.
You will create a table in HTML/XHTML by using <table> tag. Inside <table> element the
table is written out row by row. A row is contained inside a <tr> tag . which stands for table
row. And each cell is then written inside the row element using a <td> tag . which stands for
table data.
Example:
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 50
SZABIST jstc Shaheed Benazirabad
<table border="1">
<tr>
<td>Row 1, Column 1</td>
<td>Row 1, Column 2</td>
</tr>
<tr>
<td>Row 2, Column 1</td>
<td>Row 2, Column 2</td>
</tr>
</table>
This will produce following result:
Row 1, Column 1 Row 1, Column 2
Row 2, Column 1 Row 2, Column 2
NOTE: In the above example border is an attribute of <table> and it will put border across
all the cells. If you do not need a border then you cal use border="0". The border attribute
and other attributes also mentione din this session are deprecated and they have been
replaced by CSS. So it is recommended to use CSS instead of using any attribute directly.
Table Heading - The <th> Element:
Table heading can be defined using <th> element. This tag will be put to replace <td> tag
which is used to represent actual data. Normally you will put your top row as table heading
as shown below, otherwise you can use <th> element at any place:
<table border="1">
<tr>
<th>Name</th>
<th>Salary</th>
</tr>
<tr>
<td>Ramesh Raman</td>
<td>5000</td>
</tr>
<tr>
<td>Shabbir Hussein</td>
<td>7000</td>
</tr>
</table>
This will produce following result. You can see its making heading as a bold one:
Name
Salary
Ramesh Raman 5000
Shabbir Hussein 7000
NOTE: Each cell must, however, have either a <td> or a <th> element in order for the table
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 51
SZABIST jstc Shaheed Benazirabad
to display correctly even if that element is empty.
Table Cellpadding and Cellspacing:
There are two attribiutes called cellpadding and cellspacing which you will use to adjust the
white space in your table cell. Cellspacing defines the width of the border, while cellpadding
represents the distance between cell borders and the content within. Following is the
example:
<table border="1" cellpadding="5" cellspacing="5">
<tr>
<th>Name</th>
<th>Salary</th>
</tr>
<tr>
<td>Ramesh Raman</td>
<td>5000</td>
</tr>
<tr>
<td>Shabbir Hussein</td>
<td>7000</td>
</tr>
</table>
This will produce following result:
Name
Salary
Ramesh Raman
5000
Shabbir Hussein
7000
Colspan and Rowspan Attributes:
You will use colspan attribute if you want to merge two or more columns into a single
column. Similar way you will use rowspan if you want to merge two or more rows.
Following is the example:
<table border="1">
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
<tr><td rowspan="2">Row 1 Cell 1</td>
<td>Row 1 Cell 2</td><td>Row 1 Cell 3</td></tr>
<tr><td>Row 2 Cell 2</td><td>Row 2 Cell 3</td></tr>
<tr><td colspan="3">Row 3 Cell 1</td></tr>
</table>
This will produce following result:
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 52
SZABIST jstc Shaheed Benazirabad
Column 1
Row 1 Cell 1
Column 2
Column 3
Row 1 Cell 2 Row 1 Cell 3
Row 2 Cell 2 Row 2 Cell 3
Row 3 Cell 1
Tables Backgrounds
You can set table background using of the following two ways:
 Using bgcolor attribute - You can set background color for whole table or just for
one cell.
 Using background attribute - You can set background image for whole table or just
for one cell.
NOTE:You can set border color also using bordercolor attribute.
Here is an example of using bgcolor attribute:
<table border="5" bordercolor="green" bgcolor="gray">
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
<tr><td rowspan="2">Row 1 Cell 1</td>
<td bgcolor="red">Row 1 Cell 2</td><td>Row 1 Cell 3</td></tr>
<tr><td>Row 2 Cell 2</td><td>Row 2 Cell 3</td></tr>
<tr><td colspan="3">Row 3 Cell 1</td></tr>
</table>
This will produce following result:
Column 1
Row 1 Cell 1
Column 2
Column 3
Row 1 Cell 2 Row 1 Cell 3
Row 2 Cell 2 Row 2 Cell 3
Row 3 Cell 1
Here is an example of using background attribute:
<table border="1" background="/images/home.gif">
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
<tr><td rowspan="2">Row 1 Cell 1</td>
<td bgcolor="red">Row 1 Cell 2</td><td>Row 1 Cell 3</td></tr>
<tr><td>Row 2 Cell 2</td><td>Row 2 Cell 3</td></tr>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 53
SZABIST jstc Shaheed Benazirabad
<tr><td colspan="3" background="/images/pattern1.gif">
Row 3 Cell 1
</td></tr>
</table>
This will produce following result:
Column 1
Row 1 Cell 1
Column 2
Column 3
Row 1 Cell 2 Row 1 Cell 3
Row 2 Cell 2 Row 2 Cell 3
Row 3 Cell 1
Table height and width:
You can set a table width and height using width and height attrubutes. You can specify
table width or height in terms of integer value or in terms of percentage of available screen
area. Following is the example:
<table border="1"
<tr>
<td>Row 1, Column
<td>Row 1, Column
</tr>
<tr>
<td>Row 2, Column
<td>Row 2, Column
</tr>
</table>
width="400" height="150">
1</td>
2</td>
1</td>
2</td>
This will produce following result:
Row 1, Column 1
Row 1, Column 2
Row 2, Column 1
Row 2, Column 2
Using Table Caption:
The caption tags will serve as a title or explanation and show up at the top of the table. This
tag is depracated in newer version of HTML/XHTML.
<table border="1">
<caption>This is the caption</caption>
<tr>
<td>row 1, column 1</td><td>row 1, columnn 2</td>
</tr>
</table>
This will produce following result:
This is the caption
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 54
SZABIST jstc Shaheed Benazirabad
row 1, column 1 row 1, columnn 2
Using a Header, Body, and Footer:
Tables can be divided into three portions: a header, a body, and a foot. The head and foot are
rather similar to headers and footers in a word-processed document that remain the same for
every page, while the body is the main content of the table.
The three elements for separating the head, body, and foot of a table are:
 <thead> - to create a separate table header.
 <tbody> - to indicate the main body of the table.
 <tfoot> - to create a separate table footer.
A table may contain several <tbody> elements to indicate different pages or groups of data.
But it is notable that <thead> and <tfoot> tags should appear before <tbody>
<table border="1" width="100%">
<thead>
<tr>
<td colspan="4">This is the head of the table</td>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="4">This is the foot of the table</td>
</tr>
</tfoot>
<tbody>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
<td>Cell 3</td>
<td>Cell 4</td>
</tr>
<tr>
...more rows here containing four cells...
</tr>
</tbody>
<tbody>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
<td>Cell 3</td>
<td>Cell 4</td>
</tr>
<tr>
...more rows here containing four cells...
</tr>
</tbody>
</table>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 55
SZABIST jstc Shaheed Benazirabad
This will produce following result:
This will produce following result:
This is the head of the table
This is the foot of the table
Cell 1
Cell 2
Cell 3
Cell 4
...more rows here containing four cells...
Cell 1
Cell 2
Cell 3
Cell 4
...more rows here containing four cells...
Nested Tables:
You can use one table inside another table. Not only tables you can use almost all the tags inside
table data tag <td>.
Following is the example of using another table and other tags inside a table cell.
<table border="1">
<tr>
<td>
<table border="1">
<tr>
<th>Name</th>
<th>Salary</th>
</tr>
<tr>
<td>Ramesh Raman</td>
<td>5000</td>
</tr>
<tr>
<td>Shabbir Hussein</td>
<td>7000</td>
</tr>
</table>
</td>
<td>
<ul>
<li>This is another cell</li>
<li>Using list inside this cell</li>
</ul>
</td>
</tr>
<tr>
<td>Row 2, Column 1</td>
<td>Row 2, Column 2</td>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 56
SZABIST jstc Shaheed Benazirabad
</tr>
</table>
This will produce following result:
Name
Salary


Ramesh Raman 5000
This is another cell
Using list inside this cell
Shabbir Hussein 7000
Row 2, Column 1
Row 2, Column 2
You can list out your items, subjects or menu in the form of a list. HTML gives you three
different types of lists.
 <ul> - An unordered list. This will list items using bullets
 <ol> - A ordered list. This will use different schemes of numbers to list your items
 <dl> - A definition list. This is arrange your items in the same way as they are arranged
in a dictionary.
HTML Unordered Lists:
An unordered list is a collection of related items that have no special order or sequence. The
most common unordered list you will find on the Web is a collection of hyperlinks to other
documents.
This list is created by using <ul> tag. Each item in the list is marked with a butllet. The bullet
itself comes in three flavors: squares, discs, and circles. The default bullet displayed by most web
browsers is the traditional full disc.
One Movie list is given below:
<center>
<h2>Movie List</h2>
</center>
<ul>
<li>Ram Teri Ganga Meli</li>
<li>Mera Naam Jocker</li>
<li>Titanic</li>
<li>Ghost in the ship</li>
</ul>
This will produce following result:
Movie List




Ram Teri Ganga Meli
Mera Naam Jocker
Titanic
Ghost in the ship
You can use type attribute to specify the type of bullet you like. By default its is a disc.
Following are the possible way:
<ul type="square">
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 57
SZABIST jstc Shaheed Benazirabad
<ul type="disc">
<ul type="circle">
<ul type="square"> <ul type="disc">








Hindi
English
Maths
Physics
Hindi
English
Maths
Physics
<ul type="circle">
o
o
o
o
Hindi
English
Maths
Physics
HTML Ordered Lists:
The typical browser formats the contents of an ordered list just like an unordered list, except that
the items are numbered instead of bulleted. The numbering starts at one and is incremented by
one for each successive ordered list element tagged with <li>
This list is created by using <ol> tag. Each item in the list is marked with a number.
One Movie list is given below:
<center>
<h2>Movie List</h2>
</center>
<ol>
<li>Ram Teri Ganga Meli</li>
<li>Mera Naam Jocker</li>
<li>Titanic</li>
<li>Ghost in the ship</li>
</ol>
This will produce following result:
Movie List
1. Ram Teri Ganga Meli
2. Mera Naam Jocker
3. Titanic
4. Ghost in the ship
You can use type attribute to specify the type of numbers you like. By default its is a generic
numbers. Following are the other possible way:
<ol
<ol
<ol
<ol
type="I">
type="i">
type="a">
type="A">
<ol type="I">
I.
II.
III.
IV.
Hindi
English
Maths
Physics
-
Upper-Case
Lower-Case
Lower-Case
Upper-Case
Numerals.
Numerals.
Letters.
Letters.
<ol type="i">
i.
ii.
iii.
iv.
Hindi
English
Maths
Physics
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
<ol type="a">
a. Hindi
b. English
c. Maths
d. Physics
<ol type="A">
A. Hindi
B. English
C. Maths
D. Physics
Page 58
SZABIST jstc Shaheed Benazirabad
You can use start attribute to specify the beginning of any index. By default its is a first number
or character. In the following example index starts from 5:
<center>
<h2>Movie List</h2>
</center>
<ol start="5">
<li>Ram Teri Ganga Meli</li>
<li>Mera Naam Jocker</li>
<li>Titanic</li>
<li>Ghost in the ship</li>
</ol>
This will produce following result:
Movie List
5. Ram Teri Ganga Meli
6. Mera Naam Jocker
7. Titanic
8. Ghost in the ship
HTML Definition Lists:
HTML and XHTML also support a list style entirely different from the ordered and unordered
lists we have discussed so far - definition lists . Like the entries you find in a dictionary or
encyclopedia, complete with text, pictures, and other multimedia elements, the Definition List is
the ideal way to present a glossary, list of terms, or other name/value list.
Definition List makes use of following three tags.




<dl> - Defines the start of the list
<dt> - A term
<dd> - Term definition
</dl> - Defines the end of the list
Example:
<dl>
<dt><b>HTML</b></dt>
<dd>This stands for Hyper Text Markup Language</dd>
<dt><b>HTTP</b></dt>
<dd>This stands for Hyper Text Transfer Protocol</dd>
</dl>
This will produce following result:
HTML
This stands for Hyper Text Markup Language
HTTP
This stands for Hyper Text Transfer Protocol
Appropriate List Usage:
Following are just a suggestion and there is no hard and fast rule to use them:
Use unordered lists for:
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 59
SZABIST jstc Shaheed Benazirabad



Link collections
Short, nonsequenced groups of text
Emphasizing the high points of a presentation
Use ordered lists for:
 Tables of contents
 Sets of sequential sections of text
 Assigning numbers to short phrases that can be referenced elsewhere
Use definition lists for:
 Glossaries
 Custom bullets - make the item after the <dt> tag an icon-sized bullet image)
 Any list of name/value pairs
HTML Layout - Using Tables:
The simplest and most popular way of creating layouts is using HTML <table> tag. These tables
are arranged in columns and rows, so you can utilize these rows and columns in whatever way
you like.
For example, the following HTML layout example is achieved using a table with 3 rows and 2
columns - but the header and footer column spans both columns using the colspan attribute:
<table width="100%" border="0">
<tr>
<td colspan="2" style="background-color:#CC99FF;">
<h1>This is Web Page Main title</h1>
</td>
</tr>
<tr valign="top">
<td style="background-color:#FFCCFF;
width:100px;text-align:top;">
<b>Main Menu</b><br />
HTML<br />
PHP<br />
PERL...
</td>
<td style="background-color:#eeeeee;height:200px;
width:300px;text-align:top;">
Technical and Managerial Tutorials
</td>
</tr>
<tr>
<td colspan="2" style="background-color:#CC99FF;">
<center>
Copyright © 2007 Tutorialspoint.com
</center>
</td>
</tr>
</table>
This will produce following result:
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 60
SZABIST jstc Shaheed Benazirabad
This is Web Page Main title
Main Menu
HTML
PHP
PERL...
Technical and Managerial Tutorials
Copyright © 2007 Tutorialspoint.com
Multiuple Columns Layouts - Using Tables
You can design your webpage to put your web content in multiple pages. You can keep your
content in middle column and you can use left column to use menu and right column can be used
to put advertisement or some other stuff. It will be very similar to our site tutorialspoint.com.
Here is an example to create three column layout:
<table width="100%" border="0">
<tr valign="top">
<td style="background-color:#FFCCFF;width:20%;
text-align:top;">
<b>Main Menu</b><br />
HTML<br />
PHP<br />
PERL...
</td>
<td style="background-color:#eeeeee;height:200px;
width:60%;text-align:top;">
Technical and Managerial Tutorials
</td>
<td style="background-color:#FFCCFF;
width:20%;text-align:top;">
<b>Right Menu</b><br />
HTML<br />
PHP<br />
PERL...
</td>
</tr>
<table>
This will produce following result:
Main Menu Technical and Managerial Tutorials Right Menu
HTML
HTML
PHP
PHP
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 61
SZABIST jstc Shaheed Benazirabad
PERL...
PERL...
HTML Layouts - Using DIV, SPAN
The div element is a block level element used for grouping HTML elements. While the div tag is
a block-level element, the HTML span element is used for grouping elements at an inline level.
Although we can achieve pretty nice layouts with HTML tables, tables weren't really designed as
a layout tool. Tables are more suited to presenting tabular data.
You can achieve same result whatever you have achieved using <table> tag in previous example.
<div style="width:100%">
<div style="background-color:#CC99FF;">
<b style="font-size:150%">This is Web Page Main title</b>
</div>
<div style="background-color:#FFCCFF;
height:200px;width:100px;float:left;">
<b>Main Menu</b><br />
HTML<br />
PHP<br />
PERL...
</div>
<div style="background-color:#eeeeee;
height:200px;width:300px;float:left;">
Technical and Managerial Tutorials
</div>
<div style="background-color:#CC99FF;clear:both">
<center>
Copyright © 2007 Tutorialspoint.com
</center>
</div>
</div>
This will produce following result:
This is Web Page Main title
Main Menu
HTML
PHP
PERL...
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 62
SZABIST jstc Shaheed Benazirabad
Technical and Managerial Tutorials
Copyright © 2007 Tutorialspoint.com
Colors are very important to give a good look and feel to your website. You can specify colors
on page level using <body> tag or you can set colors for individual tags.
The <body> tag has following attributes which can be used to set different colors:
 bgcolor: Sets a color for the background of the page.
 text: Sets a color for the body text.
 alink: Sets a color for active links or selected links.
 link: Sets a color for linked text.
 vlink: Sets a color for visited links - that is, for linked text that you have already clicked
on.
NOTE: It is recommended to use CSS to set background or text colors.
HTML Color Coding Methods:
There are following three different methods to set colors in your web page:
 Color names: You can specify color names directly like green, blue or red.
 Hex codes: A six-digit code representing the amount of red, green, and blue that make up
the color.
 Color decimal or percentage values: : This value is specified using the rgb( ) property.
Now we will see these coloring schemes one by one.
HTML Colors - Color Names:
You can sepecify direct a color name to set text or background color. W3C has listed 16 basic
color names that will validate with an HTML validator but there are over 200 different color
names supported by Netscape and IE. Check a complete list of HTML Color Name.
W3C Standard 16 Colors:
Here is the list of W3C Standard 16 Colors names and it is recommended to use them.
Black
Gray
Silver
White
Yellow
Lime
Aqua
Fuchsia
Red
Green
Blue
Purple
Maroon
Olive
Navy
Teal
HTML Forms are required when you want to collect some data from the site visitor. For example
registration information: name, email address, credit card, etc.
A form will take input from the site visitor and then will post your back-end application such as
CGI, ASP Script or PHP script etc. Then your back-end application will do required processing
on that data in whatever way you like.
Form elements are like text fields, textarea fields, drop-down menus, radio buttons, checkboxes,
etc. which are used to take information from the user.
A simple syntax of using <form> is as follows:
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 63
SZABIST jstc Shaheed Benazirabad
<form action="back-end script" method="posting method">
form elements like input, textarea etc.
</form>
Most frequently used form attributes are:
 name: This is the name of the form.
 action: Here you will specify any script URL which will receive uploaded data.
 method: Here you will specify method to be used to upload data. It can take various
values but most frequently used are GET and POST.
 target: It specifies the target page where the result of the script will be displayed. It takes
values like _blank, _self, _parent etc.
 enctype: You can use the enctype attribute to specify how the browser encodes the data
before it sends it to the server. Possible values are like:
o application/x-www-form-urlencoded - This is the standard method most forms
use. It converts spaces to the plus sign and non-alphanumeric characters into the
hexadecimal code for that character in ASCII text.
o mutlipart/form-data - This allows the data to be sent in parts, with each
consecutive part corresponding the a form control, in the order they appear in the
form. Each part can have an optional content-type header of its own indicating the
type of data for that form control.
Please refer to PERL & CGI for a detail on data uploading using CGI.
There are different types of form controls that you can use to collect data from a visitor to your
site.
 Text input controls
 Buttons
 Checkboxes and radio buttons
 Select boxes
 File select boxes
 Hidden controls
 Submit and reset button
HTML Forms - Text Input Controls:
There are actually three types of text input used on forms:
 Single-line text input controls: Used for items that require only one line of user input,
such as search boxes or names. They are created using the <input> element.
 Password input controls: Single-line text input that mask the characters a user enters.
 Multi-line text input controls: Used when the user is required to give details that may
be longer than a single sentence. Multi-line input controls are created with the <textarea>
element.
Single-line text input controls:
Single-line text input controls are created using an <input> element whose type attribute has a
value of text.
Here is a basic example of a single-line text input used to take first name and last name:
<form action="/cgi-bin/hello_get.cgi" method="get">
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 64
SZABIST jstc Shaheed Benazirabad
First name:
<input type="text" name="first_name" />
<br>
Last name:
<input type="text" name="last_name" />
<input type="submit" value="submit" />
</form>
Following is the list of attributes for <input> tag.
 type: Indicates the type of input control you want to create. This element is also used to
create other form controls such as radio buttons and checkboxes.
 name: Used to give the name part of the name/value pair that is sent to the server,
representing each form control and the value the user entered.
 value: Provides an initial value for the text input control that the user will see when the
form loads.
 size: Allows you to specify the width of the text-input control in terms of characters.
 maxlength: Allows you to specify the maximum number of characters a user can enter
into the text box.
Password input controls::
This is also a form of single-line text input controls are created using an <input> element whose
type attribute has a value of password.
Here is a basic example of a single-line password input used to take user password:
<form action="/cgi-bin/hello_get.cgi" method="get">
Login :
<input type="text" name="login" />
<br>
Password:
<input type="text" name="password" />
<input type="submit" value="submit" />
</form>
Multiple-Line Text Input Controls:
If you want to allow a visitor to your site to enter more than one line of text, you should create a
multiple-line text input control using the <textarea> element.
Here is a basic example of a multi-line text input used to take item description:
<form action="/cgi-bin/hello_get.cgi" method="get">
Description : <br />
<textarea rows="5" cols="50" name="description">
Enter description here...
</textarea>
<input type="submit" value="submit" />
</form>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 65
SZABIST jstc Shaheed Benazirabad
Following is the detail of above used attributes for <textarea> tag.
 name: The name of the control. This is used in the name/value pair that is sent to the
server.
 rows: Indicates the number of rows of text area box.
 cols: Indicates the number of columns of text area box.
HTML Forms - Creating Button:
There are various ways in HTML to create clickable buttons. You can create clickable button
using <input> tag.
When you use the <input> element to create a button, the type of button you create is specified
using the type attribute. The type attribute can take the following values:
 submit: This creates a button that automatically submits a form.
 reset: This creates a button that automatically resets form controls to their initial values.
 button: This creates a button that is used to trigger a client-side script when the user
clicks that button.
Here is the example:
<form action="http://www.example.com/test.asp" method="get">
<input type="submit" name="Submit" value="Submit" />
<br /><br />
<input type="reset" value="Reset" />
<input type="button" value="Button" />
</form>
You can use an image to create a button. Here is the syntax:
<form action="http://www.example.com/test.asp" method="get">
<input type="image" name="imagebutton" src="URL" />
</form>
Here src attribiute specifies a location of the image on your webserver.
You can use <button> element to create various buttons. Here is the syntax:
<form action="http://www.example.com/test.asp" method="get">
<button type="submit">Submit</button>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 66
SZABIST jstc Shaheed Benazirabad
<br /><br />
<button type="reset"> Reset </button>
<button type="button"> Button </button>
</form>
HTML Forms - Checkboxes Control:
Checkboxes are used when more than one option is required to be selected. They are created
using <input> tag as shown below.
Here is example HTML code for a form with two checkboxes
<form action="/cgi-bin/checkbox.cgi" method="get">
<input type="checkbox" name="maths" value="on"> Maths
<input type="checkbox" name="physics" value="on"> Physics
<input type="submit" value="Select Subject" />
</form>
The result of this code is the following form
Maths
Physics
Following is the list of important checkbox attributes:
 type: Indicates that you want to create a checkbox.
 name: Name of the control.
 value: The value that will be used if the checkbox is selected. More than one checkbox
should share the same name only if you want to allow users to select several items from
the same list.
 checked: Indicates that when the page loads, the checkbox should be selected.
HTML Forms - Raido box Control:
Radio Buttons are used when only one option is required to be selected. They are created using
<input> tag as shown below:
Here is example HTML code for a form with two radio button:
<form action="/cgi-bin/radiobutton.cgi" method="post">
<input type="radio" name="subject" value="maths" /> Maths
<input type="radio" name="subject" value="physics" /> Physics
<input type="submit" value="Select Subject" />
</form>
The result of this code is the following form
Maths
Physics
Following is the list of important radiobox attributes:
 type: Indicates that you want to create a radiobox.
 name: Name of the control.
 value: Used to indicate the value that will be sent to the server if this option is selected.
 checked: Indicates that this option should be selected by default when the page loads.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 67
SZABIST jstc Shaheed Benazirabad
HTML Forms - Select box Control:
Drop Down Box is used when we have many options available to be selected but only one or two
will be selected..
Here is example HTML code for a form with one drop down box
<form action="/cgi-bin/dropdown.cgi" method="post">
<select name="dropdown">
<option value="Maths" selected>Maths</option>
<option value="Physics">Physics</option>
</select>
<input type="submit" value="Submit" />
</form>
Following is the list of important attributes of <select>:
 name: This is the name for the control.
 size: This can be used to present a scrolling list box.
 multiple: If set to "multiple" then allows a user to select multiple items from the menu.
Following is the list of important attributes of <option>:
 value: The value that is sent to the server if this option is selected.
 selected: Specifies that this option should be the initially selected value when the page
loads.
 label: An alternative way of labeling options.
HTML Forms - File Select Boxes:
If you want to allow a user to upload a file to your web site from his computer, you will need to
use a file upload box, also known as a file select box. This is also created using the <input>
element.
Here is example HTML code for a form with one file select box
<form action="/cgi-bin/hello_get.cgi" method="post"
name="fileupload" enctype="multipart/form-data">
<input type="file" name="fileupload" accept="image/*" />
</form>
HTML Forms - Hidden Controls:
If you will want to pass information between pages without the user seeing it. Hidden form
controls remain part of any form, but the user cannot see them in the Web browser. They should
not be used for any sensitive information you do not want the user to see because the user could
see this data if she looked in the source of the page.
Following hidden form is being used to keep current page number. When a user will click next
page then the value of hidden form will be sent to the back-end application and it will decide
which page has be displayed next.
<form action="/cgi-bin/hello_get.cgi"
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 68
SZABIST jstc Shaheed Benazirabad
method="get" name="pages">
<p>This is page 10</p>
<input type="hidden" name="pgaenumber" value="10" />
<input type="submit" value="Next Page" />
</form>
HTML Forms - Submit and Reset Button:
These are special buttons which can be created using <input> When submit button is clicked
then Forms data is submitted to the back-end application. When reset button is clicked then all
the forms control are reset to default state.
You already have seen submit button above, we will give one reset example here:
<form action="/cgi-bin/hello_get.cgi" method="get">
First name:
<input type="text" name="first_name" />
<br>
Last name:
<input type="text" name="last_name" />
<input type="submit" value="Submit" />
<input type="reset" value="Reset" />
</form>
Patterned & Transparent Backgrounds:
You might have seen many pattern or transparent backgrounds on various websites. This simply
can be achieved by using patterend image or transparent image in the background.
It is suggested that when creating patterns or transparent gifs, use the smallest dimensions
possible even as small as 1x1 if you can. Larger files load slow and inhibit the load time of your
sites.
Here are the examples to set background pattern of a table.
<!-- How to set a table background using pattrern -->
<table background="/images/pattern1.gif" width="100%" height="100">
<tr><td>
This background is filled up with a pattern image.
</td></tr>
</table>
<!-- Another example on table background using pattrern -->
<table background="/images/pattern2.gif" width="100%" height="100">
<tr><td>
This background is filled up with a pattern image.
</td></tr>
</table>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 69
SZABIST jstc Shaheed Benazirabad
HTML Uniform Resource Locators
A URL is another word for a web address.
A URL can be composed of words, such as "w3schools.com", or an Internet Protocol (IP)
address: 192.68.20.50. Most people enter the name of the website when surfing, because names
are easier to remember than numbers.
URL - Uniform Resource Locator
Web browsers request pages from web servers by using a URL.
When you click on a link in an HTML page, an underlying <a> tag points to an address on the
world wide web.
A Uniform Resource Locator (URL) is used to address a document (or other data) on the world
wide web.
A web address, like this: http://www.w3schools.com/html/default.asp follows these syntax rules:
scheme://host.domain:port/path/filename
Explanation:
 scheme - defines the type of Internet service. The most common type is http
 host - defines the domain host (the default host for http is www)
 domain - defines the Internet domain name, like w3schools.com
 port - defines the port number at the host (the default port number for http is 80)
 path - defines a path at the server (If omitted, the document must be stored at the root
directory of the web site)
 filename - defines the name of a document/resource
Common URL Schemes
The table below lists some common schemes:
Scheme
Short for....
Which pages will the scheme be used for...
Common web pages starts with http://. Not
http
HyperText Transfer Protocol
encrypted
Secure HyperText Transfer
Secure web pages. All information exchanged are
https
Protocol
encrypted
For downloading or uploading files to a website.
ftp
File Transfer Protocol
Useful for domain maintenance
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 70
SZABIST jstc Shaheed Benazirabad
File
A file on your computer
URL Encoding
URLs can only be sent over the Internet using the ASCII character-set.
Since URLs often contain characters outside the ASCII set, the URL has to be converted into a
valid ASCII format.
URL encoding converts characters into a format that can be transmitted over the Internet.
URL encoding replaces non ASCII characters with a "%" followed by two hexadecimal digits.
URLs cannot contain spaces. URL encoding normally replaces a space with a + sign.
URL Encoding Examples
Character URL-encoding
€
%80
£
%A3
©
%A9
®
%AE
À
%C0
Á
%C1
Â
%C2
Ã
%C3
Ä
%C4
Å
%C5
HTML Useful Character Entities
Note: Entity names are case sensitive!
Result Description
Entity Name Entity Number
non-breaking space  
 
<
less than
<
<
>
greater than
>
>
&
ampersand
&
&
¢
Cent
¢
¢
£
Pound
£
£
¥
Yen
¥
¥
€
Euro
€
€
§
Section
§
§
©
copyright
©
©
®
registered trademark ®
®
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 71
SZABIST jstc Shaheed Benazirabad
™
trademark
™
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 72
SZABIST jstc Shaheed Benazirabad
CSS Introduction
CSS Basic
What is CSS?





CSS stands for Cascading Style Sheets
Styles define how to display HTML elements
Styles were added to HTML 4.0 to solve a problem
External Style Sheets can save a lot of work
External Style Sheets are stored in CSS files
Styles Solved a Big Problem









HTML was never intended to contain tags for formatting a document.
HTML was intended to define the content of a document, like:
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
When tags like <font>, and color attributes were added to the HTML 3.2 specification, it
started a nightmare for web developers. Development of large web sites, where fonts and
color information were added to every single page, became a long and expensive process.
To solve this problem, the World Wide Web Consortium (W3C) created CSS.
In HTML 4.0, all formatting could be removed from the HTML document, and stored in
a separate CSS file.
All browsers support CSS today.
CSS Saves a Lot of Work!


CSS defines HOW HTML elements are to be displayed.
Styles are normally saved in external .css files. External style sheets enable you to change
the appearance and layout of all the pages in a Web site, just by editing one single file!
CSS Syntax
A CSS rule has two main parts: a selector, and one or more declarations:
The selector is normally the HTML element you want to style.
Each declaration consists of a property and a value.
The property is the style attribute you want to change. Each property has a value.
CSS Example
A CSS declaration always ends with a semicolon, and declaration groups are surrounded by
curly brackets:
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 73
SZABIST jstc Shaheed Benazirabad
p {color:red;text-align:center;}
To make the CSS more readable, you can put one declaration on each line, like this:
Example
p
{
color:red;
text-align:center;
}
CSS Comments
Comments are used to explain your code, and may help you when you edit the source code at a
later date. Comments are ignored by browsers.
A CSS comment begins with "/*", and ends with "*/", like this:
/*This is a comment*/
p
{
text-align:center;
/*This is another comment*/
color:black;
font-family:arial;
}
body
{
background-color:#d0e4fe;
}
h1
{
color:orange;
text-align:center;
}
p
{
font-family:"Times New Roman";
font-size:20px;
}
The id and class Selectors
In addition to setting a style for a HTML element, CSS allows you to specify your own selectors
called "id" and "class".
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 74
SZABIST jstc Shaheed Benazirabad
The id Selector
The id selector is used to specify a style for a single, unique element.
The id selector uses the id attribute of the HTML element, and is defined with a "#".
The style rule below will be applied to the element with id="para1":
Example
#para1
{
text-align:center;
color:red;
}
The class Selector
The class selector is used to specify a style for a group of elements. Unlike the id selector, the
class selector is most often used on several elements.
This allows you to set a particular style for many HTML elements with the same class.
The class selector uses the HTML class attribute, and is defined with a "."
In the example below, all HTML elements with class="center" will be center-aligned:
Example
.center {text-align:center;}
Three Ways to Insert CSS
There are three ways of inserting a style sheet:



External style sheet
Internal style sheet
Inline style
External Style Sheet
An external style sheet is ideal when the style is applied to many pages. With an external style
sheet, you can change the look of an entire Web site by changing one file. Each page must link to
the style sheet using the <link> tag. The <link> tag goes inside the head section:
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
An external style sheet can be written in any text editor. The file should not contain any html
tags. Your style sheet should be saved with a .css extension. An example of a style sheet file is
shown below:
hr {color:sienna;}
p {margin-left:20px;}
body {background-image:url("images/back40.gif");}
Do not add a space between the property value and the unit (such as margin-left:20 px). The
correct way is: margin-left:20px
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 75
SZABIST jstc Shaheed Benazirabad
Internal Style Sheet
An internal style sheet should be used when a single document has a unique style. You define
internal styles in the head section of an HTML page, by using the <style> tag, like this:
<head>
<style>
hr {color:sienna;}
p {margin-left:20px;}
body {background-image:url("images/back40.gif");}
</style>
</head>
Inline Styles
An inline style loses many of the advantages of style sheets by mixing content with presentation.
Use this method sparingly!
To use inline styles you use the style attribute in the relevant tag. The style attribute can contain
any CSS property. The example shows how to change the color and the left margin of a
paragraph:
<p style="color:sienna;margin-left:20px">This is a paragraph.</p>
Multiple Style Sheets
If some properties have been set for the same selector in different style sheets, the values will be
inherited from the more specific style sheet.
For example, an external style sheet has these properties for the h3 selector:
h3
{
color:red;
text-align:left;
font-size:8pt;
}
And an internal style sheet has these properties for the h3 selector:
h3
{
text-align:right;
font-size:20pt;
}
If the page with the internal style sheet also links to the external style sheet the properties for h3
will be:
color:red;
text-align:right;
font-size:20pt;
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 76
SZABIST jstc Shaheed Benazirabad
The color is inherited from the external style sheet and the text-alignment and the font-size is
replaced by the internal style sheet.
Multiple Styles Will Cascade into One
Styles can be specified:



inside an HTML element
inside the head section of an HTML page
in an external CSS file
Tip: Even multiple external style sheets can be referenced inside a single HTML document.
Cascading order
What style will be used when there is more than one style specified for an HTML element?
Generally speaking we can say that all the styles will "cascade" into a new "virtual" style sheet
by the following rules, where number four has the highest priority:
1.
2.
3.
4.
Browser default
External style sheet
Internal style sheet (in the head section)
Inline style (inside an HTML element)
So, an inline style (inside an HTML element) has the highest priority, which means that it will
override a style defined inside the <head> tag, or in an external style sheet, or in a browser (a
default value).
Note: If the link to the external style sheet is placed after the internal style sheet in HTML
<head>, the external style sheet will override the internal style sheet!
CSS Styling
CSS Background
CSS background properties are used to define the background effects of
an element.
CSS properties used for background effects:
 background-color
 background-image
 background-repeat
 background-attachment
 background-position
Background Color
The background-color property specifies the background color of an element.
The background color of a page is defined in the body selector:
Example
body {background-color:#b0c4de;}
With CSS, a color is most often specified by:



a HEX value - like "#ff0000"
an RGB value - like "rgb(255,0,0)"
a color name - like "red"
Look at CSS Color Values for a complete list of possible color values.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 77
SZABIST jstc Shaheed Benazirabad
In the example below, the h1, p, and div elements have different background colors:
Example
h1 {background-color:#6495ed;}
p {background-color:#e0ffff;}
div {background-color:#b0c4de;}
Background Image
The background-image property specifies an image to use as the background of an element.
By default, the image is repeated so it covers the entire element.
The background image for a page can be set like this:
Example
body {background-image:url('paper.gif');}
Below is an example of a bad combination of text and background image. The text is almost not
readable:
Example
body {background-image:url('bgdesert.jpg');}
Background Image - Repeat Horizontally or Vertically
By default, the background-image property repeats an image both horizontally and vertically.
Some images should be repeated only horizontally or vertically, or they will look strange, like
this:
Example
body
{
background-image:url('gradient2.png');
}
If the image is repeated only horizontally (repeat-x), the background will look better:
Example
body
{
background-image:url('gradient2.png');
background-repeat:repeat-x;
}
Background Image - Set position and no-repeat
When using a background image, use an image that does not disturb the text.
Showing the image only once is specified by the background-repeat property:
Example
body
{
background-image:url('img_tree.png');
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 78
SZABIST jstc Shaheed Benazirabad
background-repeat:no-repeat;
}
In the example above, the background image is shown in the same place as the text. We want to
change the position of the image, so that it does not disturb the text too much.
The position of the image is specified by the background-position property:
Example
body
{
background-image:url('img_tree.png');
background-repeat:no-repeat;
background-position:right top;
}
Background - Shorthand property
As you can see from the examples above, there are many properties to consider when dealing
with backgrounds.
To shorten the code, it is also possible to specify all the properties in one single property. This is
called a shorthand property.
The shorthand property for background is simply "background":
Example
body {background:#ffffff url('img_tree.png') no-repeat right top;}
When using the shorthand property the order of the property values is:
 background-color
 background-image
 background-repeat
 background-attachment
 background-position
It does not matter if one of the property values is missing, as long as the ones that are present are
in this order.
CSS Text
Text Color
The color property is used to set the color of the text.
With CSS, a color is most often specified by:



a HEX value - like "#ff0000"
an RGB value - like "rgb(255,0,0)"
a color name - like "red"
Look at CSS Color Values for a complete list of possible color values.
The default color for a page is defined in the body selector.
Example
body {color:blue;}
h1 {color:#00ff00;}
h2 {color:rgb(255,0,0);}
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 79
SZABIST jstc Shaheed Benazirabad
Text Alignment
The text-align property is used to set the horizontal alignment of a text.
Text can be centered, or aligned to the left or right, or justified.
When text-align is set to "justify", each line is stretched so that every line has equal width, and
the left and right margins are straight (like in magazines and newspapers).
Example
h1 {text-align:center;}
p.date {text-align:right;}
p.main {text-align:justify;}
Text Decoration
The text-decoration property is used to set or remove decorations from text.
The text-decoration property is mostly used to remove underlines from links for design purposes:
Example
a {text-decoration:none;}
It can also be used to decorate text:
Example
h1 {text-decoration:overline;}
h2 {text-decoration:line-through;}
h3 {text-decoration:underline;}
Text Transformation
The text-transform property is used to specify uppercase and lowercase letters in a text.
It can be used to turn everything into uppercase or lowercase letters, or capitalize the first letter
of each word.
Example
p.uppercase {text-transform:uppercase;}
p.lowercase {text-transform:lowercase;}
p.capitalize {text-transform:capitalize;}
Text Indentation
The text-indentation property is used to specify the indentation of the first line of a text.
Example
p {text-indent:50px;}
CSS Font
Font Family
The font family of a text is set with the font-family property.
The font-family property should hold several font names as a "fallback" system. If the browser
does not support the first font, it tries the next font.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 80
SZABIST jstc Shaheed Benazirabad
Start with the font you want, and end with a generic family, to let the browser pick a similar font
in the generic family, if no other fonts are available.
Note: If the name of a font family is more than one word, it must be in quotation marks, like
font-family: "Times New Roman".
More than one font family is specified in a comma-separated list:
Example
p{font-family:"Times New Roman", Times, serif;
Font Style
The font-style property is mostly used to specify italic text.
This property has three values:
 normal - The text is shown normally
 italic - The text is shown in italics
 oblique - The text is "leaning" (oblique is very similar to italic, but less supported)
Example
p.normal {font-style:normal;}
p.italic {font-style:italic;}
p.oblique {font-style:oblique;}
Font Size
The font-size property sets the size of the text.
Being able to manage the text size is important in web design. However, you should not use font
size adjustments to make paragraphs look like headings, or headings look like paragraphs.
Always use the proper HTML tags, like <h1> - <h6> for headings and <p> for paragraphs.
The font-size value can be an absolute, or relative size.
Absolute size:
 Sets the text to a specified size
 Does not allow a user to change the text size in all browsers (bad for accessibility
reasons)
 Absolute size is useful when the physical size of the output is known
Relative size:
 Sets the size relative to surrounding elements
 Allows a user to change the text size in browsers
If you do not specify a font size, the default size for normal text, like paragraphs, is 16px
(16px=1em).
Set Font Size With Pixels
Setting the text size with pixels gives you full control over the text size:
Example
h1 {font-size:40px;}
h2 {font-size:30px;}
p {font-size:14px;}
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 81
SZABIST jstc Shaheed Benazirabad
The example above allows Internet Explorer 9, Firefox, Chrome, Opera, and Safari to resize the
text.
Note: The example above does not work in IE, prior version 9.
The text can be resized in all browsers using the zoom tool (however, this resizes the entire page,
not just the text).
Set Font Size With Em
To avoid the resizing problem with older versions of Internet Explorer, many developers use em
instead of pixels.
The em size unit is recommended by the W3C.
1em is equal to the current font size. The default text size in browsers is 16px. So, the default
size of 1em is 16px.
The size can be calculated from pixels to em using this formula: pixels/16=em
Example
h1 {font-size:2.5em;} /* 40px/16=2.5em */
h2 {font-size:1.875em;} /* 30px/16=1.875em */
p {font-size:0.875em;} /* 14px/16=0.875em */
In the example above, the text size in em is the same as the previous example in pixels.
However, with the em size, it is possible to adjust the text size in all browsers.
Unfortunately, there is still a problem with older versions of IE. The text becomes larger than it
should when made larger, and smaller than it should when made smaller.
Use a Combination of Percent and Em
The solution that works in all browsers, is to set a default font-size in percent for the <body>
element:
Example
body {font-size:100%;}
h1 {font-size:2.5em;}
h2 {font-size:1.875em;}
p {font-size:0.875em;}
CSS Links
Styling Links
Links can be styled with any CSS property (e.g. color, font-family, background, etc.).
Special for links are that they can be styled differently depending on what state they are in.
The four links states are:
 a:link - a normal, unvisited link
 a:visited - a link the user has visited
 a:hover - a link when the user mouses over it
 a:active - a link the moment it is clicked
Example
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 82
SZABIST jstc Shaheed Benazirabad
a:link {color:#FF0000;}
/* unvisited link */
a:visited {color:#00FF00;} /* visited link */
a:hover {color:#FF00FF;} /* mouse over link */
a:active {color:#0000FF;} /* selected link */
When setting the style for several link states, there are some order rules:
 a:hover MUST come after a:link and a:visited
 a:active MUST come after a:hover
Common Link Styles
In the example above the link changes color depending on what state it is in.
Lets go through some of the other common ways to style links:
Text Decoration
The text-decoration property is mostly used to remove underlines from links:
Example
a:link {text-decoration:none;}
a:visited {text-decoration:none;}
a:hover {text-decoration:underline;}
a:active {text-decoration:underline;
Background Color
The background-color property specifies the background color for links:
Example
a:link {background-color:#B2FF99;}
a:visited {background-color:#FFFF85;}
a:hover {background-color:#FF704D;}
a:active {background-color:#FF704D;}
CSS Lists



The CSS list properties allow you to:
Set different list item markers for ordered lists
Set different list item markers for unordered lists
Set an image as the list item marker
List
In HTML, there are two types of lists:
 unordered lists - the list items are marked with bullets
 ordered lists - the list items are marked with numbers or letters
With CSS, lists can be styled further, and images can be used as the list item marker.
Different List Item Markers
The type of list item marker is specified with the list-style-type property:
Example
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 83
SZABIST jstc Shaheed Benazirabad
ul.a {list-style-type: circle;}
ul.b {list-style-type: square;}
ol.c {list-style-type: upper-roman;}
ol.d {list-style-type: lower-alpha;}
An Image as The List Item Marker
To specify an image as the list item marker, use the list-style-image property:
Example
ul
{
list-style-image: url('sqpurple.gif');
}
The example above does not display equally in all browsers. IE and Opera will display the
image-marker a little bit higher than Firefox, Chrome, and Safari.
If you want the image-marker to be placed equally in all browsers, a crossbrowser solution is
explained below.
Crossbrowser Solution
The following example displays the image-marker equally in all browsers:
Example
ul
{
list-style-type: none;
padding: 0px;
margin: 0px;
}
ul li
{
background-image: url(sqpurple.gif);
background-repeat: no-repeat;
background-position: 0px 5px;
padding-left: 14px;
}
Example explained:
 For ul:
o Set the list-style-type to none to remove the list item marker
o Set both padding and margin to 0px (for cross-browser compatibility)
 For all li in ul:
o Set the URL of the image, and show it only once (no-repeat)
o Position the image where you want it (left 0px and down 5px)
o Position the text in the list with padding-left
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 84
SZABIST jstc Shaheed Benazirabad
List - Shorthand property
It is also possible to specify all the list properties in one, single property. This is called a
shorthand property.
The shorthand property used for lists, is the list-style property:
Example
ul
{
list-style: square url("sqpurple.gif");
}
When using the shorthand property, the order of the values are:
 list-style-type
 list-style-position (for a description, see the CSS properties table below)
 list-style-image
It does not matter if one of the values above are missing, as long as the rest are in the specified
order.
CSS Tables
The look of an HTML table can be greatly improved with CSS:
Company
Contact
Country
Alfreds Futterkiste
Maria Anders
Germany
Berglunds snabbköp
Christina Berglund Sweden
Centro comercial Moctezuma Francisco Chang Mexico
Ernst Handel
Roland Mendel
Austria
Island Trading
Helen Bennett
UK
Königlich Essen
Philip Cramer
Germany
Laughing Bacchus Winecellars Yoshi Tannamuri Canada
Magazzini Alimentari Riuniti Giovanni Rovelli Italy
North/South
Simon Crowther UK
Paris spécialités
Marie Bertrand
France
The Big Cheese
Liz Nixon
USA
Vaffeljernet
Palle Ibsen
Denmark
Table Borders
To specify table borders in CSS, use the border property.
The example below specifies a black border for table, th, and td elements:
Example
table, th, td
{
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 85
SZABIST jstc Shaheed Benazirabad
border: 1px solid black;
}
Notice that the table in the example above has double borders. This is because both the table and
the th/td elements have separate borders.
To display a single border for the table, use the border-collapse property.
Collapse Borders
The border-collapse property sets whether the table borders are collapsed into a single border or
separated:
Example
table
{
border-collapse:collapse;
}
table,th, td
{
border: 1px solid black;
}
Table Width and Height
Width and height of a table is defined by the width and height properties.
The example below sets the width of the table to 100%, and the height of the th elements to
50px:
Example
table
{
width:100%;
}
th
{
height:50px;
}
Table Text Alignment
The text in a table is aligned with the text-align and vertical-align properties.
The text-align property sets the horizontal alignment, like left, right, or center:
Example
td
{
text-align:right;
}
The vertical-align property sets the vertical alignment, like top, bottom, or middle:
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 86
SZABIST jstc Shaheed Benazirabad
Example
td
{
height:50px;
vertical-align:bottom;
}
Table Padding
To control the space between the border and content in a table, use the padding property on td
and th elements:
Example
td
{
padding:15px;
}
Table Color
The example below specifies the color of the borders, and the text and background color of th
elements:
Example
table, td, th
{
border:1px solid green;
}
th
{
background-color:green;
color:white;
}
CSS Box Model
The CSS Box Model
All HTML elements can be considered as boxes. In CSS, the term "box model" is used when
talking about design and layout.
The CSS box model is essentially a box that wraps around HTML elements, and it consists of:
margins, borders, padding, and the actual content.
The box model allows us to place a border around elements and space elements in relation to
other elements.
The image below illustrates the box model:
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 87
SZABIST jstc Shaheed Benazirabad
Explanation of the different parts:
 Margin - Clears an area around the border. The margin does not have a background
color, it is completely transparent
 Border - A border that goes around the padding and content. The border is affected by
the background color of the box
 Padding - Clears an area around the content. The padding is affected by the background
color of the box
 Content - The content of the box, where text and images appear
In order to set the width and height of an element correctly in all browsers, you need to know
how the box model works.
Width and Height of an Element
Important: When you set the width and height properties of an element with CSS, you just
set the width and height of the content area. To calculate the full size of an element, you must
also add the padding, borders and margins.
The total width of the element in the example below is 300px:
width:250px;
padding:10px;
border:5px solid gray;
margin:10px;
Let's do the math:
250px (width)
+ 20px (left + right padding)
+ 10px (left + right border)
+ 20px (left + right margin)
= 300px
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 88
SZABIST jstc Shaheed Benazirabad
Assume that you had only 250px of space. Let's make an element with a total width of 250px:
Example
width:220px;
padding:10px;
border:5px solid gray;
margin:0px;
The total width of an element should be calculated like this:
Total element width = width + left padding + right padding + left border + right border + left
margin + right margin
The total height of an element should be calculated like this:
Total element height = height + top padding + bottom padding + top border + bottom border +
top margin + bottom margin
Browsers Compatibility Issue
IE8 and earlier versions of IE, included padding and border in the width property.
To fix this problem, add a <!DOCTYPE html> to the HTML page.
CSS Border
Border Style
border-style values:
Border Width
The border-width property is used to set the width of the border.
The width is set in pixels, or by using one of the three pre-defined values: thin, medium, or thick.
Note: The "border-width" property does not work if it is used alone. Use the "border-style"
property to set the borders first.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 89
SZABIST jstc Shaheed Benazirabad
Example
p.one
{
border-style:solid;
border-width:5px;
}
p.two
{
border-style:solid;
border-width:medium;
}
Border Color
The border-color property is used to set the color of the border. The color can be set by:
 name - specify a color name, like "red"
 RGB - specify a RGB value, like "rgb(255,0,0)"
 Hex - specify a hex value, like "#ff0000"
You can also set the border color to "transparent".
Note: The "border-color" property does not work if it is used alone. Use the "border-style"
property to set the borders first.
Example
p.one
{
border-style:solid;
border-color:red;
}
p.two
{
border-style:solid;
border-color:#98bf21;
}
Border - Individual sides
In CSS it is possible to specify different borders for different sides:
Example
p
{
border-top-style:dotted;
border-right-style:solid;
border-bottom-style:dotted;
border-left-style:solid;
}
The example above can also be set with a single property:
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 90
SZABIST jstc Shaheed Benazirabad
Example
border-style:dotted solid;
The border-style property can have from one to four values.
 border-style:dotted solid double dashed;
o top border is dotted
o right border is solid
o bottom border is double
o left border is dashed

border-style:dotted solid double;
o top border is dotted
o right and left borders are solid
o bottom border is double

border-style:dotted solid;
o top and bottom borders are dotted
o right and left borders are solid

border-style:dotted;
o all four borders are dotted
The border-style property is used in the example above. However, it also works with borderwidth and border-color.
Border - Shorthand property
As you can see from the examples above, there are many properties to consider when dealing
with borders.
To shorten the code, it is also possible to specify all the individual border properties in one
property. This is called a shorthand property.
The border property is a shorthand for the following individual border properties:
 border-width
 border-style (required)
 border-color
Example
border:5px solid red;
CSS Outlines
CSS Outline
An outline is a line that is drawn around elements (outside the borders) to make the element
"stand out".
However, the outline property is different from the border property.
The outline is not a part of an element's dimensions; the element's total width and height is not
affected by the width of the outline.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 91
SZABIST jstc Shaheed Benazirabad
All CSS Outline Properties
The number in the "CSS" column indicates in which CSS version the property is defined (CSS1
or CSS2).
Property
outline
outline-color
outline-style
outline-width
Description
Values
outline-color
outline-style
Sets all the outline properties in one declaration
outline-width
inherit
color_name
hex_number
Sets the color of an outline
rgb_number
invert
inherit
none
dotted
dashed
solid
double
Sets the style of an outline
groove
ridge
inset
outset
inherit
thin
medium
Sets the width of an outline
thick
length
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
CSS
2
2
2
2
Page 92
SZABIST jstc Shaheed Benazirabad
inherit
CSS Margin
Margin
The margin clears an area around an element (outside the border). The margin does not have a
background color, and is completely transparent.
The top, right, bottom, and left margin can be changed independently using separate properties.
A shorthand margin property can also be used, to change all margins at once.
Possible Values
Value Description
auto The browser calculates a margin
length Specifies a margin in px, pt, cm, etc. Default value is 0px
%
Specifies a margin in percent of the width of the containing element
inherit Specifies that the margin should be inherited from the parent element
It is possible to use negative values, to overlap content.
Margin - Individual sides
In CSS, it is possible to specify different margins for different sides:
Example
margin-top:100px;
margin-bottom:100px;
margin-right:50px;
margin-left:50px;
Margin - Shorthand property
To shorten the code, it is possible to specify all the margin properties in one property. This is
called a shorthand property.
The shorthand property for all the margin properties is "margin":
Example
margin:100px 50px;
The margin property can have from one to four values.
 margin:25px 50px 75px 100px;
o top margin is 25px
o right margin is 50px
o bottom margin is 75px
o left margin is 100px

margin:25px 50px 75px;
o top margin is 25px
o right and left margins are 50px
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 93
SZABIST jstc Shaheed Benazirabad
o
bottom margin is 75px

margin:25px 50px;
o top and bottom margins are 25px
o right and left margins are 50px

margin:25px;
o all four margins are 25px
CSS Padding
Padding
The padding clears an area around the content (inside the border) of an element. The padding is
affected by the background color of the element.
The top, right, bottom, and left padding can be changed independently using separate properties.
A shorthand padding property can also be used, to change all paddings at once.
Possible Values
Value Description
length Defines a fixed padding (in pixels, pt, em, etc.)
%
Defines a padding in % of the containing element
Padding - Individual sides
In CSS, it is possible to specify different padding for different sides:
Example
padding-top:25px;
padding-bottom:25px;
padding-right:50px;
padding-left:50px;
Padding - Shorthand property
To shorten the code, it is possible to specify all the padding properties in one property. This is
called a shorthand property.
The shorthand property for all the padding properties is "padding":
Example
padding:25px 50px;
The padding property can have from one to four values.
 padding:25px 50px 75px 100px;
o top padding is 25px
o right padding is 50px
o bottom padding is 75px
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 94
SZABIST jstc Shaheed Benazirabad
o
left padding is 100px

padding:25px 50px 75px;
o top padding is 25px
o right and left paddings are 50px
o bottom padding is 75px

padding:25px 50px;
o top and bottom paddings are 25px
o right and left paddings are 50px

padding:25px;
o all four paddings are 25px
CSS Advanced
CSS Grouping and Nesting Selectors
Grouping Selectors
In style sheets there are often elements with the same style.
h1
{
color:green;
}
h2
{
color:green;
}
p
{
color:green;
}
To minimize the code, you can group selectors.
Separate each selector with a comma.
In the example below we have grouped the selectors from the code above:
Example
h1,h2,p
{
color:green;
}
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 95
SZABIST jstc Shaheed Benazirabad
Nesting Selectors
It is possible to apply a style for a selector within a selector.
In the example below, one style is specified for all p elements, one style is specified for all
elements with class="marked", and a third style is specified only for p elements within elements
with class="marked":
Example
p
{
color:blue;
text-align:center;
}
.marked
{
background-color:red;
}
.marked p
{
color:white;
}
CSS Display and Visibility
Hiding an Element - display:none or visibility:hidden
h1.hidden {visibility:hidden;}
display:none hides an element, and it will not take up any space. The element will be hidden, and the
page will be displayed as if the element is not there
Example
h1.hidden {display:none;}
CSS Display - Block and Inline Elements
A block element is an element that takes up the full width available, and has a line break before
and after it.
Examples of block elements:
 <h1>
 <p>
 <div>
An inline element only takes up as much width as necessary, and does not force line breaks.
Examples of inline elements:
 <span>
 <a>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 96
SZABIST jstc Shaheed Benazirabad
Changing How an Element is Displayed
Changing an inline element to a block element, or vice versa, can be useful for making the page
look a specific way, and still follow web standards.
The following example displays list items as inline elements:
Example
li {display:inline;}
The following example displays span elements as block elements:
Example
span {display:block;}
CSS Positioning
Positioning
The CSS positioning properties allow you to position an element. It can also place an element
behind another, and specify what should happen when an element's content is too big.
Elements can be positioned using the top, bottom, left, and right properties. However, these
properties will not work unless the position property is set first. They also work differently
depending on the positioning method.
There are four different positioning methods.
Static Positioning
HTML elements are positioned static by default. A static positioned element is always positioned
according to the normal flow of the page.
Static positioned elements are not affected by the top, bottom, left, and right properties.
Fixed Positioning
An element with fixed position is positioned relative to the browser window.
It will not move even if the window is scrolled:
Example
p.pos_fixed
{
position:fixed;
top:30px;
right:5px;
}
Note: IE7 and IE8 support the fixed value only if a !DOCTYPE is specified.
Fixed positioned elements are removed from the normal flow. The document and other elements
behave like the fixed positioned element does not exist.
Fixed positioned elements can overlap other elements.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 97
SZABIST jstc Shaheed Benazirabad
Relative Positioning
A relative positioned element is positioned relative to its normal position.
Example
h2.pos_left
{
position:relative;
left:-20px;
}
h2.pos_right
{
position:relative;
left:20px;
}
The content of relatively positioned elements can be moved and overlap other elements, but the
reserved space for the element is still preserved in the normal flow.
Example
h2.pos_top
{
position:relative;
top:-50px;
}
Relatively positioned elements are often used as container blocks for absolutely positioned
elements.
Absolute Positioning
An absolute position element is positioned relative to the first parent element that has a position
other than static. If no such element is found, the containing block is <html>:
Example
h2
{
position:absolute;
left:100px;
top:150px;
}
Absolutely positioned elements are removed from the normal flow. The document and other
elements behave like the absolutely positioned element does not exist.
Absolutely positioned elements can overlap other elements.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 98
SZABIST jstc Shaheed Benazirabad
Overlapping Elements
When elements are positioned outside the normal flow, they can overlap other elements.
The z-index property specifies the stack order of an element (which element should be placed in
front of, or behind, the others).
An element can have a positive or negative stack order:
Example
img
{
position:absolute;
left:0px;
top:0px;
z-index:-1;
}
All CSS Positioning Properties
The number in the "CSS" column indicates in which CSS version the property is defined (CSS1
or CSS2).
Property
bottom
clip
cursor
left
Description
Values
auto
Sets the bottom margin edge for a
length
positioned box
%
inherit
shape
Clips an absolutely positioned element
auto
inherit
url
auto
crosshair
default
pointer
move
e-resize
ne-resize
Specifies the type of cursor to be displayed nw-resize
n-resize
se-resize
sw-resize
s-resize
w-resize
text
wait
help
Sets the left margin edge for a positioned auto
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
CSS
2
2
2
2
Page 99
SZABIST jstc Shaheed Benazirabad
box
overflow
position
right
top
z-index
length
%
inherit
auto
hidden
Specifies what happens if content overflows
scroll
an element's box
visible
inherit
absolute
fixed
Specifies the type of positioning for an
relative
element
static
inherit
auto
Sets the right margin edge for a positioned length
box
%
inherit
auto
Sets the top margin edge for a positioned length
box
%
inherit
number
Sets the stack order of an element
auto
inherit
2
2
2
2
2
What is CSS Float?
With CSS float, an element can be pushed to the left or right, allowing other elements to wrap
around it.
Float is very often used for images, but it is also useful when working with layouts.
How Elements Float
Elements are floated horizontally, this means that an element can only be floated left or right, not
up or down.
A floated element will move as far to the left or right as it can. Usually this means all the way to
the left or right of the containing element.
The elements after the floating element will flow around it.
The elements before the floating element will not be affected.
If an image is floated to the right, a following text flows around it, to the left:
Example
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 100
SZABIST jstc Shaheed Benazirabad
img
{
float:right;
}
Floating Elements Next to Each Other
If you place several floating elements after each other, they will float next to each other if there
is room.
Here we have made an image gallery using the float property:
Example
.thumbnail
{
float:left;
width:110px;
height:90px;
margin:5px;
}
Turning off Float - Using Clear
Elements after the floating element will flow around it. To avoid this, use the clear property.
The clear property specifies which sides of an element other floating elements are not allowed.
Add a text line into the image gallery, using the clear property:
Example
.text_line
{
clear:both;
}
All CSS Float Properties
The number in the "CSS" column indicates in which CSS version the property is defined (CSS1
or CSS2).
Property
clear
float
Description
Values
left
right
Specifies which sides of an element where
both
other floating elements are not allowed
none
inherit
left
right
Specifies whether or not a box should float
none
inherit
CSS
1
CSS Horizontal Align
Aligning Block Elements
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 101
SZABIST jstc Shaheed Benazirabad
A block element is an element that takes up the full width available, and has a line break before
and after it.
Examples of block elements:



<h1>
<p>
<div>
For aligning text, see the CSS Text chapter.
In this chapter we will show you how to horizontally align block elements for layout purposes.
Center Aligning Using the margin Property
Block elements can be aligned by setting the left and right margins to "auto".
Note: Using margin:auto will not work in IE8 and earlier, unless a !DOCTYPE is declared.
Setting the left and right margins to auto specifies that they should split the available margin
equally. The result is a centered element:
Example
.center
{
margin-left:auto;
margin-right:auto;
width:70%;
background-color:#b0e0e6;
}
Left and Right Aligning Using the position Property
One method of aligning elements is to use absolute positioning:
Example
.right
{
position:absolute;
right:0px;
width:300px;
background-color:#b0e0e6;
}
Crossbrowser Compatibility Issues
When aligning elements like this, it is always a good idea to predefine margin and padding for
the <body> element. This is to avoid visual differences in different browsers.
There is a problem with IE8 and earlier, when using the position property. If a container element
(in our case <div class="container">) has a specified width, and the !DOCTYPE declaration is
missing, IE8 and earlier versions will add a 17px margin on the right side. This seems to be
space reserved for a scrollbar. Always set the !DOCTYPE declaration when using the position
property:
Example
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 102
SZABIST jstc Shaheed Benazirabad
body
{
margin:0;
padding:0;
}
.container
{
position:relative;
width:100%;
}
.right
{
position:absolute;
right:0px;
width:300px;
background-color:#b0e0e6;
}
Left and Right Aligning Using the float Property
One method of aligning elements is to use the float property:
Example
.right
{
float:right;
width:300px;
background-color:#b0e0e6;
}
Crossbrowser Compatibility Issues
When aligning elements like this, it is always a good idea to predefine margin and padding for
the <body> element. This is to avoid visual differences in different browsers.
There is a problem with IE8 and earlier when using the float property. If the !DOCTYPE
declaration is missing, IE8 and earlier versions will add a 17px margin on the right side. This
seems to be space reserved for a scrollbar. Always set the !DOCTYPE declaration when using
the float property:
Example
body
{
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 103
SZABIST jstc Shaheed Benazirabad
margin:0;
padding:0;
}
.right
{
float:right;
width:300px;
background-color:#b0e0e6;
}
CSS Pseudo-classes
Syntax
The syntax of pseudo-classes:
selector:pseudo-class {property:value;}
CSS classes can also be used with pseudo-classes:
selector.class:pseudo-class {property:value;}
Anchor Pseudo-classes
Links can be displayed in different ways in a CSS-supporting browser:
Example
a:link {color:#FF0000;}
/* unvisited link */
a:visited {color:#00FF00;} /* visited link */
a:hover {color:#FF00FF;} /* mouse over link */
a:active {color:#0000FF;} /* selected link */
Note: a:hover MUST come after a:link and a:visited in the CSS definition in order to be
effective!!
Note: a:active MUST come after a:hover in the CSS definition in order to be effective!!
Note: Pseudo-class names are not case-sensitive.
Pseudo-classes and CSS Classes
Pseudo-classes can be combined with CSS classes:
a.red:visited {color:#FF0000;}
<a class="red" href="css_syntax.asp">CSS Syntax</a>
If the link in the example above has been visited, it will be displayed in red.
CSS - The :first-child Pseudo-class
The :first-child pseudo-class matches a specified element that is the first child of another
element.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 104
SZABIST jstc Shaheed Benazirabad
Note: For :first-child to work in IE8 and earlier, a <!DOCTYPE> must be declared.
Match the first <p> element
In the following example, the selector matches any <p> element that is the first child of any
element:
Example
<html>
<head>
<style>
p:first-child
{
color:blue;
}
</style>
</head>
<body>
<p>I am a strong man.</p>
<p>I am a strong man.</p>
</body>
</html>
Match the first <i> element in all <p> elements
In the following example, the selector matches the first <i> element in all <p> elements:
Example
<html>
<head>
<style>
p > i:first-child
{
color:blue;
}
</style>
</head>
<body>
<p>I am a <i>strong</i> man. I am a <i>strong</i> man.</p>
<p>I am a <i>strong</i> man. I am a <i>strong</i> man.</p>
</body>
</html>
Match all <i> elements in all first child <p> elements
In the following example, the selector matches all <i> elements in <p> elements that are the first
child of another element:
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 105
SZABIST jstc Shaheed Benazirabad
Example
<html>
<head>
<style>
p:first-child i
{
color:blue;
}
</style>
</head>
<body>
<p>I am a <i>strong</i> man. I am a <i>strong</i> man.</p>
<p>I am a <i>strong</i> man. I am a <i>strong</i> man.</p>
</body>
</html>
CSS - The :lang Pseudo-class
The :lang pseudo-class allows you to define special rules for different languages.
Note: IE8 supports the :lang pseudo-class only if a <!DOCTYPE> is specified.
In the example below, the :lang class defines the quotation marks for q elements with lang="no":
Example
<html>
<head>
<style>
q:lang(no) {quotes: "~" "~";}
</style>
</head>
<body>
<p>Some text <q lang="no">A quote in a paragraph</q> Some text.</p>
</body>
</html>
All CSS Pseudo Classes/Elements
Selector
:link
:visited
:active
:hover
:focus
:first-letter
Example
a:link
a:visited
a:active
a:hover
input:focus
p:first-letter
Example description
Selects all unvisited links
Selects all visited links
Selects the active link
Selects links on mouse over
Selects the input element which has focus
Selects the first letter of every <p> element
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 106
SZABIST jstc Shaheed Benazirabad
:first-line
:first-child
:before
:after
p:first-line
p:first-child
p:before
p:after
:lang(language)
p:lang(it)
Selects the first line of every <p> element
Selects every <p> elements that is the first child of its parent
Insert content before every <p> element
Insert content after every <p> element
Selects every <p> element with a lang attribute value starting
with "it"
CSS Pseudo-elements
CSS pseudo-elements are used to add special effects to some selectors.
Syntax
The syntax of pseudo-elements:
selector:pseudo-element {property:value;}
CSS classes can also be used with pseudo-elements:
selector.class:pseudo-element {property:value;}
The :first-line Pseudo-element
The "first-line" pseudo-element is used to add a special style to the first line of a text.
In the following example the browser formats the first line of text in a p element according to the
style in the "first-line" pseudo-element (where the browser breaks the line, depends on the size of
the browser window):
Example
p:first-line
{
color:#ff0000;
font-variant:small-caps;
}
Note: The "first-line" pseudo-element can only be used with block-level elements.
Note: The following properties apply to the "first-line" pseudo-element:
 font properties
 color properties
 background properties
 word-spacing
 letter-spacing
 text-decoration
 vertical-align
 text-transform
 line-height
 clear
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 107
SZABIST jstc Shaheed Benazirabad
The :first-letter Pseudo-element
The "first-letter" pseudo-element is used to add a special style to the first letter of a text:
Example
p:first-letter
{
color:#ff0000;
font-size:xx-large;
}
Note: The "first-letter" pseudo-element can only be used with block-level elements.
Note: The following properties apply to the "first-letter" pseudo- element:
 font properties
 color properties
 background properties
 margin properties
 padding properties
 border properties
 text-decoration
 vertical-align (only if "float" is "none")
 text-transform
 line-height
 float
 clear
Pseudo-elements and CSS Classes
Pseudo-elements can be combined with CSS classes:
p.article:first-letter {color:#ff0000;}
<p class="article">A paragraph in an article</p>
The example above will display the first letter of all paragraphs with class="article", in red.
Multiple Pseudo-elements
Several pseudo-elements can also be combined.
In the following example, the first letter of a paragraph will be red, in an xx-large font size. The
rest of the first line will be blue, and in small-caps. The rest of the paragraph will be the default
font size and color:
Example
p:first-letter
{
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 108
SZABIST jstc Shaheed Benazirabad
color:#ff0000;
font-size:xx-large;
}
p:first-line
{
color:#0000ff;
font-variant:small-caps;
}
CSS - The :before Pseudo-element
The ":before" pseudo-element can be used to insert some content before the content of an
element.
The following example inserts an image before each <h1> element:
Example
h1:before
{
content:url(smiley.gif);
}
CSS - The :after Pseudo-element
The ":after" pseudo-element can be used to insert some content after the content of an element.
The following example inserts an image after each <h1> element:
Example
h1:after
{
content:url(smiley.gif);
}
All CSS Pseudo Classes/Elements
Selector
:link
:visited
:active
:hover
:focus
:first-letter
:first-line
:first-child
:before
:after
Example
a:link
a:visited
a:active
a:hover
input:focus
p:first-letter
p:first-line
p:first-child
p:before
p:after
:lang(language)
p:lang(it)
Example description
Selects all unvisited links
Selects all visited links
Selects the active link
Selects links on mouse over
Selects the input element which has focus
Selects the first letter of every <p> element
Selects the first line of every <p> element
Selects every <p> elements that is the first child of its parent
Insert content before every <p> element
Insert content after every <p> element
Selects every <p> element with a lang attribute value starting
with "it"
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 109
SZABIST jstc Shaheed Benazirabad
Navigation Bars
Having easy-to-use navigation is important for any web site.
With CSS you can transform boring HTML menus into good-looking navigation bars.
Navigation Bar = List of Links
A navigation bar needs standard HTML as a base.
In our examples we will build the navigation bar from a standard HTML list.
A navigation bar is basically a list of links, so using the <ul> and <li> elements makes perfect
sense:
Example
<ul>
<li><a href="default.asp">Home</a></li>
<li><a href="news.asp">News</a></li>
<li><a href="contact.asp">Contact</a></li>
<li><a href="about.asp">About</a></li>
</ul>
Now let's remove the bullets and the margins and padding from the list:
Example
ul
{
list-style-type:none;
margin:0;
padding:0;
}
Example explained:
 list-style-type:none - Removes the bullets. A navigation bar does not need list markers
 Setting margins and padding to 0 to remove browser default settings
The code in the example above is the standard code used in both vertical, and horizontal
navigation bars.
Vertical Navigation Bar
To build a vertical navigation bar we only need to style the <a> elements, in addition to the code
above:
Example
a
{
display:block;
width:60px;
}
Example explained:
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 110
SZABIST jstc Shaheed Benazirabad


display:block - Displaying the links as block elements makes the whole link area clickable (not
just the text), and it allows us to specify the width
width:60px - Block elements take up the full width available by default. We want to specify a 60
px width
Tip: Also take a look at our fully styled vertical navigation bar example.
Note: Always specify the width for <a> elements in a vertical navigation bar. If you omit the
width, IE6 can produce unexpected results.
Horizontal Navigation Bar
There are two ways to create a horizontal navigation bar. Using inline or floating list items.
Both methods work fine, but if you want the links to be the same size, you have to use the
floating method.
Inline List Items
One way to build a horizontal navigation bar is to specify the <li> elements as inline, in addition
to the "standard" code above:
Example
li
{
display:inline;
}
Example explained:

display:inline; - By default, <li> elements are block elements. Here, we remove the line breaks
before and after each list item, to display them on one line
Tip: Also take a look at our fully styled horizontal navigation bar example.
Floating List Items
In the example above the links have different widths.
For all the links to have an equal width, float the <li> elements and specify a width for the <a>
elements:
Example
li
{
float:left;
}
a
{
display:block;
width:60px;
}
Example explained:
 float:left - use float to get block elements to slide next to each other
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 111
SZABIST jstc Shaheed Benazirabad


display:block - Displaying the links as block elements makes the whole link area
clickable (not just the text), and it allows us to specify the width
width:60px - Since block elements take up the full width available, they cannot float next
to each other. We specify the width of the links to 60px
Image Gallery
The following image gallery is created with CSS:
Example
<html>
<head>
<style>
div.img
{
margin:2px;
border:1px solid #0000ff;
height:auto;
width:auto;
float:left;
text-align:center;
}
div.img img
{
display:inline;
margin:3px;
border:1px solid #ffffff;
}
div.img a:hover img
{
border:1px solid #0000ff;
}
div.desc
{
text-align:center;
font-weight:normal;
width:120px;
margin:2px;
}
</style>
</head>
<body>
<div class="img">
<a target="_blank" href="klematis_big.htm">
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 112
SZABIST jstc Shaheed Benazirabad
<img src="klematis_small.jpg" alt="Klematis" width="110" height="90">
</a>
<div class="desc">Add a description of the image here</div>
</div>
<div class="img">
<a target="_blank" href="klematis2_big.htm">
<img src="klematis2_small.jpg" alt="Klematis" width="110" height="90">
</a>
<div class="desc">Add a description of the image here</div>
</div>
<div class="img">
<a target="_blank" href="klematis3_big.htm">
<img src="klematis3_small.jpg" alt="Klematis" width="110" height="90">
</a>
<div class="desc">Add a description of the image here</div>
</div>
<div class="img">
<a target="_blank" href="klematis4_big.htm">
<img src="klematis4_small.jpg" alt="Klematis" width="110" height="90">
</a>
<div class="desc">Add a description of the image here</div>
</div>
</body>
</html>
CSS Image Opacity / Transparency
Creating a Transparent Image
The CSS3 property for transparency is opacity.
First we will show you how to create a transparent image with CSS.
Regular image:
The same image with transparency:
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 113
SZABIST jstc Shaheed Benazirabad
Look at the following CSS:
img
{
opacity:0.4;
filter:alpha(opacity=40); /* For IE8 and earlier */
}
IE9, Firefox, Chrome, Opera, and Safari use the property opacity for transparency. The opacity
property can take a value from 0.0 - 1.0. A lower value makes the element more transparent.
IE8 and earlier use filter:alpha(opacity=x). The x can take a value from 0 - 100. A lower value
makes the element more transparent.
Example 2 - Image Transparency - Hover Effect
Mouse over the images:
The CSS looks like this:
img
{
opacity:0.4;
filter:alpha(opacity=40); /* For IE8 and earlier */
}
img:hover
{
opacity:1.0;
filter:alpha(opacity=100); /* For IE8 and earlier */
}
The first CSS block is similar to the code in Example 1. In addition, we have added what should
happen when a user hover over one of the images. In this case we want the image to NOT be
transparent when the user hover over it.
The CSS for this is: opacity=1.
IE8 and earlier: filter:alpha(opacity=100).
When the mouse pointer moves away from the image, the image will be transparent again.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 114
SZABIST jstc Shaheed Benazirabad
Example 3 - Text in Transparent Box
This is some text that is placed in the transparent box. This is some text that is placed in the
transparent box. This is some text that is placed in the transparent box. This is some text that is
placed in the transparent box. This is some text that is placed in the transparent box.
The source code looks like this:
<html>
<head>
<style>
div.background
{
width:500px;
height:250px;
background:url(klematis.jpg) repeat;
border:2px solid black;
}
div.transbox
{
width:400px;
height:180px;
margin:30px 50px;
background-color:#ffffff;
border:1px solid black;
opacity:0.6;
filter:alpha(opacity=60); /* For IE8 and earlier */
}
div.transbox p
{
margin:30px 40px;
font-weight:bold;
color:#000000;
}
</style>
</head>
<body>
<div class="background">
<div class="transbox">
<p>This is some text that is placed in the transparent box.
This is some text that is placed in the transparent box.
This is some text that is placed in the transparent box.
This is some text that is placed in the transparent box.
This is some text that is placed in the transparent box.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 115
SZABIST jstc Shaheed Benazirabad
</p>
</div>
</div>
</body>
</html>
First, we create a div element (class="background") with a fixed height and width, a background
image, and a border. Then we create a smaller div (class="transbox") inside the first div element.
The "transbox" div have a fixed width, a background color, and a border - and it is transparent.
Inside the transparent div, we add some text inside a p element.
CSS Attribute Selectors
Style HTML Elements With Specific Attributes
It is possible to style HTML elements that have specific attributes, not just class and id.
Note: IE7 and IE8 support attribute selectors only if a !DOCTYPE is specified. Attribute
selection is NOT supported in IE6 and lower.
Attribute Selector
The example below styles all elements with a title attribute:
Example
[title]
{
color:blue;
}
Attribute and Value Selector
The example below styles all elements with title="W3Schools":
Example
[title=W3Schools]
{
border:5px solid green;
}
Attribute and Value Selector - Multiple Values
The example below styles all elements with a title attribute that contains a specified value. This
works even if the attribute has space separated values:
Example
[title~=hello] { color:blue; }
The example below styles all elements with a lang attribute that contains a specified value. This
works even if the attribute has hyphen ( - ) separated values:
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 116
SZABIST jstc Shaheed Benazirabad
Example
[lang|=en] { color:blue; }
Styling Forms
The attribute selectors are particularly useful for styling forms without class or ID:
Example
input[type="text"]
{
width:150px;
display:block;
margin-bottom:10px;
background-color:yellow;
}
input[type="button"]
{
width:120px;
margin-left:35px;
display:block;
}
CSS Selectors
In CSS, selectors are patterns used to select the element(s) you want to style.
The "CSS" column indicates in which CSS version the property is defined (CSS1, CSS2, or
CSS3).
Selector
.class
#id
*
element
element,element
element element
Example
.intro
#firstname
*
p
div,p
div p
element>element
div>p
element+element
div+p
[attribute]
[attribute=value]
[target]
[target=_blank]
[attribute~=value]
[title~=flower]
[attribute|=value]
[lang|=en]
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Example description
Selects all elements with class="intro"
Selects the element with id="firstname"
Selects all elements
Selects all <p> elements
Selects all <div> elements and all <p> elements
Selects all <p> elements inside <div> elements
Selects all <p> elements where the parent is a <div>
element
Selects all <p> elements that are placed immediately
after <div> elements
Selects all elements with a target attribute
Selects all elements with target="_blank"
Selects all elements with a title attribute containing the
word "flower"
Selects all elements with a lang attribute value starting
with "en"
CSS
1
1
2
1
1
1
2
2
2
2
2
2
Page 117
SZABIST jstc Shaheed Benazirabad
:link
:visited
:active
:hover
:focus
:first-letter
:first-line
a:link
a:visited
a:active
a:hover
input:focus
p:first-letter
p:first-line
Selects all unvisited links
Selects all visited links
Selects the active link
Selects links on mouse over
Selects the input element which has focus
Selects the first letter of every <p> element
Selects the first line of every <p> element
Selects every <p> element that is the first child of its
:first-child
p:first-child
parent
:before
p:before
Insert content before the content of every <p> element
:after
p:after
Insert content after every <p> element
Selects every <p> element with a lang attribute equal to
:lang(language)
p:lang(it)
"it" (Italian)
Selects every <ul> element that are preceded by a <p>
element1~element2 p~ul
element
Selects every <a> element whose src attribute value
[attribute^=value]
a[src^="https"]
begins with "https"
Selects every <a> element whose src attribute value
[attribute$=value]
a[src$=".pdf"]
ends with ".pdf"
Selects every <a> element whose src attribute value
[attribute*=value]
a[src*="w3schools"]
contains the substring "w3schools"
Selects every <p> element that is the first <p> element
:first-of-type
p:first-of-type
of its parent
Selects every <p> element that is the last <p> element of
:last-of-type
p:last-of-type
its parent
Selects every <p> element that is the only <p> element
:only-of-type
p:only-of-type
of its parent
Selects every <p> element that is the only child of its
:only-child
p:only-child
parent
Selects every <p> element that is the second child of its
:nth-child(n)
p:nth-child(2)
parent
Selects every <p> element that is the second child of its
:nth-last-child(n)
p:nth-last-child(2)
parent, counting from the last child
Selects every <p> element that is the second <p>
:nth-of-type(n)
p:nth-of-type(2)
element of its parent
Selects every <p> element that is the second <p>
:nth-last-of-type(n) p:nth-last-of-type(2)
element of its parent, counting from the last child
Selects every <p> element that is the last child of its
:last-child
p:last-child
parent
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
1
1
1
1
2
1
1
2
2
2
2
3
3
3
3
3
3
3
3
3
3
3
3
3
Page 118
SZABIST jstc Shaheed Benazirabad
:root
:root
:empty
p:empty
:target
#news:target
:enabled
:disabled
:checked
:not(selector)
input:enabled
input:disabled
input:checked
:not(p)
::selection
::selection
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Selects the document’s root element
Selects every <p> element that has no children
(including text nodes)
Selects the current active #news element (clicked on a
URL containing that anchor name)
Selects every enabled <input> element
Selects every disabled <input> element
Selects every checked <input> element
Selects every element that is not a <p> element
Selects the portion of an element that is selected by a
user
3
3
3
3
3
3
3
3
Page 119
SZABIST jstc Shaheed Benazirabad
CSS3 Introduction
CSS3 is completely backwards compatible, so you will not have to change existing designs.
Browsers will always support CSS2.
CSS3 Modules
CSS3 is split up into "modules". The old specification has been split into smaller pieces, and new
ones are also added.
Some of the most important CSS3 modules are:
 Selectors
 Box Model
 Backgrounds and Borders
 Text Effects
 2D/3D Transformations
 Animations
 Multiple Column Layout
 User Interface
CSS3 Recommendation
The CSS3 specification is still under development by W3C.
However, many of the new CSS3 properties have been implemented in modern browsers.
CSS3 Borders
CSS3 Borders
With CSS3, you can create rounded borders, add shadow to boxes, and use an image as a border
- without using a design program, like Photoshop.
In this chapter you will learn about the following border properties:
 border-radius
 box-shadow
 border-image
Internet Explorer 9+ supports border-radius and box-shadow.
Firefox, Chrome, and Safari supports all of the new border properties.
Note: Safari 5, and older versions, requires the prefix -webkit- for border-image.
Opera supports border-radius and box-shadow, but requires the prefix -o- for border-image.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 120
SZABIST jstc Shaheed Benazirabad
CSS3 Rounded Corners
Adding rounded corners in CSS2 was tricky. We had to use different images for each corner.
In CSS3, creating rounded corners is easy.
In CSS3, the border-radius property is used to create rounded corners:
Example
Add rounded corners to a div element:
div
{
border:2px solid;
border-radius:25px;
}
CSS3 Box Shadow
In CSS3, the box-shadow property is used to add shadow to boxes:
Example
Add a box-shadow to a div element:
div
{
box-shadow: 10px 10px 5px #888888;
}
CSS3 Border Image
With the CSS3 border-image property you can use an image to create a border:
The border-image property allows you to specify an image as a border!
The original image used to create the border above:
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 121
SZABIST jstc Shaheed Benazirabad
Example
Use an image to create a border around a div element:
div
{
border-image:url(border.png) 30 30 round;
-webkit-border-image:url(border.png) 30 30 round; /* Safari 5 and older */
-o-border-image:url(border.png) 30 30 round; /* Opera */
}
New Border Properties
Property
border-image
border-radius
box-shadow
Description
A shorthand property for setting all the border-image-* properties
A shorthand property for setting all the four border-*-radius
properties
Attaches one or more drop-shadows to the box
CSS
3
3
3
CSS3 Backgrounds
CSS3 Backgrounds
CSS3 contains several new background properties,
which allow greater control of the background element.
In this chapter you will learn about the following background properties:
 background-size
 background-origin
You will also learn how to use multiple background images.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 122
SZABIST jstc Shaheed Benazirabad
CSS3 The background-size Property
The background-size property specifies the size of the background image.
Before CSS3, the background image size was determined by the actual size of the image. In
CSS3 it is possible to specify the size of the background image, which allows us to re-use
background images in different contexts.
You can specify the size in pixels or in percentages. If you specify the size as a percentage, the
size is relative to the width and height of the parent element.
Example 1
Resize a background image:
div
{
background:url(img_flwr.gif);
background-size:80px 60px;
background-repeat:no-repeat;
}
Example 2
Stretch the background image to completely fill the content area:
div
{
background:url(img_flwr.gif);
background-size:100% 100%;
background-repeat:no-repeat;
}
CSS3 The background-origin Property
The background-origin property specifies the positioning area of the background images.
The background image can be placed within the content-box, padding-box, or border-box area.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 123
SZABIST jstc Shaheed Benazirabad
Example
Position the background image within the content-box:
div
{
background:url(img_flwr.gif);
background-repeat:no-repeat;
background-size:100% 100%;
background-origin:content-box;
}
CSS3 Multiple Background Images
CSS3 allows you to use several background images for an element.
Example
Set two background images for the body element:
body
{
background-image:url(img_flwr.gif),url(img_tree.gif);
}
New Background Properties
Property
background-clip
background-origin
background-size
Description
CSS
Specifies the painting area of the background images 3
Specifies the positioning area of the background images 3
Specifies the size of the background images
CSS3 Text Effects
CSS3 Text Effects
CSS3 contains several new text features.
In this chapter you will learn about the following text properties:
 text-shadow
 word-wrap
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 124
SZABIST jstc Shaheed Benazirabad
Internet Explorer 10, Firefox, Chrome, Safari, and Opera support the text-shadow property.
All major browsers support the word-wrap property.
Note: Internet Explorer 9 and earlier versions, does not support the text-shadow property.
CSS3 Text Shadow
In CSS3, the text-shadow property applies shadow to text.
You specify the horizontal shadow, the vertical shadow, the blur distance, and the color of the
shadow:
Example
Add a shadow to a header:
h1
{
text-shadow: 5px 5px 5px #FF0000;
}
CSS3 Word Wrapping
If a word is too long to fit within an area, it expands outside:
This paragraph contains a very long word: thisisaveryveryveryveryveryverylongword. The long
word will break and wrap to the next line.
In CSS3, the word-wrap property allows you to force the text to wrap - even if it means splitting
it in the middle of a word:
This paragraph contains a very long word: thisisaveryveryveryveryveryverylongword. The long
word will break and wrap to the next line.
The CSS code is as follows:
Example
Allow long words to be able to break and wrap onto the next line:
p {word-wrap:break-word;}
New Text Properties
Property
hanging-punctuation
Description
CSS
Specifies whether a punctuation character may be placed outside the
3
line box
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 125
SZABIST jstc Shaheed Benazirabad
punctuation-trim
text-align-last
text-emphasis
text-justify
text-outline
text-overflow
text-shadow
text-wrap
word-break
word-wrap
Specifies whether a punctuation character should be trimmed
Describes how the last line of a block or a line right before a forced
line break is aligned when text-align is "justify"
Applies emphasis marks, and the foreground color of the emphasis
marks, to the element's text
Specifies the justification method used when text-align is "justify"
Specifies a text outline
Specifies what should happen when text overflows the containing
element
Adds shadow to text
Specifies line breaking rules for text
Specifies line breaking rules for non-CJK scripts
Allows long, unbreakable words to be broken and wrap to the next
line
3
3
3
3
3
3
3
3
3
CSS3 Fonts
The CSS3 @font-face Rule
Before CSS3, web designers had to use fonts that were already installed on the user's computer.
With CSS3, web designers can use whatever font he/she likes.
When you have found/bought the font you wish to use, include the font file on your web server,
and it will be automatically downloaded to the user when needed.
Your "own" fonts are defined in the CSS3 @font-face rule.
Browser Support
Property Browser Support
@font-face
Internet Explorer 9+, Firefox, Chrome, Safari, and Opera support the WOFF (Web Open Font
Format) font.
Firefox, Chrome, Safari, and Opera support fonts of type TTF (True Type Fonts) and OTF
(OpenType Fonts).
Chrome, Safari and Opera also support SVG fonts/shapes.
Internet Explorer also supports EOT (Embedded OpenType) fonts.
Note: Internet Explorer 8 and earlier versions, do not support the @font-face rule.
Using The Font You Want
In the new @font-face rule you must first define a name for the font (e.g. myFirstFont), and then
point to the font file.
Tip: Use lowercase letters for the font URL. Uppercase letters can give unexpected results
in IE.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 126
SZABIST jstc Shaheed Benazirabad
To use the font for an HTML element, refer to the name of the font (myFirstFont) through the
font-family property:
Example
<style>
@font-face
{
font-family: myFirstFont;
src: url(sansation_light.woff);
}
div
{
font-family:myFirstFont;
}
</style>
Using Bold Text
You must add another @font-face rule containing descriptors for bold text:
Example
@font-face
{
font-family: myFirstFont;
src: url(sansation_bold.woff);
font-weight:bold;
}
The file "Sansation_Bold.ttf" is another font file, that contains the bold characters for the
Sansation font.
Browsers will use this whenever a piece of text with the font-family "myFirstFont" should render
as bold.
This way you can have many @font-face rules for the same font.
CSS3 Font Descriptors
The following table lists all the font descriptors that can be defined inside the @font-face rule:
Descriptor
Values
Description
font-family
name
Required. Defines a name for the font
src
URL
Required. Defines the URL of the font file
normal
Optional. Defines how the font should be stretched. Default
font-stretch
condensed
is "normal"
ultra-condensed
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 127
SZABIST jstc Shaheed Benazirabad
font-style
font-weight
unicode-range
extra-condensed
semi-condensed
expanded
semi-expanded
extra-expanded
ultra-expanded
normal
italic
oblique
normal
bold
100
200
300
400
500
600
700
800
900
unicode-range
Optional. Defines how the font should be styled. Default is
"normal"
Optional. Defines the boldness of the font. Default is
"normal"
Optional. Defines the range of UNICODE characters the
font supports. Default is "U+0-10FFFF"
CSS3 2D Transforms
CSS3 Transforms
With CSS3 transform, we can move, scale, turn, spin, and stretch elements.
How Does it Work?
A transform is an effect that lets an element change shape, size and position.
You can transform your elements using 2D or 3D transformation.
Browser Support
Property Browser Support
transform
Internet Explorer 10, Firefox, and Opera support the transform property.
Chrome and Safari requires the prefix -webkit-.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 128
SZABIST jstc Shaheed Benazirabad
Note: Internet Explorer 9 requires the prefix -ms-.
2D Transforms
In this chapter you will learn about the 2d transform methods:
 translate()
 rotate()
 scale()
 skew()
 matrix()
You will learn about 3D transforms in the next chapter.
Example
div
{
transform: rotate(30deg);
-ms-transform: rotate(30deg); /* IE 9 */
-webkit-transform: rotate(30deg); /* Safari and Chrome */
}
The translate() Method
With the translate() method, the element moves from its current position, depending on the
parameters given for the left (X-axis) and the top (Y-axis) position:
Example
div
{
transform: translate(50px,100px);
-ms-transform: translate(50px,100px); /* IE 9 */
-webkit-transform: translate(50px,100px); /* Safari and Chrome */
}
The value translate(50px,100px) moves the element 50 pixels from the left, and 100 pixels from
the top.
The rotate() Method
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 129
SZABIST jstc Shaheed Benazirabad
With the rotate() method, the element rotates clockwise at a given degree. Negative values are
allowed and rotates the element counter-clockwise.
Example
div
{
transform: rotate(30deg);
-ms-transform: rotate(30deg); /* IE 9 */
-webkit-transform: rotate(30deg); /* Safari and Chrome */
}
The value rotate(30deg) rotates the element clockwise 30 degrees.
The scale() Method
With the scale() method, the element increases or decreases the size, depending on the
parameters given for the width (X-axis) and the height (Y-axis):
Example
div
{
transform: scale(2,4);
-ms-transform: scale(2,4); /* IE 9 */
-webkit-transform: scale(2,4); /* Safari and Chrome */
}
The value scale(2,4) transforms the width to be twice its original size, and the height 4 times its
original size.
The skew() Method
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 130
SZABIST jstc Shaheed Benazirabad
With the skew() method, the element turns in a given angle, depending on the parameters given
for the horizontal (X-axis) and the vertical (Y-axis) lines:
Example
div
{
transform: skew(30deg,20deg);
-ms-transform: skew(30deg,20deg); /* IE 9 */
-webkit-transform: skew(30deg,20deg); /* Safari and Chrome */
}
The value skew(30deg,20deg) turns the element 30 degrees around the X-axis, and 20 degrees
around the Y-axis.
The matrix() Method
The matrix() method combines all of the 2D transform methods into one.
The matrix method take six parameters, containing mathematic functions, which allows you to:
rotate, scale, move (translate), and skew elements.
Example
How to rotate a div element 30 degrees, using the matrix method:
div
{
transform:matrix(0.866,0.5,-0.5,0.866,0,0);
-ms-transform:matrix(0.866,0.5,-0.5,0.866,0,0); /* IE 9 */
-webkit-transform:matrix(0.866,0.5,-0.5,0.866,0,0); /* Safari and Chrome */
}
New Transform Properties
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 131
SZABIST jstc Shaheed Benazirabad
The following table lists all the transform properties:
Property
transform
transform-origin
Description
CSS
Applies a 2D or 3D transformation to an element
3
Allows you to change the position on transformed elements 3
2D Transform Methods
Function
matrix(n,n,n,n,n,n)
translate(x,y)
translateX(n)
translateY(n)
scale(x,y)
scaleX(n)
scaleY(n)
rotate(angle)
skew(x-angle,y-angle)
skewX(angle)
skewY(angle)
Description
Defines a 2D transformation, using a matrix of six values
Defines a 2D translation, moving the element along the X- and the Y-axis
Defines a 2D translation, moving the element along the X-axis
Defines a 2D translation, moving the element along the Y-axis
Defines a 2D scale transformation, changing the elements width and height
Defines a 2D scale transformation, changing the element's width
Defines a 2D scale transformation, changing the element's height
Defines a 2D rotation, the angle is specified in the parameter
Defines a 2D skew transformation along the X- and the Y-axis
Defines a 2D skew transformation along the X-axis
Defines a 2D skew transformation along the Y-axis
CSS3 3D Transforms
3D Transforms
CSS3 allows you to format your elements using 3D transforms.
In this chapter you will learn about some of the 3D transform methods:


rotateX()
rotateY()
Click on the elements below, to see the difference between a 2D transform and a 3D transform:
2D rotate
3D rotate
Browser Support
Property Browser Support
transform
Internet Explorer 10 and Firefox supports 3D transforms.
Chrome and Safari requires the prefix -webkit-.
Opera does not yet support 3D transforms (It supports 2D transforms only).
The rotateX() Method
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 132
SZABIST jstc Shaheed Benazirabad
With the rotateX() method, the element rotates around its X-axis at a given degree.
Example
div
{
transform: rotateX(120deg);
-webkit-transform: rotateX(120deg); /* Safari and Chrome */
}
The rotateY() Method
With the rotateY() method, the element rotates around its Y-axis at a given degree.
Example
div
{
transform: rotateY(130deg);
-webkit-transform: rotateY(130deg); /* Safari and Chrome */
}
Transform Properties
The following table lists all the transform properties:
Property
transform
transform-origin
transform-style
perspective
perspective-origin
backface-visibility
Description
Applies a 2D or 3D transformation to an element
Allows you to change the position on transformed elements
Specifies how nested elements are rendered in 3D space
Specifies the perspective on how 3D elements are viewed
Specifies the bottom position of 3D elements
Defines whether or not an element should be visible when not facing
the screen
CSS
3
3
3
3
3
3
3D Transform Methods
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 133
SZABIST jstc Shaheed Benazirabad
Function
Description
matrix3d
Defines a 3D transformation, using a 4x4 matrix of 16 values
(n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n)
translate3d(x,y,z)
Defines a 3D translation
translateX(x)
Defines a 3D translation, using only the value for the X-axis
translateY(y)
Defines a 3D translation, using only the value for the Y-axis
translateZ(z)
Defines a 3D translation, using only the value for the Z-axis
scale3d(x,y,z)
Defines a 3D scale transformation
scaleX(x)
Defines a 3D scale transformation by giving a value for the X-axis
scaleY(y)
Defines a 3D scale transformation by giving a value for the Y-axis
scaleZ(z)
Defines a 3D scale transformation by giving a value for the Z-axis
rotate3d(x,y,z,angle)
Defines a 3D rotation
rotateX(angle)
Defines a 3D rotation along the X-axis
rotateY(angle)
Defines a 3D rotation along the Y-axis
rotateZ(angle)
Defines a 3D rotation along the Z-axis
perspective(n)
Defines a perspective view for a 3D transformed element
CSS3 Transitions
CSS3 Transitions
With CSS3, we can add an effect when changing from one style to another, without using Flash
animations or JavaScripts.
Mouse over the element below:
CSS3
Transition
Browser Support
Property Browser Support
transition
Internet Explorer 10, Firefox, Chrome, and Opera supports the transition property.
Safari requires the prefix -webkit-.
Note: Internet Explorer 9, and earlier versions, does not support the transition property.
Note: Chrome 25, and earlier versions, requires the prefix -webkit-.
How does it work?
CSS3 transitions are effects that let an element gradually change from one style to another.
To do this, you must specify two things:
 Specify the CSS property you want to add an effect to
 Specify the duration of the effect.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 134
SZABIST jstc Shaheed Benazirabad
Example
Transition effect on the width property, duration: 2 seconds:
div
{
transition: width 2s;
-webkit-transition: width 2s; /* Safari */
}
Note: If the duration is not specified, the transition will have no effect, because default value is
0.
The effect will start when the specified CSS property changes value. A typical CSS property
change would be when a user mouse-over an element:
Example
Specify :hover for <div> elements:
div:hover
{
width:300px;
}
Note: When the cursor mouse out of the element, it gradually changes back to it's original style.
Multiple changes
To add a transitional effect for more than one style, add more properties, separated by commas:
Example
Add effects on the width, height, and the transformation:
div
{
transition: width 2s, height 2s, transform 2s;
-webkit-transition: width 2s, height 2s, -webkit-transform 2s;
}
Transition Properties
The following table lists all the transition properties:
Property
transition
transition-property
transition-duration
transition-timing-function
Description
A shorthand property for setting the four transition properties into a
single property
Specifies the name of the CSS property to which the transition is
applied
Defines the length of time that a transition takes. Default 0
Describes how the speed during a transition will be calculated.
Default "ease"
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
CSS
3
3
3
3
Page 135
SZABIST jstc Shaheed Benazirabad
transition-delay
Defines when the transition will start. Default 0
3
The two examples below sets all transition properties:
Example
Use all transition properties in one example:
div
{
transition-property: width;
transition-duration: 1s;
transition-timing-function: linear;
transition-delay: 2s;
/* Safari */
-webkit-transition-property:width;
-webkit-transition-duration:1s;
-webkit-transition-timing-function:linear;
-webkit-transition-delay:2s;
}
Example
The same transition effects as above, using the shorthand transition property:
div
{
transition: width 1s linear 2s;
/* Safari */
-webkit-transition:width 1s linear 2s;
}
CSS3 Animations
With CSS3, we can create animations, which can replace animated images, Flash animations,
and JavaScripts in many web pages.
CSS3
Animation
CSS3 @keyframes Rule
To create animations in CSS3, you will have to learn about the @keyframes rule.
The @keyframes rule is where the animation is created. Specify a CSS style inside the
@keyframes rule and the animation will gradually change from the current style to the new style.
Browser Support
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 136
SZABIST jstc Shaheed Benazirabad
Property Browser Support
@keyframes
animation
Internet Explorer 10, Firefox, and Opera supports the @keyframes rule and animation property.
Chrome and Safari requires the prefix -webkit-.
Note: Internet Explorer 9, and earlier versions, does not support the @keyframe rule or
animation property.
Example
@keyframes myfirst
{
from {background: red;}
to {background: yellow;}
}
@-webkit-keyframes myfirst /* Safari and Chrome */
{
from {background: red;}
to {background: yellow;}
}
CSS3 animation
When the animation is created in the @keyframe, bind it to a selector, otherwise the animation
will have no effect.
Bind the animation to a selector by specifying at least these two CSS3 animation properties:
 Specify the name of the animation
 Specify the duration of the animation
Example
Binding the "myfirst" animation to a div element, duration: 5 seconds:
div
{
animation: myfirst 5s;
-webkit-animation: myfirst 5s; /* Safari and Chrome */
}
Note: You must define the name and the duration of the animation. If duration is omitted, the
animation will not run, because the default value is 0.
What are Animations in CSS3?
An animation is an effect that lets an element gradually change from one style to another.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 137
SZABIST jstc Shaheed Benazirabad
You can change as many styles you want, as many times you want.
Specify when the change will happen in percent, or the keywords "from" and "to", which is the
same as 0% and 100%.
0% is the beginning of the animation, 100% is when the animation is complete.
For best browser support, you should always define both the 0% and the 100% selectors.
Example
Change the background color when the animation is 25%, 50%, and again when the animation is
100% complete:
@keyframes myfirst
{
0% {background: red;}
25% {background: yellow;}
50% {background: blue;}
100% {background: green;}
}
@-webkit-keyframes myfirst /* Safari and Chrome */
{
0% {background: red;}
25% {background: yellow;}
50% {background: blue;}
100% {background: green;}
}
Example
Change the background color and position:
@keyframes myfirst
{
0% {background: red; left:0px; top:0px;}
25% {background: yellow; left:200px; top:0px;}
50% {background: blue; left:200px; top:200px;}
75% {background: green; left:0px; top:200px;}
100% {background: red; left:0px; top:0px;}
}
@-webkit-keyframes myfirst /* Safari and Chrome */
{
0% {background: red; left:0px; top:0px;}
25% {background: yellow; left:200px; top:0px;}
50% {background: blue; left:200px; top:200px;}
75% {background: green; left:0px; top:200px;}
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 138
SZABIST jstc Shaheed Benazirabad
100% {background: red; left:0px; top:0px;}
}
CSS3 Animation Properties
The following table lists the @keyframes rule and all the animation properties:
Property
@keyframes
animation
animation-name
animation-duration
animation-timing-function
animation-delay
animation-iteration-count
animation-direction
animation-play-state
Description
Specifies the animation
A shorthand property for all the the animation properties, except the
animation-play-state property
Specifies the name of the @keyframes animation
Specifies how many seconds or milliseconds an animation takes to
complete one cycle. Default 0
Describes how the animation will progress over one cycle of its
duration. Default "ease"
Specifies when the animation will start. Default 0
Specifies the number of times an animation is played. Default 1
Specifies whether or not the animation should play in reverse on
alternate cycles. Default "normal"
Specifies whether the animation is running or paused. Default
"running"
CSS
3
3
3
3
3
3
3
3
3
The two examples below sets all the animation properties:
Example
Run an animation called myfirst, with all the animation properties set:
div
{
animation-name: myfirst;
animation-duration: 5s;
animation-timing-function: linear;
animation-delay: 2s;
animation-iteration-count: infinite;
animation-direction: alternate;
animation-play-state: running;
/* Safari and Chrome: */
-webkit-animation-name: myfirst;
-webkit-animation-duration: 5s;
-webkit-animation-timing-function: linear;
-webkit-animation-delay: 2s;
-webkit-animation-iteration-count: infinite;
-webkit-animation-direction: alternate;
-webkit-animation-play-state: running;
}
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 139
SZABIST jstc Shaheed Benazirabad
Example
The same animation as above, using the shorthand animation property:
div
{
animation: myfirst 5s linear 2s infinite alternate;
/* Safari and Chrome: */
-webkit-animation: myfirst 5s linear 2s infinite alternate;
}
CSS3 Multiple Columns
CSS3 Multiple Columns
With CSS3, you can create multiple columns for laying out text - like in newspapers!
In this chapter you will learn about the following multiple column properties:
 column-count
 column-gap
 column-rule
Internet Explorer 10 and Opera supports multiple columns properties.
Firefox requires the prefix -moz-.
Chrome and Safari requires the prefix -webkit-.
Note: Internet Explorer 9, and earlier versions, does not support the multiple columns properties.
CSS3 Create Multiple Columns
The column-count property specifies the number of columns an element should be divided into:
Example
Divide the text in a div element into three columns:
div
{
-moz-column-count:3; /* Firefox */
-webkit-column-count:3; /* Safari and Chrome */
column-count:3;
}
CSS3 Specify the Gap Between Columns
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 140
SZABIST jstc Shaheed Benazirabad
The column-gap property specifies the gap between the columns:
Example
Specify a 40 pixels gap between the columns:
div
{
-moz-column-gap:40px; /* Firefox */
-webkit-column-gap:40px; /* Safari and Chrome */
column-gap:40px;
}
CSS3 Column Rules
The column-rule property sets the width, style, and color of the rule between columns.
Example
Specify the width, style and color of the rule between columns:
div
{
-moz-column-rule:3px outset #ff00ff; /* Firefox */
-webkit-column-rule:3px outset #ff00ff; /* Safari and Chrome */
column-rule:3px outset #ff00ff;
}
New Multiple Columns Properties
Property
column-count
column-fill
column-gap
column-rule
column-rule-color
column-rule-style
column-rule-width
column-span
column-width
columns
Description
CSS
Specifies the number of columns an element should be divided into 3
Specifies how to fill columns
3
Specifies the gap between the columns
3
A shorthand property for setting all the column-rule-* properties 3
Specifies the color of the rule between columns
3
Specifies the style of the rule between columns
3
Specifies the width of the rule between columns
3
Specifies how many columns an element should span across
3
Specifies the width of the columns
3
A shorthand property for setting column-width and column-count 3
CSS3 User Interface
In CSS3, some of the new user interface features are resizing elements, box sizing, and outlining.
In this chapter you will learn about the following user interface properties:
 resize
 box-sizing
 outline-offset
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 141
SZABIST jstc Shaheed Benazirabad
The resize property is supported in Firefox, Chrome, and Safari.
The box-sizing is supported in Internet Explorer, Chrome, Safari, and Opera. Firefox requires the
prefix -moz-.
The outline-offset property is supported in all major browsers, except Internet Explorer.
CSS3 Resizing
In CSS3, the resize property specifies whether or not an element should be resizable by the user.
This div element is resizable by the user (in Firefox, Chrome, and Safari).
The CSS code is as follows:
Example
Specify that a div element should be resizable by the user:
div
{
resize:both;
overflow:auto;
}
CSS3 Box Sizing
The box-sizing property allows you to define certain elements to fit an area in a certain way:
Example
Specify two bordered boxes side by side:
div
{
box-sizing:border-box;
-moz-box-sizing:border-box; /* Firefox */
width:50%;
float:left;
}
CSS3 Outline Offset
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 142
SZABIST jstc Shaheed Benazirabad
The outline-offset property offsets an outline, and draws it beyond the border edge.
Outlines differ from borders in two ways:
 Outlines do not take up space
 Outlines may be non-rectangular

This div has an outline 15px outside the border edge.
The CSS code is as follows:
Example
Specify an outline 15px outside the border edge:
div
{
border:2px solid black;
outline:2px solid red;
outline-offset:15px;
}
New User-interface Properties
Property
appearance
box-sizing
icon
nav-down
nav-index
nav-left
nav-right
nav-up
outline-offset
resize
Description
Allows you to make an element look like a standard user interface
element
Allows you to define certain elements to fit an area in a certain way
Provides the author the ability to style an element with an iconic
equivalent
Specifies where to navigate when using the arrow-down navigation
key
Specifies the tabbing order for an element
Specifies where to navigate when using the arrow-left navigation key
Specifies where to navigate when using the arrow-right navigation
key
Specifies where to navigate when using the arrow-up navigation key
Offsets an outline, and draws it beyond the border edge
Specifies whether or not an element is resizable by the user
CSS
3
3
3
3
3
3
3
3
3
Measurement Values
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 143
SZABIST jstc Shaheed Benazirabad
Unit
%
in
cm
mm
em
ex
pt
pc
px
Description
percentage
inch
centimeter
millimeter
1em is equal to the current font size. 2em means 2 times the size of the
current font. E.g., if an element is displayed with a font of 12 pt, then
'2em' is 24 pt. The 'em' is a very useful unit in CSS, since it can adapt
automatically to the font that the reader uses
one ex is the x-height of a font (x-height is usually about half the fontsize)
point (1 pt is the same as 1/72 inch)
pica (1 pc is the same as 12 points)
pixels (a dot on the computer screen)
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 144
SZABIST jstc Shaheed Benazirabad
JAVA SCRIPT
What is JavaScript ?
JavaScript started life as LiveScript, but Netscape changed the name, possibly because of the
excitement being generated by Java.to JavaScript. JavaScript made its first appearance in
Netscape 2.0 in 1995 with a name LiveScript.
JavaScript is a lightweight, interpreted programming language with object-oriented capabilities
that allows you to build interactivity into otherwise static HTML pages.
The general-purpose core of the language has been embedded in Netscape, Internet Explorer, and
other web browsers
The ECMA-262 Specification defined a standard version of the core JavaScript language.
JavaScript is:
 JavaScript is a lightweight, interpreted programming language
 Designed for creating network-centric applications
 Complementary to and integrated with Java
 Complementary to and integrated with HTML
 Open and cross-platform
Advantages of JavaScript:
The merits of using JavaScript are:
 Less server interaction: You can validate user input before sending the page off to the
server. This saves server traffic, which means less load on your server.
 Immediate feedback to the visitors: They don't have to wait for a page reload to see if
they have forgotten to enter something.
 Increased interactivity: You can create interfaces that react when the user hovers over
them with a mouse or activates them via the keyboard.
 Richer interfaces: You can use JavaScript to include such items as drag-and-drop
components and sliders to give a Rich Interface to your site visitors.
Limitations with JavaScript:
We can not treat JavaScript as a full fledged programming language. It lacks the following
important features:
 Client-side JavaScript does not allow the reading or writing of files. This has been kept
for security reason.
 JavaScript can not be used for Networking applications because there is no such support
available.
 JavaScript doesn't have any multithreading or multiprocess capabilities.
Once again, JavaScript is a lightweight, interpreted programming language that allows you to
build interactivity into otherwise static HTML pages.
A JavaScript consists of JavaScript statements that are placed within the <script>... </script> HTML tags
in a web page.
<script ...>
JavaScript code
</script>
The script tag takes two important attributes:
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 145
SZABIST jstc Shaheed Benazirabad

language: This attribute specifies what scripting language you are using. Typically, its
value will be javascript. Although recent versions of HTML (and XHTML, its successor)
have phased out the use of this attribute.
 type: This attribute is what is now recommended to indicate the scripting language in use
and its value should be set to "text/javascript".
So your JavaScript segment will look like:
<script language="javascript" type="text/javascript">
JavaScript code
</script>
Your First JavaScript Script:
Let us write our class example to print out "Hello World".
<html>
<body>
<script language="javascript" type="text/javascript">
<!-document.write("Hello World!")
//-->
</script>
</body>
</html>
Whitespace and Line Breaks:
JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs.
Semicolons are Optional:
Simple statements in JavaScript are generally followed by a semicolon character, just as they are
in C, C++, and Java. JavaScript, however, allows you to omit this semicolon if your statements
are each placed on a separate line. For example, the following code could be written without
semicolons
<script language="javascript" type="text/javascript">
<!-var1 = 10
var2 = 20
//-->
</script>
But when formatted in a single line as follows, the semicolons are required:
<script language="javascript" type="text/javascript">
<!-var1 = 10; var2 = 20;
//-->
</script>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 146
SZABIST jstc Shaheed Benazirabad
Case Sensitivity:
JavaScript is a case-sensitive language. This means that language keywords, variables, function
names, and any other identifiers must always be typed with a consistent capitalization of letters.
So identifiers Time, TIme and TIME will have different meanings in JavaScript.
NOTE: Care should be taken while writing your variable and function names in JavaScript.
Comments in JavaScript:
JavaScript supports both C-style and C++-style comments, Thus:
 Any text between a // and the end of a line is treated as a comment and is ignored by
JavaScript.
 Any text between the characters /* and */ is treated as a comment. This may span
multiple lines.
 JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript treats
this as a single-line comment, just as it does the // comment.
 The HTML comment closing sequence --> is not recognized by JavaScript so it should be
written as //-->.
Example:
<script language="javascript" type="text/javascript">
<!-// This is a comment. It is similar to comments in C++
/*
* This is a multiline comment in JavaScript
* It is very similar to comments in C Programming
*/
//-->
</script>
JavaScript in Internet Explorer:
Here are simple steps to turn on or turn off JavaScript in your Internet Explorer:
1. Follow Tools-> Internet Options from the menu
2. Select Security tab from the dialog box
3. Click the Custom Level button
4. Scroll down till you find Scripting option
5. Select Enable radio button under Active scripting
6. Finally click OK and come out
To disable JavaScript support in your Internet Explorer, you need to select Disable radio button
under Active scripting.
JavaScript in Firefox:
Here are simple steps to turn on or turn off JavaScript in your Firefox:
1. Follow Tools-> Options
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 147
SZABIST jstc Shaheed Benazirabad
from the menu
2. Select Content option from the dialog box
3. Select Enable JavaScript checkbox
4. Finally click OK and come out
To disable JavaScript support in your Firefox, you should not select Enable JavaScript
checkbox.
JavaScript in Opera:
Here are simple steps to turn on or turn off JavaScript in your Opera:
1. Follow Tools-> Preferences
from the menu
2. Select Advanced option from the dialog box
3. Select Content from the listed items
4. Select Enable JavaScript checkbox
5. Finally click OK and come out
To disable JavaScript support in your Opera, you should not select Enable JavaScript checkbox.
Warning for Non-JavaScript Browsers:
If you have to do something important using JavaScript then you can display a warning message
to the user using <noscript> tags.
You can add a noscript block immediately after the script block as follows:
<html>
<body>
<script language="javascript" type="text/javascript">
<!-document.write("Hello World!")
//-->
</script>
<noscript>
Sorry...JavaScript is needed to go ahead.
</noscript>
</body>
</html>
There is a flexibility given to include JavaScript code anywhere in an HTML document. But
there are following most preferred ways to include JavaScript in your HTML file.
 Script in <head>...</head> section.
 Script in <body>...</body> section.
 Script in <body>...</body> and <head>...</head> sections.
 Script in and external file and then include in <head>...</head> section.
In the following section we will see how we can put JavaScript in different ways:
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 148
SZABIST jstc Shaheed Benazirabad
JavaScript in <head>...</head> section:
If you want to have a script run on some event, such as when a user clicks somewhere, then you
will place that script in the head as follows:
<html>
<head>
<script type="text/javascript">
<!-function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
This will produce following result:
JavaScript in <body>...</body> section:
If you need a script to run as the page loads so that the script generates content in the page, the
script goes in the <body> portion of the document. In this case you would not have any function
defined using JavaScript:
<html>
<head>
</head>
<body>
<script type="text/javascript">
<!-document.write("Hello World")
//-->
</script>
<p>This is web page body </p>
</body>
</html>
This will produce following result:
Advertisements
Hello World
This is web page body
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 149
SZABIST jstc Shaheed Benazirabad
JavaScript in <body> and <head> sections:
You can put your JavaScript code in <head> and <body> section altogether as follows:
<html>
<head>
<script type="text/javascript">
<!-function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<script type="text/javascript">
<!-document.write("Hello World")
//-->
</script>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
This will produce following result:
Advertisements
Hello World
JavaScript in External File :
As you begin to work more extensively with JavaScript, you will likely find that there are cases
where you are reusing identical JavaScript code on multiple pages of a site.
You are not restricted to be maintaining identical code in multiple HTML files. The script tag
provides a mechanism to allow you to store JavaScript in an external file and then include it into
your HTML files.
Here is an example to show how you can include an external JavaScript file in your HTML code
using script tag and its src attribute:
<html>
<head>
<script type="text/javascript" src="filename.js" ></script>
</head>
<body>
.......
</body>
</html>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 150
SZABIST jstc Shaheed Benazirabad
To use JavaScript from an external file source, you need to write your all JavaScript source code
in a simple text file with extension ".js" and then include that file as shown above.
For example, you can keep following content in filename.js file and then you can use sayHello
function in your HTML file after including filename.js file:
function sayHello() {
alert("Hello World")
}
JavaScript DataTypes:
One of the most fundamental characteristics of a programming language is the set of data types it
supports. These are the type of values that can be represented and manipulated in a programming
language.
JavaScript allows you to work with three primitive data types:
 Numbers eg. 123, 120.50 etc.
 Strings of text e.g. "This text string" etc.
 Boolean e.g. true or false.
JavaScript also defines two trivial data types, null and undefined, each of which defines only a
single value.
In addition to these primitive data types, JavaScript supports a composite data type known as
object. We will see an object detail in a separate chapter.
Note: Java does not make a distinction between integer values and floating-point values. All
numbers in JavaScript are represented as floating-point values. JavaScript represents numbers
using the 64-bit floating-point format defined by the IEEE 754 standard.
JavaScript Variables:
Like many other programming languages, JavaScript has variables. Variables can be thought of
as named containers. You can place data into these containers and then refer to the data simply
by naming the container.
Before you use a variable in a JavaScript program, you must declare it. Variables are declared
with the var keyword as follows:
<script type="text/javascript">
<!-var money;
var name;
//-->
</script>
You can also declare multiple variables with the same var keyword as follows:
<script type="text/javascript">
<!-var _money, name;
//-->
</script>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 151
SZABIST jstc Shaheed Benazirabad
Storing a value in a variable is called variable initialization. You can do variable initialization at
the time of variable creation or later point in time when you need that variable as follows:
For instance, you might create a variable named money and assign the value 2000.50 to it later.
For another variable you can assign a value the time of initialization as follows:
<script type="text/javascript">
<!-var name = "Ali";
var money;
money = 2000.50;
//-->
</script>
Note: Use the var keyword only for declaration or initialization.once for the life of any variable
name in a document. You should not re-declare same variable twice.
JavaScript is untyped language. This means that a JavaScript variable can hold a value of any
data type. Unlike many other languages, you don't have to tell JavaScript during variable
declaration what type of value the variable will hold. The value type of a variable can change
during the execution of a program and JavaScript takes care of it automatically.
Declaring (Creating) JavaScript Variables
Creating a variable in JavaScript is most often referred to as "declaring" a variable.
You declare JavaScript variables with the var keyword:
var carname;
After the declaration, the variable is empty (it has no value).
To assign a value to the variable, use the equal sign:
carname="Volvo";
However, you can also assign a value to the variable when you declare it:
var carname="Volvo";
In the example below we create a variable called carname, assigns the value "Volvo" to it, and
put the value inside the HTML paragraph with id="demo":
Example
<p id="demo"></p>
var carname="Volvo";
document.getElementById("demo").innerHTML=carname;
JavaScript Variable Scope:
The scope of a variable is the region of your program in which it is defined. JavaScript variable
will have only two scopes.
 Global Variables: A global variable has global scope which means it is defined
everywhere in your JavaScript code.
 Local Variables: A local variable will be visible only within a function where it is
defined. Function parameters are always local to that function.
Within the body of a function, a local variable takes precedence over a global variable with the
same name. If you declare a local variable or function parameter with the same name as a global
variable, you effectively hide the global variable. Following example explains it:
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 152
SZABIST jstc Shaheed Benazirabad
<script type="text/javascript">
<!-var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
//-->
</script>
This produces the following result:
local
JavaScript Variable Names:
While naming your variables in JavaScript keep following rules in mind.
 You should not use any of the JavaScript reserved keyword as variable name. These
keywords are mentioned in the next section. For example, break or boolean variable
names are not valid.
 JavaScript variable names should not start with a numeral (0-9). They must begin with a
letter or the underscore character. For example, 123test is an invalid variable name but
_123test is a valid one.
 JavaScript variable names are case sensitive. For example, Name and name are two
different variables.
JavaScript Reserved Words:
The following are reserved words in JavaScript. They cannot be used as JavaScript variables,
functions, methods, loop labels, or any object names.
abstract
boolean
break
byte
case
catch
char
class
const
continue
debugger
default
delete
do
double
else
enum
export
extends
false
final
finally
float
for
function
goto
if
implements
import
in
instanceof
int
interface
long
native
new
null
package
private
protected
public
return
short
static
super
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
switch
synchronized
this
throw
throws
transient
true
try
typeof
var
void
volatile
while
with
Page 153
SZABIST jstc Shaheed Benazirabad
JavaScript Data Types
String, Number, Boolean, Array, Object, Null, Undefined
JavaScript Has Dynamic Types
JavaScript has dynamic types. This means that the same variable can be used as different types:
Example
var x;
// Now x is undefined
var x = 5;
// Now x is a Number
var x = "John"; // Now x is a String
JavaScript Strings
A string is a variable which stores a series of characters like "John Doe".
A string can be any text inside quotes. You can use single or double quotes:
Example
var carname="Volvo XC60";
var carname='Volvo XC60';
You can use quotes inside a string, as long as they don't match the quotes surrounding the string:
Example
var answer="It's alright";
var answer="He is called 'Johnny'";
var answer='He is called "Johnny"';
JavaScript Numbers
JavaScript has only one type of numbers. Numbers can be written with, or without decimals:
Example
var x1=34.00; //Written with decimals
var x2=34;
//Written without decimals
Extra large or extra small numbers can be written with scientific (exponential) notation:
Example
var y=123e5;
var z=123e-5;
// 12300000
// 0.00123
JavaScript Booleans
Booleans can only have two values: true or false.
var x=true;
var y=false;
Booleans are often used in conditional testing. You will learn more about conditional testing in a
later chapter of this tutorial.
JavaScript Arrays
The following code creates an Array called cars:
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 154
SZABIST jstc Shaheed Benazirabad
var cars=new Array();
cars[0]="Saab";
cars[1]="Volvo";
cars[2]="BMW";
or (condensed array):
var cars=new Array("Saab","Volvo","BMW");
or (literal array):
Example
var cars=["Saab","Volvo","BMW"];
Array indexes are zero-based, which means the first item is [0], second is [1], and so on.
You will learn a lot more about arrays in later chapters of this tutorial.
JavaScript Objects
An object is delimited by curly braces. Inside the braces the object's properties are defined as
name and value pairs (name : value). The properties are separated by commas:
var person={firstname:"John", lastname:"Doe", id:5566};
The object (person) in the example above has 3 properties: firstname, lastname, and id.
Spaces and line breaks are not important. Your declaration can span multiple lines:
var person={
firstname : "John",
lastname : "Doe",
id
: 5566
};
You can address the object properties in two ways:
Example
name=person.lastname;
name=person["lastname"];
Undefined and Null
Undefined is the value of a variable with no value.
Variables can be emptied by setting the value to null;
Example
cars=null;
person=null;
Declaring Variable Types
When you declare a new variable, you can declare its type using the "new" keyword:
var carname=new String;
var x= new Number;
var y= new Boolean;
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 155
SZABIST jstc Shaheed Benazirabad
var cars= new Array;
var person= new Object;
JavaScript Objects
"Everything" in JavaScript is an Object: a String, a Number, an Array, a Date....
In JavaScript, an object is data, with properties and methods.
Properties and Methods
Properties are values associated with objects.
Methods are actions that objects can perform.
A Real Life Object. A Car:
Properties:
Methods:
car.name=Fiat
car.start()
car.model=500
car.drive()
car.weight=850kg
car.brake()
car.color=white
The properties of the car include name, model, weight, color, etc.
All cars have these properties, but the property values differ from car to car.
The methods of the car could be start(), drive(), brake(), etc.
All cars have these methods, but they are performed at different times.
Objects in JavaScript:
In JavaScript, objects are data (variables), with properties and methods.
When you declare a JavaScript variable like this:
var txt = "Hello";
You actually create a JavaScript String object. The String object has a built-in property called
length. For the string above, length has the value 5. The String object also have several built-in
methods.
Properties:
txt.length=5
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
"Hello"
Methods:
txt.indexOf()
Page 156
SZABIST jstc Shaheed Benazirabad
txt.replace()
txt.search()
In object oriented languages, properties and methods are often called object members.
You will learn more about properties and the methods of the String object in a later chapter of
this tutorial.
Creating JavaScript Objects
Almost "everything" in JavaScript is an object. Strings, Dates, Arrays, Functions.
You can also create your own objects.
This example creates an object called "person", and adds four properties to it:
Example
person=new Object();
person.firstname="John";
person.lastname="Doe";
person.age=50;
person.eyecolor="blue";
There are many different ways to create new JavaScript objects, and you can also add properties
and methods to existing objects.
You will learn much more about this in a later chapter of this tutorial.
Accessing Object Properties
The syntax for accessing the property of an object is:
objectName.propertyName
This example uses the length property of the String object to find the length of a string:
var message="Hello World!";
var x=message.length;
The value of x, after execution of the code above will be:
12
Accessing Object Methods
You can call a method with the following syntax:
objectName.methodName()
This example uses the toUpperCase() method of the String object, to convert a text to uppercase:
var message="Hello world!";
var x=message.toUpperCase();
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 157
SZABIST jstc Shaheed Benazirabad
The value of x, after execution of the code above will be:
HELLO WORLD!
What is an operator?
Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called
operands and + is called operator. JavaScript language supports following type of operators.
 Arithmetic Operators
 Comparision Operators
 Logical (or Relational) Operators
 Assignment Operators
 Conditional (or ternary) Operators
Lets have a look on all operators one by one.
The Arithmatic Operators:
There are following arithmatic operators supported by JavaScript language:
Assume variable A holds 10 and variable B holds 20 then:
Operator
Description
Example
+
Adds two operands
A + B will give 30
-
Subtracts second operand from the first
A - B will give -10
*
Multiply both operands
A * B will give 200
/
Divide numerator by denumerator
B / A will give 2
%
Modulus Operator and remainder of after an integer
division
B % A will give 0
++
Increment operator, increases integer value by one
A++ will give 11
--
Decrement operator, decreases integer value by one
A-- will give 9
Note: Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will give "a10".
The Comparison Operators:
There are following comparison operators supported by JavaScript language
Assume variable A holds 10 and variable B holds 20 then:
Operator
==
Description
Checks if the value of two operands are equal or not, if
yes then condition becomes true.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Example
(A == B) is not true.
Page 158
SZABIST jstc Shaheed Benazirabad
!=
Checks if the value of two operands are equal or not, if
values are not equal then condition becomes true.
(A != B) is true.
>
Checks if the value of left operand is greater than the
value of right operand, if yes then condition becomes
true.
(A > B) is not true.
<
Checks if the value of left operand is less than the value
of right operand, if yes then condition becomes true.
(A < B) is true.
>=
Checks if the value of left operand is greater than or
equal to the value of right operand, if yes then
condition becomes true.
(A >= B) is not true.
<=
Checks if the value of left operand is less than or equal
to the value of right operand, if yes then condition
becomes true.
(A <= B) is true.
The Logical Operators:
There are following logical operators supported by JavaScript language
Assume variable A holds 10 and variable B holds 20 then:
Operator
Description
Example
&&
Called Logical AND operator. If both the operands are
non zero then then condition becomes true.
(A && B) is true.
||
Called Logical OR Operator. If any of the two operands
are non zero then then condition becomes true.
(A || B) is true.
!
Called Logical NOT Operator. Use to reverses the logical
state of its operand. If a condition is true then Logical
NOT operator will make false.
!(A && B) is false.
The Bitwise Operators:
There are following bitwise operators supported by JavaScript language
Assume variable A holds 2 and variable B holds 3 then:
Operator
Description
Example
&
Called Bitwise AND operator. It performs a Boolean
AND operation on each bit of its integer arguments.
(A & B) is 2 .
|
Called Bitwise OR Operator. It performs a Boolean OR
operation on each bit of its integer arguments.
(A | B) is 3.
^
Called Bitwise XOR Operator. It performs a Boolean
(A ^ B) is 1.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 159
SZABIST jstc Shaheed Benazirabad
exclusive OR operation on each bit of its integer
arguments. Exclusive OR means that either operand one
is true or operand two is true, but not both.
~
Called Bitwise NOT Operator. It is a is a unary operator
and operates by reversing all bits in the operand.
<<
Called Bitwise Shift Left Operator. It moves all bits in its
first operand to the left by the number of places
specified in the second operand. New bits are filled with
(A << 1) is 4.
zeros. Shifting a value left by one position is equivalent
to multiplying by 2, shifting two positions is equivalent
to multiplying by 4, etc.
>>
Called Bitwise Shift Right with Sign Operator. It moves
all bits in its first operand to the right by the number of
places specified in the second operand. The bits filled in
on the left depend on the sign bit of the original
operand, in order to preserve the sign of the result. If
the first operand is positive, the result has zeros placed (A >> 1) is 1.
in the high bits; if the first operand is negative, the
result has ones placed in the high bits. Shifting a value
right one place is equivalent to dividing by 2 (discarding
the remainder), shifting right two places is equivalent to
integer division by 4, and so on.
>>>
Called Bitwise Shift Right with Zero Operator. This
operator is just like the >> operator, except that the bits (A >>> 1) is 1.
shifted in on the left are always zero,
(~B) is -4 .
The Assignment Operators:
There are following assignment operators supported by JavaScript language:
Operator
Description
Example
=
Simple assignment operator, Assigns values from right
side operands to left side operand
C = A + B will assigne value of A + B
into C
+=
Add AND assignment operator, It adds right operand to
the left operand and assign the result to left operand
C += A is equivalent to C = C + A
-=
Subtract AND assignment operator, It subtracts right
operand from the left operand and assign the result to
left operand
C -= A is equivalent to C = C - A
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 160
SZABIST jstc Shaheed Benazirabad
*=
Multiply AND assignment operator, It multiplies right
operand with the left operand and assign the result to
left operand
C *= A is equivalent to C = C * A
/=
Divide AND assignment operator, It divides left operand
with the right operand and assign the result to left
operand
C /= A is equivalent to C = C / A
%=
Modulus AND assignment operator, It takes modulus
using two operands and assign the result to left
operand
C %= A is equivalent to C = C % A
Note: Same logic applies to Bitwise operators so they will become like <<=, >>=, >>=, &=, |=
and ^=.
Miscellaneous Operator
The Conditional Operator (? :)
There is an oprator called conditional operator. This first evaluates an expression for a true or
false value and then execute one of the two given statements depending upon the result of the
evaluation. The conditioanl operator has this syntax:
Operator
?:
Description
Conditional Expression
Example
If Condition is true ? Then value X : Otherwise
value Y
The typeof Operator
The typeof is a unary operator that is placed before its single operand, which can be of any type.
Its value is a string indicating the data type of the operand.
The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number,
string, or boolean value and returns true or false based on the evaluation.
Here is the list of return values for the typeof Operator :
Type
String Returned by typeof
Number
"number"
String
"string"
Boolean
"boolean"
Object
"object"
Function
"function"
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 161
SZABIST jstc Shaheed Benazirabad
Undefined
"undefined"
Null
"object"
JavaScript Functions
JavaScript Function Syntax
A function is written as a code block (inside curly { } braces), preceded by the function
keyword:
function functionname()
{
some code to be executed
}
The code inside the function will be executed when "someone" calls the function.
The function can be called directly when an event occurs (like when a user clicks a button), and
it can be called from "anywhere" by JavaScript code.
JavaScript is case sensitive. The function keyword must be written in lowercase letters, and
the function must be called with the same capitals as used in the function name.
Calling a Function with Arguments
When you call a function, you can pass along some values to it, these values are called
arguments or parameters.
These arguments can be used inside the function.
You can send as many arguments as you like, separated by commas (,)
myFunction(argument1,argument2)
Declare the argument, as variables, when you declare the function:
function myFunction(var1,var2)
{
some code
}
The variables and the arguments must be in the expected order. The first variable is given the
value of the first passed argument etc.
Example
<button onclick="myFunction('Harry Potter','Wizard')">Try it</button>
<script>
function myFunction(name,job)
{
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 162
SZABIST jstc Shaheed Benazirabad
alert("Welcome " + name + ", the " + job);
}
</script>
The function above will alert "Welcome Harry Potter, the Wizard" when the button is clicked.
The function is flexible, you can call the function using different arguments, and different
welcome messages will be given:
Example
<button onclick="myFunction('Harry Potter','Wizard')">Try it</button>
<button onclick="myFunction('Bob','Builder')">Try it</button>
Functions With a Return Value
Sometimes you want your function to return a value back to where the call was made.
This is possible by using the return statement.
When using the return statement, the function will stop executing, and return the specified value.
Syntax
function myFunction()
{
var x=5;
return x;
}
The function above will return the value 5.
Note: It is not the entire JavaScript that will stop executing, only the function. JavaScript will
continue executing code, where the function-call was made from.
The function-call will be replaced with the return value:
var myVar=myFunction();
The variable myVar holds the value 5, which is what the function "myFunction()" returns.
You can also use the return value without storing it as a variable:
document.getElementById("demo").innerHTML=myFunction();
The innerHTML of the "demo" element will be 5, which is what the function "myFunction()"
returns.
You can make a return value based on arguments passed into the function:
Example
Calculate the product of two numbers, and return the result:
function myFunction(a,b)
{
return a*b;
}
document.getElementById("demo").innerHTML=myFunction(4,3);
The innerHTML of the "demo" element will be:
12
The return statement is also used when you simply want to exit a function. The return value is
optional:
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 163
SZABIST jstc Shaheed Benazirabad
function myFunction(a,b)
{
if (a>b)
{
return;
}
x=a+b
}
The function above will exit the function if a>b, and will not calculate the sum of a and b.
Local JavaScript Variables
A variable declared (using var) within a JavaScript function becomes LOCAL and can only be
accessed from within that function. (the variable has local scope).
You can have local variables with the same name in different functions, because local variables
are only recognized by the function in which they are declared.
Local variables are deleted as soon as the function is completed.
Global JavaScript Variables
Variables declared outside a function, become GLOBAL, and all scripts and functions on the
web page can access it.
The Lifetime of JavaScript Variables
The lifetime JavaScript variables starts when they are declared.
Local variables are deleted when the function is completed.
Global variables are deleted when you close the page.
Assigning Values to Undeclared JavaScript Variables
If you assign a value to variable that has not yet been declared, the variable will automatically be
declared as a GLOBAL variable.
This statement:
carname="Volvo";
will declare the variable carname as a global variable , even if it is executed inside a function.
Conditional Statements
Very often when you write code, you want to perform different actions for different decisions.
You can use conditional statements in your code to do this.
In JavaScript we have the following conditional statements:



if statement - use this statement to execute some code only if a specified condition is true
if...else statement - use this statement to execute some code if the condition is true and
another code if the condition is false
if...else if....else statement - use this statement to select one of many blocks of code to be
executed
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 164
SZABIST jstc Shaheed Benazirabad

switch statement - use this statement to select one of many blocks of code to be executed
If Statement
Use the if statement to execute some code only if a specified condition is true.
Syntax
if (condition)
{
code to be executed if condition is true
}
Note that if is written in lowercase letters. Using uppercase letters (IF) will generate a JavaScript
error!
Example
Make a "Good day" greeting if the time is less than 20:00:
if (time<20)
{
x="Good day";
}
The result of x will be:
Good day
Notice that there is no ..else.. in this syntax. You tell the browser to execute some code only if
the specified condition is true.
If...else Statement
Use the if....else statement to execute some code if a condition is true and another code if the
condition is not true.
Syntax
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
Example
If the time is less than 20:00, you will get a "Good day" greeting, otherwise you will get a "Good
evening" greeting
if (time<20)
{
x="Good day";
}
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 165
SZABIST jstc Shaheed Benazirabad
else
{
x="Good evening";
}
The result of x will be:
Good day
If...else if...else Statement
Use the if....else if...else statement to select one of several blocks of code to be executed.
Syntax
if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if neither condition1 nor condition2 is true
}
Example
If the time is less than 10:00, you will get a "Good morning" greeting, if not, but the time is less
than 20:00, you will get a "Good day" greeting, otherwise you will get a "Good evening"
greeting:
if (time<10)
{
x="Good morning";
}
else if (time<20)
{
x="Good day";
}
else
{
x="Good evening";
}
The result of x will be:
Good day
The switch statement is used to perform different action based on different conditions.
The JavaScript Switch Statement
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 166
SZABIST jstc Shaheed Benazirabad
Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
This is how it works: First we have a single expression n (most often a variable), that is
evaluated once. The value of the expression is then compared with the values for each case in the
structure. If there is a match, the block of code associated with that case is executed. Use break
to prevent the code from running into the next case automatically.
Example
Display today's weekday-name. Note that Sunday=0, Monday=1, Tuesday=2, etc:
var day=new Date().getDay();
switch (day)
{
case 0:
x="Today it's Sunday";
break;
case 1:
x="Today it's Monday";
break;
case 2:
x="Today it's Tuesday";
break;
case 3:
x="Today it's Wednesday";
break;
case 4:
x="Today it's Thursday";
break;
case 5:
x="Today it's Friday";
break;
case 6:
x="Today it's Saturday";
break;
}
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 167
SZABIST jstc Shaheed Benazirabad
The result of x will be:
Today it's Monday
The default Keyword
Use the default keyword to specify what to do if there is no match:
Example
If it is NOT Saturday or Sunday, then write a default message:
var day=new Date().getDay();
switch (day)
{
case 6:
x="Today it's Saturday";
break;
case 0:
x="Today it's Sunday";
break;
default:
x="Looking forward to the Weekend";
}
The result of x will be:
Looking forward to the Weekend
JavaScript Loops
Loops are handy, if you want to run the same code over and over again, each time with a
different value.
Often this is the case when working with arrays:
Instead of writing:
document.write(cars[0] + "<br>");
document.write(cars[1] + "<br>");
document.write(cars[2] + "<br>");
document.write(cars[3] + "<br>");
document.write(cars[4] + "<br>");
document.write(cars[5] + "<br>");
You can write:
for (var i=0;i<cars.length;i++)
{
document.write(cars[i] + "<br>");
}
Different Kinds of Loops
JavaScript supports different kinds of loops:
 for - loops through a block of code a number of times
 for/in - loops through the properties of an object
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 168
SZABIST jstc Shaheed Benazirabad


while - loops through a block of code while a specified condition is true
do/while - also loops through a block of code while a specified condition is true
The For Loop
The for loop is often the tool you will use when you want to create a loop.
The for loop has the following syntax:
for (statement 1; statement 2; statement 3)
{
the code block to be executed
}
Statement 1 is executed before the loop (the code block) starts.
Statement 2 defines the condition for running the loop (the code block).
Statement 3 is executed each time after the loop (the code block) has been executed.
Example
for (var i=0; i<5; i++)
{
x=x + "The number is " + i + "<br>";
}
From the example above, you can read:
Statement 1 sets a variable before the loop starts (var i=0).
Statement 2 defines the condition for the loop to run (i must be less than 5).
Statement 3 increases a value (i++) each time the code block in the loop has been executed.
Statement 1
Normally you will use statement 1 to initiate the variable used in the loop (var i=0).
This is not always the case, JavaScript doesn't care, and statement 1 is optional.
You can initiate any (or many) values in statement 1:
Example:
for (var i=0,len=cars.length; i<len; i++)
{
document.write(cars[i] + "<br>");
}
And you can omit statement 1 (like when your values are set before the loop starts):
Example:
var i=2,len=cars.length;
for (; i<len; i++)
{
document.write(cars[i] + "<br>");
}
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 169
SZABIST jstc Shaheed Benazirabad
Statement 2
Often statement 2 is used to evaluate the condition of the initial variable.
This is not always the case, JavaScript doesn't care, and statement 2 is optional.
If statement 2 returns true, the loop will start over again, if it returns false, the loop will end.
If you omit statement 2, you must provide a break inside the loop. Otherwise the loop will
never end. This will crash your browser. Read about breaks in a later chapter of this
tutorial.
Statement 3
Often statement 3 increases the initial variable.
This is not always the case, JavaScript doesn't care, and statement 3 is optional.
Statement 3 could do anything. The increment could be negative (i--), or larger (i=i+15).
Statement 3 can also be omitted (like when you have corresponding code inside the loop):
Example:
var i=0,len=cars.length;
for (; i<len; )
{
document.write(cars[i] + "<br>");
i++;
}
The For/In Loop
The JavaScript for/in statement loops through the properties of an object:
Example
var person={fname:"John",lname:"Doe",age:25};
for (x in person)
{
txt=txt + person[x];
}
The While Loop
The while loop loops through a block of code as long as a specified condition is true.
Syntax
while (condition)
{
code block to be executed
}
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 170
SZABIST jstc Shaheed Benazirabad
Example
The loop in this example will continue to run as long as the variable i is less than 5:
Example
while (i<5)
{
x=x + "The number is " + i + "<br>";
i++;
}
If you forget to increase the variable used in the condition, the loop will never end. This will crash your
browser.
The Do/While Loop
The do/while loop is a variant of the while loop. This loop will execute the code block once,
before checking if the condition is true, then it will repeat the loop as long as the condition is
true.
Syntax
do
{
code block to be executed
}
while (condition);
Example
The example below uses a do/while loop. The loop will always be executed at least once, even if
the condition is false, because the code block is executed before the condition is tested:
Example
do
{
x=x + "The number is " + i + "<br>";
i++;
}
while (i<5);
Comparing For and While
If you have read the previous chapter, about the for loop, you will discover that a while loop is
much the same as a for loop, with statement 1 and statement 3 omitted.
The loop in this example uses a for loop to display all the values in the cars array:
Example
cars=["BMW","Volvo","Saab","Ford"];
var i=0;
for (;cars[i];)
{
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 171
SZABIST jstc Shaheed Benazirabad
document.write(cars[i] + "<br>");
i++;
}
The loop in this example uses a while loop to display all the values in the cars array:
Example
cars=["BMW","Volvo","Saab","Ford"];
var i=0;
while (cars[i])
{
document.write(cars[i] + "<br>");
i++;
}
The Break Statement
You have already seen the break statement used in an earlier chapter of this tutorial. It was used
to "jump out" of a switch() statement.
The break statement can also be used to jump out of a loop.
The break statement breaks the loop and continues executing the code after the loop (if any):
Example
for (i=0;i<10;i++)
{
if (i==3)
{
break;
}
x=x + "The number is " + i + "<br>";
}
Since the if statement has only one single line of code, the braces can be omitted:
for (i=0;i<10;i++)
{
if (i==3) break;
x=x + "The number is " + i + "<br>";
}
The Continue Statement
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.
This example skips the value of 3:
Example
for (i=0;i<=10;i++)
{
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 172
SZABIST jstc Shaheed Benazirabad
if (i==3) continue;
x=x + "The number is " + i + "<br>";
}
JavaScript Labels
As you have already seen, in the chapter about the switch statement, JavaScript statements can
be labeled.
To label JavaScript statements you precede the statements with a colon:
label:
statements
The break and the continue statements are the only JavaScript statements that can "jump out of"
a code block.
Syntax:
break labelname;
continue labelname;
The continue statement (with or without a label reference) can only be used inside a loop.
The break statement, without a label reference, can only be used inside a loop or a switch.
With a label reference, it can be used to "jump out of" any JavaScript code block:
Example
cars=["BMW","Volvo","Saab","Ford"];
list:
{
document.write(cars[0] + "<br>");
document.write(cars[1] + "<br>");
document.write(cars[2] + "<br>");
break list;
document.write(cars[3] + "<br>");
document.write(cars[4] + "<br>");
document.write(cars[5] + "<br>");
}
0
The try statement lets you test a block of code for errors.
The catch statement lets you handle the error.
The throw statement lets you create custom errors.
Errors Will Happen!
When the JavaScript engine is executing JavaScript code, different errors can occur:
It can be syntax errors, typically coding errors or typos made by the programmer.
It can be misspelled or missing features in the language (maybe due to browser differences).
It can be errors due to wrong input, from a user, or from an Internet server.
And, of course, it can be many other unforeseeable things.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 173
SZABIST jstc Shaheed Benazirabad
JavaScript Throws Errors
When an error occurs, when something goes wrong, the JavaScript engine will normally stop,
and generate an error message.
The technical term for this is: JavaScript will throw an error.
JavaScript try and catch
The try statement allows you to define a block of code to be tested for errors while it is being
executed.
The catch statement allows you to define a block of code to be executed, if an error occurs in the
try block.
The JavaScript statements try and catch come in pairs.
Syntax
try
{
//Run some code here
}
catch(err)
{
//Handle errors here
}
Examples
In the example below we have deliberately made a typo in the code in the try block.
The catch block catches the error in the try block, and executes code to handle it:
Example
<!DOCTYPE html>
<html>
<head>
<script>
var txt="";
function message()
{
try
{
adddlert("Welcome guest!");
}
catch(err)
{
txt="There was an error on this page.\n\n";
txt+="Error description: " + err.message + "\n\n";
txt+="Click OK to continue.\n\n";
alert(txt);
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 174
SZABIST jstc Shaheed Benazirabad
}
}
</script>
</head>
<body>
<input type="button" value="View message" onclick="message()">
</body>
</html>
The Throw Statement
The throw statement allows you to create a custom error.
The correct technical term is to create or throw an exception.
If you use the throw statement together with try and catch, you can control program flow and
generate custom error messages.
Syntax
throw exception
The exception can be a JavaScript String, a Number, a Boolean or an Object.
Example
This example examines the value of an input variable. If the value is wrong, an exception (error)
is thrown. The error is caught by the catch statement and a custom error message is displayed:
Example
<script>
function myFunction()
{
try
{
var x=document.getElementById("demo").value;
if(x=="") throw "empty";
if(isNaN(x)) throw "not a number";
if(x>10) throw "too high";
if(x<5) throw "too low";
}
catch(err)
{
var y=document.getElementById("mess");
y.innerHTML="Error: " + err + ".";
}
}
</script>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 175
SZABIST jstc Shaheed Benazirabad
<h1>My First JavaScript</h1>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="mess"></p>
JavaScript Form Validation
JavaScript can be used to validate data in HTML forms before sending off the content to a
server.
Form data that typically are checked by a JavaScript could be:
 has the user left required fields empty?
 has the user entered a valid e-mail address?
 has the user entered a valid date?
 has the user entered text in a numeric field?
Required Fields
The function below checks if a field has been left empty. If the field is blank, an alert box alerts a
message, the function returns false, and the form will not be submitted:
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
The function above could be called when a form is submitted:
Example
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()"
method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
E-mail Validation
The function below checks if the content has the general syntax of an email.
This means that the input data must contain an @ sign and at least one dot (.). Also, the @ must
not be the first character of the email address, and the last dot must be present after the @ sign,
and minimum 2 characters before the end:
function validateForm()
{
var x=document.forms["myForm"]["email"].value;
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 176
SZABIST jstc Shaheed Benazirabad
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
The function above could be called when a form is submitted:
Example
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();"
method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>
JS HTML DOM
The HTML DOM (Document Object Model)
When a web page is loaded, the browser creates a Document Object Model of the page.
The HTML DOM model is constructed as a tree of Objects:
The HTML DOM Tree
With a programmable object model, JavaScript gets all the power it needs to create dynamic
HTML:
 JavaScript can change all the HTML elements in the page
 JavaScript can change all the HTML attributes in the page
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 177
SZABIST jstc Shaheed Benazirabad


JavaScript can change all the CSS styles in the page
JavaScript can react to all the events in the page
Finding HTML Elements
Often, with JavaScript, you want to manipulate HTML elements.
To do so, you have to find the elements first. There are a couple of ways to do this:
 Finding HTML elements by id
 Finding HTML elements by tag name
 Finding HTML elements by class name
Finding HTML Elements by Id
The easiest way to find HTML elements in the DOM, is by using the element id.
This example finds the element with id="intro":
Example
var x=document.getElementById("intro");
If the element is found, the method will return the element as an object (in x).
If the element is not found, x will contain null.
Finding HTML Elements by Tag Name
This example finds the element with id="main", and then finds all <p> elements inside "main":
Example
var x=document.getElementById("main");
var y=x.getElementsByTagName("p");
HTML DOM Tutorial
In the next chapters of this tutorial you will learn:
 How to change the content (innerHTML) of HTML elements
 How to change the style (CSS) of HTML elements
 How to react to HTML DOM events
 How to add or delete HTML elements
Changing the HTML Output Stream
JavaScript can create dynamic HTML content:
Date: Mon Jun 10 2013 12:57:35 GMT+0500 (Pakistan Standard Time)
In JavaScript, document.write() can be used to write directly to the HTML output stream:
Example
<!DOCTYPE html>
<html>
<body>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 178
SZABIST jstc Shaheed Benazirabad
<script>
document.write(Date());
</script>
</body>
</html>
Changing HTML Content
The easiest way to modify the content of an HTML element is by using the innerHTML
property.
To change the content of an HTML element, use this syntax:
document.getElementById(id).innerHTML=new HTML
This example changes the content of a <p> element:
Example
<html>
<body>
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML="New text!";
</script>
</body>
</html>
This example changes the content of an <h1> element:
Example
<!DOCTYPE html>
<html>
<body>
<h1 id="header">Old Header</h1>
<script>
var element=document.getElementById("header");
element.innerHTML="New Header";
</script>
</body>
</html>
Example explained:
 The HTML document above contains an <h1> element with id="header"
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 179
SZABIST jstc Shaheed Benazirabad


We use the HTML DOM to get the element with id="header"
A JavaScript changes the content (innerHTML) of that element
Changing an HTML Attribute
To change the attribute of an HTML element, use this syntax:
document.getElementById(id).attribute=new value
This example changes the src attribute of an <img> element:
Example
<!DOCTYPE html>
<html>
<body>
<img id="image" src="smiley.gif">
<script>
document.getElementById("image").src="landscape.jpg";
</script>
</body>
</html>
Example explained:
 The HTML document above contains an <img> element with id="image"
 We use the HTML DOM to get the element with id="image"
 A JavaScript changes the src attribute of that element from "smiley.gif" to
"landscape.jpg"
Changing HTML Style



To change the style of an HTML element, use this syntax:
document.getElementById(id).style.property=new style
The following example changes the style of a <p> element:


Example
<html>
<body>
<p id="p2">Hello World!</p>
<script>
document.getElementById("p2").style.color="blue";
</script>
<p>The paragraph above was changed by a script.</p>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 180
SZABIST jstc Shaheed Benazirabad
</body>
</html>
This example changes the style of the HTML element with id="id1", when the user clicks a
button:
Example
<!DOCTYPE html>
<html>
<body>
<h1 id="id1">My Heading 1</h1>
<button type="button"
onclick="document.getElementById('id1').style.color='red'">
Click Me!</button>
</body>
</html>
HTML DOM allows JavaScript to react to HTML events.
Example
Mouse Over Me
Click Me
Reacting to Events
A JavaScript can be executed when an event occurs, like when a user clicks on an HTML
element.
To execute code when a user clicks on an element, add JavaScript code to an HTML event
attribute:
onclick=JavaScript
Examples of HTML events:
 When a user clicks the mouse
 When a web page has loaded
 When an image has been loaded
 When the mouse moves over an element
 When an input field is changed
 When an HTML form is submitted
 When a user strokes a key
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 181
SZABIST jstc Shaheed Benazirabad
In this example, the content of the <h1> element is changed when a user clicks on it:
Example
<!DOCTYPE html>
<html>
<body>
<h1 onclick="this.innerHTML='Ooops!'">Click on this text!</h1>
</body>
</html>
In this example, a function is called from the event handler:
Example
<!DOCTYPE html>
<html>
<head>
<script>
function changetext(id)
{
id.innerHTML="Ooops!";
}
</script>
</head>
<body>
<h1 onclick="changetext(this)">Click on this text!</h1>
</body>
</html>
HTML Event Attributes
To assign events to HTML elements you can use event attributes.
Example
Assign an onclick event to a button element:
<button onclick="displayDate()">Try it</button>
Assign Events Using the HTML DOM
The HTML DOM allows you to assign events to HTML elements using JavaScript:
Example
Assign an onclick event to a button element:
<script>
document.getElementById("myBtn").onclick=function(){displayDate()};
</script>
In the example above, a function named displayDate is assigned to an HTML element with the
id=myBtn".
The function will be executed when the button is clicked.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 182
SZABIST jstc Shaheed Benazirabad
The onload and onunload Events
The onload and onunload events are triggered when the user enters or leaves the page.
The onload event can be used to check the visitor's browser type and browser version, and load
the proper version of the web page based on the information.
The onload and onunload events can be used to deal with cookies.
Example
<body onload="checkCookies()">
The onchange Event
The onchange event are often used in combination with validation of input fields.
Below is an example of how to use the onchange. The upperCase() function will be called when
a user changes the content of an input field.
Example
<input type="text" id="fname" onchange="upperCase()">
The onmouseover and onmouseout Events
The onmouseover and onmouseout events can be used to trigger a function when the user
mouses over, or out of, an HTML element.
The onmousedown, onmouseup and onclick Events
The onmousedown, onmouseup, and onclick events are all parts of a mouse-click. First when a
mouse-button is clicked, the onmousedown event is triggered, then, when the mouse-button is
released, the onmouseup event is triggered, finally, when the mouse-click is completed, the
onclick event is triggered.
Creating New HTML Elements
To add a new element to the HTML DOM, you must create the element (element node) first, and
then append it to an existing element.
Example
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para=document.createElement("p");
var node=document.createTextNode("This is new.");
para.appendChild(node);
var element=document.getElementById("div1");
element.appendChild(para);
</script>
Example Explained
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 183
SZABIST jstc Shaheed Benazirabad
This code creates a new <p> element:
var para=document.createElement("p");
To add text to the <p> element, you must create a text node first. This code creates a text node:
var node=document.createTextNode("This is a new paragraph.");
Then you must append the text node to the <p> element:
para.appendChild(node);
Finally you must append the new element to an existing element.
This code finds an existing element:
var element=document.getElementById("div1");
This code appends the new element to the existing element:
element.appendChild(para);
Removing Existing HTML Elements
To remove an HTML element, you must know the parent of the element:
Example
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var parent=document.getElementById("div1");
var child=document.getElementById("p1");
parent.removeChild(child);
</script>
Example Explained
This HTML document contains a <div> element with two child nodes (two <p> elements):
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
Find the element with id="div1":
var parent=document.getElementById("div1");
Find the <p> element with id="p1":
var child=document.getElementById("p1");
Remove the child from the parent:
parent.removeChild(child);
It would be nice to be able to remove an element without referring to the parent.
But sorry. The DOM needs to know both the element you want to remove, and its parent.
Here is a common workaround: Find the child you want to remove, and use its parentNode
property to find the parent:
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 184
SZABIST jstc Shaheed Benazirabad
var child=document.getElementById("p1");
child.parentNode.removeChild(child);
HTML DOM Tutorial
In the HTML DOM section of this JavaScript tutorial you have learned:
 How to change the content (innerHTML) of HTML elements
 How to change the style (CSS) of HTML elements
 How to react to HTML DOM events
 How to add or delete HTML elements
Creating JavaScript Objects
<!DOCTYPE html>
<html>
<body>
<script>
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
this.changeName=changeName;
function changeName(name)
{
this.lastname=name;
}
}
myMother=new person("Sally","Rally",48,"green");
myMother.changeName("Doe");
document.write(myMother.lastname);
</script>
</body>
</html>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 185
SZABIST jstc Shaheed Benazirabad
JS Objects
JavaScript has several built-in objects, like String, Date, Array, and more.
An object is just a special kind of data, with properties and methods.
The syntax for accessing the property of an object is:
objectName.propertyName
For String Length
var message="Hello World!";
var x=message.length;
For UpperCase
var message="Hello world!";
var x=message.toUpperCase();
Not a Number
The NaN property represents "Not-a-Number" value. This property indicates that a value is not a
legal number.
The NaN property is the same as the Number.Nan property.
Tip: Use the isNaN() global function to check if a value is a NaN value.
JavaScript toExponential() Method
Syntax
Number.NaN
Example
Convert a number into an exponential notation:
var num = 5.56789;
var n=num.toExponential()
The result of n will be:
5.56789e+0
JavaScript toFixed() Method
Convert a number into a string, keeping only two decimals:
var num = 5.56789;
var n=num.toFixed(2);
The result of n will be:
5.57
JavaScript toPrecision() Method
Example
Format a number into a specified length:
var num = new Number(13.3714);
var n=num.toPrecision(2);
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 186
SZABIST jstc Shaheed Benazirabad
The result of n will be:
13
JavaScript toString() Method
Example
Convert a number to a string:
var num = 15;
var n = num.toString();
The result of n will be:
15
JavaScript valueOf() Method
Example
Return the primitive value of a Number object:
var num = 15;
var n = num.valueOf();
The result of n will be:
15
JavaScript Strings Methods
String Length
var txt="Hello World!";
document.write(txt.length);
var txt="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.write(txt.length);
Finding a String in a String
The indexOf() method returns the position (as a number) of the first found occurrence of a
specified text inside a string:
Example
var str="Hello world, welcome to the universe.";
var n=str.indexOf("welcome");
Matching Content
The match() method can be used to search for a matching content in a string:
Example
var str="Hello world!";
document.write(str.match("world") + "<br>");
document.write(str.match("World") + "<br>");
document.write(str.match("world!"));
Replacing Content
The replace() method replaces a specified value with another value in a string.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 187
SZABIST jstc Shaheed Benazirabad
Example
str="Please visit Microsoft!"
var n=str.replace("Microsoft","W3Schools");
Upper Case and Lower Case
A string is converted to upper/lower case with the methods toUpperCase() / toLowerCase():
Example
var txt="Hello World!";
// String
var txt1=txt.toUpperCase(); // txt1 is txt converted to upper
var txt2=txt.toLowerCase(); // txt2 is txt converted to lower
Convert a String to an Array
A string is converted to an array with the built in method string.split():
Example
txt="a,b,c,d,e" // String
txt.split(","); // Split on commas
txt.split(" "); // Split on spaces
txt.split("|"); // Split on pipe
Math Object
var x=Math.PI;
var y=Math.sqrt(16);
Mathematical Methods
document.write(Math.round(4.7));
The following example uses the random() method of the Math object to return a random number
between 0 and 1:
document.write(Math.floor(Math.random()*11));
The following example uses the floor() and random() methods of the Math object to return a random
number between 0 and 10:
document.write(Math.max(5,10));
document.write(Math.min(5,10));
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 188
SZABIST jstc Shaheed Benazirabad
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables
could look like this:
var car1="Saab";
var car2="Volvo";
var car3="BMW";
However, what if you want to loop through the cars and find a specific one? And what if you had
not 3 cars, but 300?
The solution is an array!
An array can hold many values under a single name, and you can access the values by referring
to an index number.
Create an Array
An array can be created in three ways.
The following code creates an Array object called myCars:
1: Regular:
var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
2: Condensed:
var myCars=new Array("Saab","Volvo","BMW");
3: Literal:
var myCars=["Saab","Volvo","BMW"];
Access an Array
You refer to an element in an array by referring to the index number.
This statement access the value of the first element in myCars:
var name=myCars[0];
This statement modifies the first element in myCars:
myCars[0]="Opel";
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 189
SZABIST jstc Shaheed Benazirabad
What is RegExp?
A regular expression is an object that describes a pattern of characters.
When you search in a text, you can use a pattern to describe what you are searching for.
A simple pattern can be one single character.
A more complicated pattern can consist of more characters, and can be used for parsing, format
checking, substitution and more.
Regular expressions are used to perform powerful pattern-matching and "search-and-replace"
functions on text.
Syntax
var patt=new RegExp(pattern,modifiers);
or more simply:
var patt=/pattern/modifiers;
 pattern specifies the pattern of an expression
 modifiers specify if a search should be global, case-sensitive, etc.
RegExp Modifiers
Modifiers are used to perform case-insensitive and global searches.
The i modifier is used to perform case-insensitive matching.
The g modifier is used to perform a global match (find all matches rather than stopping after the
first match).
Example 1
Do a case-insensitive search for "w3schools" in a string:
var str="Visit W3Schools";
var patt1=/w3schools/i;
The marked text below shows where the expression gets a match:
Visit W3Schools
Example
<!DOCTYPE html>
<html>
<body>
<script>
var str = "Visit W3Schools";
var patt1 = /w3schools/i;
document.write(str.match(patt1));
</script>
</body>
</html>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 190
SZABIST jstc Shaheed Benazirabad
Example 2
Do a global search for "is":
var str="Is this all there is?";
var patt1=/is/g;
The marked text below shows where the expression gets a match:
Is this all there is?
<!DOCTYPE html>
<html>
<body>
<script>
var str="Is this all there is?";
var patt1=/is/g;
document.write(str.match(patt1));
</script>
</body>
</html>
Example 3
Do a global, case-insensitive search for "is":
var str="Is this all there is?";
var patt1=/is/gi;
The marked text below shows where the expression gets a match:
Is this all there is?
<!DOCTYPE html>
<html>
<body>
<script>
var str="Is this all there is?";
var patt1=/is/gi;
document.write(str.match(patt1));
</script>
</body>
</html>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 191
SZABIST jstc Shaheed Benazirabad
test()
The test() method searches a string for a specified value, and returns true or false, depending on
the result.
The following example searches a string for the character "e":
Example
var patt1=new RegExp("e");
document.write(patt1.test("The best things in life are free"));
Since there is an "e" in the string, the output of the code above will be:
true
<!DOCTYPE html>
<html>
<body>
<script>
var patt1=new RegExp("e");
document.write(patt1.test("The best things in life are free"));
</script>
</body>
</html>
exec()
The exec() method searches a string for a specified value, and returns the text of the found value.
If no match is found, it returns null.
The following example searches a string for the character "e":
Example 1
var patt1=new RegExp("e");
document.write(patt1.exec("The best things in life are free"));
Since there is an "e" in the string, the output of the code above will be:
E
Example
<!DOCTYPE html>
<html>
<body>
<script>
var patt1=new RegExp("e");
document.write(patt1.exec("The best things in life are free"));
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 192
SZABIST jstc Shaheed Benazirabad
</script>
</body>
</html>
Regular Expressions and RegExp Object
A regular expression is an object that describes a pattern of characters.
The JavaScript RegExp class represents regular expressions, and both String and RegExp define
methods that use regular expressions to perform powerful pattern-matching and search-andreplace functions on text.
Syntax:
A regular expression could be defined with the RegExp( ) constructor like this:
var pattern = new RegExp(pattern, attributes);
or simply
var pattern = /pattern/attributes;
Here is the description of the parameters:
 pattern: A string that specifies the pattern of the regular expression or another regular
expression.
 attributes: An optional string containing any of the "g", "i", and "m" attributes that
specify global, case-insensitive, and multiline matches, respectively.
Brackets:
Brackets ([]) have a special meaning when used in the context of regular expressions. They are
used to find a range of characters.
Expression
Description
[...]
Any one character between the brackets.
[^...]
Any one character not between the brackets.
[0-9]
It matches any decimal digit from 0 through 9.
[a-z]
It matches any character from lowercase a through lowercase z.
[A-Z]
It matches any character from uppercase A through uppercase Z.
[a-Z]
It matches any character from lowercase a through uppercase Z.
The ranges shown above are general; you could also use the range [0-3] to match any decimal
digit ranging from 0 through 3, or the range [b-v] to match any lowercase character ranging from
b through v.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 193
SZABIST jstc Shaheed Benazirabad
Quantifiers:
The frequency or position of bracketed character sequences and single characters can be denoted
by a special character. Each pecial character having a specific connotation. The +, *, ?, and $
flags all follow a character sequence.
Expression
Description
p+
It matches any string containing at least one p.
p*
It matches any string containing zero or more p's.
p?
It matches any string containing one or more p's.
p{N}
It matches any string containing a sequence of N p's
p{2,3}
It matches any string containing a sequence of two or three p's.
p{2, }
It matches any string containing a sequence of at least two p's.
p$
It matches any string with p at the end of it.
^p
It matches any string with p at the beginning of it.
Examples:
Following examples will clear your concepts about matching chracters.
Expression
Description
[^a-zA-Z]
It matches any string not containing any of the characters ranging from a through z and A
through Z.
p.p
It matches any string containing p, followed by any character, in turn followed by another
p.
^.{2}$
It matches any string containing exactly two characters.
<b>(.*)</b> It matches any string enclosed within <b> and </b>.
p(hp)*
It matches any string containing a p followed by zero or more instances of the sequence
hp.
Literal characters:
Character
Description
Alphanumeric Itself
\0
The NUL character (\u0000)
\t
Tab (\u0009)
\n
Newline (\u000A)
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 194
SZABIST jstc Shaheed Benazirabad
\v
Vertical tab (\u000B)
\f
Form feed (\u000C)
\r
Carriage return (\u000D)
\xnn
The Latin character specified by the hexadecimal number nn; for example, \x0A is the
same as \n
\uxxxx
The Unicode character specified by the hexadecimal number xxxx; for example, \u0009
is the same as \t
\cX
The control character ^X; for example, \cJ is equivalent to the newline character \n
Metacharacters
A metacharacter is simply an alphabetical character preceded by a backslash that acts to give the
combination a special meaning.
For instance, you can search for large money sums using the '\d' metacharacter: /([\d]+)000/,
Here \d will search for any string of numerical character.
Following is the list of metacharacters which can be used in PERL Style Regular Expressions.
Character
.
\s
\S
\d
\D
\w
\W
[\b]
[aeiou]
[^aeiou]
(foo|bar|baz)
Description
a single character
a whitespace character (space, tab, newline)
non-whitespace character
a digit (0-9)
a non-digit
a word character (a-z, A-Z, 0-9, _)
a non-word character
a literal backspace (special case).
matches a single character in the given set
matches a single character outside the given set
matches any of the alternatives specified
Modifiers
Several modifiers are available that can make your work with regexps much easier, like case
sensitivity, searching in multiple lines etc.
Modifier
Description
i
Perform case-insensitive matching.
m
Specifies that if the string has newline or carriage return characters, the ^ and $ operators
will now match against a newline boundary, instead of a string boundary
g
Perform a global matchthat is, find all matches rather than stopping after the first match.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 195
SZABIST jstc Shaheed Benazirabad
RegExp Properties:
Here is a list of each property and their description.
Property
Description
constructor
Specifies the function that creates an object's prototype.
global
Specifies if the "g" modifier is set.
ignoreCase
Specifies if the "i" modifier is set.
lastIndex
The index at which to start the next match.
multiline
Specifies if the "m" modifier is set.
source
The text of the pattern.
RegExp Methods:
Here is a list of each method and its description.
Method
Description
exec()
Executes a search for a match in its string parameter.
test()
Tests for a match in its string parameter.
toSource()
Returns an object literal representing the specified object; you can use this value to
create a new object.
toString()
Returns a string representing the specified obje
What is an Event ?
JavaScript's interaction with HTML is handled through events that occur when the user or
browser manipulates a page.
When the page loads, that is an event. When the user clicks a button, that click, too, is an event.
Another example of events are like pressing any key, closing window, resizing window etc.
Developers can use these events to execute JavaScript coded responses, which cause buttons to
close windows, messages to be displayed to users, data to be validated, and virtually any other
type of response imaginable to occur.
Events are a part of the Document Object Model (DOM) Level 3 and every HTML element have
a certain set of events which can trigger JavaScript Code.
Please go through this small tutorial for a better understanding HTML Event Reference. Here we
will see few examples to understand a relation between Event and JavaScript:
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 196
SZABIST jstc Shaheed Benazirabad
onclick Event Type:
This is the most frequently used event type which occurs when a user clicks mouse left button.
You can put your validation, warning etc against this event type.
Example:
<html>
<head>
<script type="text/javascript">
<!-function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
This will produce following result and when you click Hello button then onclick event will occur
which will trigger sayHello() function.
onsubmit event type:
Another most important event type is onsubmit. This event occurs when you try to submit a
form. So you can put your form validation against this event type.
Here is simple example showing its usage. Here we are calling a validate() function before
submitting a form data to the webserver. If validate() function returns true the form will be
submitted otherwise it will not submit the data.
Example:
<html>
<head>
<script type="text/javascript">
<!-function validation() {
all validation goes here
.........
return either true or false
}
//-->
</script>
</head>
<body>
<form method="POST" action="t.cgi" onsubmit="return validate()">
.......
<input type="submit" value="Submit" />
</form>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 197
SZABIST jstc Shaheed Benazirabad
</body>
</html>
onmouseover and onmouseout:
These two event types will help you to create nice effects with images or even with text as well.
The onmouseover event occurs when you bring your mouse over any element and the
onmouseout occurs when you take your mouse out from that element.
Example:
Following example shows how a division reacts when we bring our mouse in that division:
<html>
<head>
<script type="text/javascript">
<!-function over() {
alert("Mouse Over");
}
function out() {
alert("Mouse Out");
}
//-->
</script>
</head>
<body>
<div onmouseover="over()" onmouseout="out()">
<h2> This is inside the division </h2>
</div>
</body>
</html>
You can change different images using these two event types or you can create help baloon to
help your users.
HTML 4 Standard Events
The standard HTML 4 events are listed here for your reference. Here script indicates a Javascript
function to be executed agains that event.
Event
Value
Description
onchange
script
Script runs when the element changes
onsubmit
script
Script runs when the form is submitted
onreset
script
Script runs when the form is reset
onselect
script
Script runs when the element is selected
onblur
script
Script runs when the element loses focus
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 198
SZABIST jstc Shaheed Benazirabad
onfocus
script
Script runs when the element gets focus
onkeydown
script
Script runs when key is pressed
onkeypress
script
Script runs when key is pressed and released
onkeyup
script
Script runs when key is released
onclick
script
Script runs when a mouse click
ondblclick
script
Script runs when a mouse double-click
onmousedown
script
Script runs when mouse button is pressed
onmousemove
script
Script runs when mouse pointer moves
onmouseout
script
Script runs when mouse pointer moves out of an element
onmouseover
script
Script runs when mouse pointer moves over an element
onmouseup
script
Script runs when mouse button is released
What is page redirection ?
When you click a URL to reach to a page X but internally you are directed to another page Y that
simply happens because of page re-direction. This concept is different from JavaScript Page
Refresh.
There could be various reasons why you would like to redirect from original page. I'm listing
down few of the reasons:
 You did not like the name of your domain and you are moving to a new one. Same time
you want to direct your all visitors to new site. In such case you can maintain your old
domain but put a single page with a page re-direction so that your all old domain visitors
can come to your new domain.
 You have build-up various pages based on browser versions or their names or may be
based on different countries, then instead of using your server side page redirection you
can use client side page redirection to land your users on appropriate page.
 The Search Engines may have already indexed your pages. But while moving to another
domain then you would not like to lose your visitors coming through search engines. So
you can use client side page redirection. But keep in mind this should not be done to
make search engine a fool otherwise this could get your web site banned.
How Page Re-direction works ?
Example 1:
This is very simple to do a page redirect using JavaScript at client side. To redirect your site
visitors to a new page, you just need to add a line in your head section as follows:
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 199
SZABIST jstc Shaheed Benazirabad
<head>
<script type="text/javascript">
<!-window.location="http://www.newlocation.com";
//-->
</script>
</head>
Example 2:
You can show an appropriate message to your site visitors before redirecting them to a new page.
This would need a bit time delay to load a new page. Following is the simple example to
implement the same:
<head>
<script type="text/javascript">
<!-function Redirect()
{
window.location="http://www.newlocation.com";
}
document.write("You will be redirected to main page in 10 sec.");
setTimeout('Redirect()', 10000);
//-->
</script>
</head>
Here setTimeout() is a built-in JavaScript function which can be used to execute another function
after a given time interval.
Example 3:
Following is the example to redirect site visitors on different pages based on their browsers :
<head>
<script type="text/javascript">
<!-var browsername=navigator.appName;
if( browsername == "Netscape" )
{
window.location="http://www.location.com/ns.htm";
}
else if ( browsername =="Microsoft Internet Explorer")
{
window.location="http://www.location.com/ie.htm";
}
else
{
window.location="http://www.location.com/other.htm";
}
//-->
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 200
SZABIST jstc Shaheed Benazirabad
</script>
</head>
JavaScript - Dialog Boxes
JavaScript supports three important types of dialog boxes. These dialog boxes can be used to
raise and alert, or to get confirmation on any input or to have a kind of input from the users.
Here we will see each dialog box one by one:
Alert Dialog Box:
An alert dialog box is mostly used to give a warning message to the users. Like if one input field
requires to enter some text but user does not enter that field then as a part of validation you can
use alert box to give warning message as follows:
<head>
<script type="text/javascript">
<!-alert("Warning Message");
//-->
</script>
</head>
Nonetheless, an alert box can still be used for friendlier messages. Alert box gives only one
button "OK" to select and proceed.
Confirmation Dialog Box:
A confirmation dialog box is mostly used to take user's consent on any option. It displays a
dialog box with two buttons: OK and Cancel.
If the user clicks on OK button the window method confirm() will return true. If the user clicks
on the Cancel button confirm() returns false. You can use confirmation dialog box as follows:
<head>
<script type="text/javascript">
<!-var retVal = confirm("Do you want to continue ?");
if( retVal == true ){
alert("User wants to continue!");
return true;
}else{
alert("User does not want to continue!");
return false;
}
//-->
</script>
</head>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 201
SZABIST jstc Shaheed Benazirabad
Prompt Dialog Box:
The prompt dialog box is very useful when you want to pop-up a text box to get user input. Thus
it enable you to interact with the user. The user needs to fill in the field and then click OK.
This dialog box is displayed using a method called prompt() which takes two parameters (i) A
label which you want to display in the text box (ii) A default string to display in the text box.
This dialog box with two buttons: OK and Cancel. If the user clicks on OK button the window
method prompt() will return entered value from the text box. If the user clicks on the Cancel
button the window method prompt() returns null.
You can use prompt dialog box as follows:
<head>
<script type="text/javascript">
<!-var retVal = prompt("Enter your name : ", "your name here");
alert("You have entered : " + retVal );
//-->
</script>
</head>
JavaScript - Void Keyword
The void is an important keyword in JavaScript which can be used as a unary operator that
appears before its single operand, which may be of any type.
This operator specifies an expression to be evaluated without returning a value. Its syntax could
be one of the following:
<head>
<script type="text/javascript">
<!-void func()
javascript:void func()
or:
void(func())
javascript:void(func())
//-->
</script>
</head>
Example 1:
The most common use for this operator is in a client-side javascript: URL, where it allows you to
evaluate an expression for its side effects without the browser displaying the value of the
evaluated expression.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 202
SZABIST jstc Shaheed Benazirabad
Here the expression alert('Warning!!!') is evaluated but it is not loaded back into the current
document:
<head>
<script type="text/javascript">
<!-//-->
</script>
</head>
<body>
<a href="javascript:void(alert('Warning!!!'))">Click me!</a>
</body>
Example 2:
Another example the following link does nothing because the expression "0" has no effect in
JavaScript. Here the expression "0" is evaluated but it is not loaded back into the current
document:
<head>
<script type="text/javascript">
<!-//-->
</script>
</head>
<body>
<a href="javascript:void(0))">Click me!</a>
</body>
Example 3:
Another use for void is to purposely generate the undefined value as follows:
<head>
<script type="text/javascript">
<!-function getValue(){
var a,b,c;
a = void ( b = 5, c = 7 );
document.write('a = ' + a + ' b = ' + b +' c = ' + c );
}
//-->
</script>
</head>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 203
SZABIST jstc Shaheed Benazirabad
Javascript - Page Printing
Many times you would like to give a button at your webpage to print out the content of that web
page via an actual printer.
JavaScript helps you to implement this functionality using print function of window object.
The JavaScript print function window.print() will print the current web page when executed.
You can call this function directly using onclick event as follows:
<head>
<script type="text/javascript">
<!-//-->
</script>
</head>
<body>
<form>
<input type="button" value="Print" onclick="window.print()" />
</form>
</body>
This will produce following button which let you print this page. Try it by clicking:
This serves your purpose to get page printed out, but this is not a recommended way of giving
printing facility. A printer friendly page is really just a page with text, no images, graphics, or
advertising.
You can do one of the followings to make a page printer friendly:
 Make a copy of the page and leave out unwanted text and graphics, then link to that
printer friendly page from the original. Check Example.
 If you do not want to keep extra copy of a page then you can mark your printable text
using proper comments like <!-- PRINT STARTS HERE -->..... <!-- PRINT ENDS
HERE --> and then you can use PERL or any other script in background to purge
printable text and display for final printing. Our site is using same method to give print
facility to our site visitors. Check Example.
How to print a page:
If someone is providing none of the above facilities then you can use browser's standard toolbar
to get web pages printed out. Follow the link as follows:
File --> Print --> Click OK button.
JavaScript - Errors & Exceptions Handling
There are three types of errors in programming: (a) Syntax Errors and (b) Runtime Errors (c)
Logical Errors:
Syntax errors:
Syntax errors, also called parsing errors, occur at compile time for traditional programming
languages and at interpret time for JavaScript.
For example, the following line causes a syntax error because it is missing a closing parenthesis:
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 204
SZABIST jstc Shaheed Benazirabad
<script type="text/javascript">
<!-window.print(;
//-->
</script>
When a syntax error occurs in JavaScript, only the code contained within the same thread as the
syntax error is affected and code in other threads gets executed assuming nothing in them
depends on the code containing the error.
Runtime errors:
Runtime errors, also called exceptions, occur during execution (after compilation/interpretation).
For example, the following line causes a run time error because here syntax is correct but at run
time it is trying to call a non existed method:
<script type="text/javascript">
<!-window.printme();
//-->
</script>
Exceptions also affect the thread in which they occur, allowing other JavaScript threads to
continue normal execution.
Logical errors:
Logic errors can be the most difficult type of errors to track down. These errors are not the result
of a syntax or runtime error. Instead, they occur when you make a mistake in the logic that drives
your script and you do not get the result you expected.
You can not catch those errors, because it depends on your business requirement what type of
logic you want to put in your program.
The try...catch...finally Statement:
The latest versions of JavaScript added exception handling capabilities. JavaScript implements
the try...catch...finally construct as well as the throw operator to handle exceptions.
You can catch programmer-generated and runtime exceptions, but you cannot catch JavaScript
syntax errors.
Here is the try...catch...finally block syntax:
<script type="text/javascript">
<!-try {
// Code to run
[break;]
} catch ( e ) {
// Code to run if an exception occurs
[break;]
}[ finally {
// Code that is always executed regardless of
// an exception occurring
}]
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 205
SZABIST jstc Shaheed Benazirabad
//-->
</script>
The try block must be followed by either exactly one catch block or one finally block (or one of
both). When an exception occurs in the try block, the exception is placed in e and the catch
block is executed. The optional finally block executes unconditionally after try/catch.
Examples:
Here is one example where we are trying to call a non existing function this is causing an
exception raise. Let us see how it behaves without with try...catch:
<html>
<head>
<script type="text/javascript">
<!-function myFunc()
{
var a = 100;
alert("Value of variable a is : " + a );
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>
Now let us try to catch this exception using try...catch and display a user friendly message. You
can also suppress this message, if you want to hide this error from a user.
<html>
<head>
<script type="text/javascript">
<!-function myFunc()
{
var a = 100;
try {
alert("Value of variable a is : " + a );
} catch ( e ) {
alert("Error: " + e.description );
}
}
//-->
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 206
SZABIST jstc Shaheed Benazirabad
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>
You can use finally block which will always execute unconditionally after try/catch. Here is an
example:
<html>
<head>
<script type="text/javascript">
<!-function myFunc()
{
var a = 100;
try {
alert("Value of variable a is : " + a );
}catch ( e ) {
alert("Error: " + e.description );
}finally {
alert("Finally block will always execute!" );
}
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>
The throw Statement:
You can use throw statement to raise your built-in exceptions or your customized exceptions.
Later these exceptions can be captured and you can take an appropriate action.
Following is the example showing usage of throw statement.
<html>
<head>
<script type="text/javascript">
<!-function myFunc()
{
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 207
SZABIST jstc Shaheed Benazirabad
var a = 100;
var b = 0;
try{
if ( b == 0 ){
throw( "Divide by zero error." );
}else{
var c = a / b;
}
}catch ( e ) {
alert("Error: " + e );
}
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>
You can raise an exception in one function using a string, integer, Boolean or an object and then
you can capture that exception either in the same function as we did above, or in other function
using try...catch block.
The onerror() Method
The onerror event handler was the first feature to facilitate error handling for JavaScript. The
error event is fired on the window object whenever an exception occurs on the page. Example:
<html>
<head>
<script type="text/javascript">
<!-window.onerror = function () {
alert("An error occurred.");
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>
The onerror event handler provides three pieces of information to identify the exact nature of
the error:
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 208
SZABIST jstc Shaheed Benazirabad



Error message . The same message that the browser would display for the given error
URL . The file in which the error occurred
Line number . The line number in the given URL that caused the error
Here is the example to show how to extract this information
<html>
<head>
<script type="text/javascript">
<!-window.onerror = function (msg, url, line) {
alert("Message : " + msg );
alert("url : " + url );
alert("Line number : " + line );
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>
You can display extracted information in whatever way you think it is better.
You can use onerror method to show an error message in case there is any problem in loading
an image as follows:
<img src="myimage.gif"
onerror="alert('An error occurred loading the image.')" />
You can use onerror with many HTML tags to display appropriate messages in case of errors.
JavaScript - Form Validation
Form validation used to occur at the server, after the client had entered all necessary data and
then pressed the Submit button. If some of the data that had been entered by the client had been
in the wrong form or was simply missing, the server would have to send all the data back to the
client and request that the form be resubmitted with correct information. This was really a
lengthy process and over burdening server.
JavaScript, provides a way to validate form's data on the client's computer before sending it to
the web server. Form validation generally performs two functions.
 Basic Validation - First of all, the form must be checked to make sure data was entered
into each form field that required it. This would need just loop through each field in the
form and check for data.
 Data Format Validation - Secondly, the data that is entered must be checked for correct
form and value. This would need to put more logic to test correctness of data.
We will take an example to understand the process of validation. Here is the simple form to
proceed :
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 209
SZABIST jstc Shaheed Benazirabad
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
<!-// Form validation code will come here.
//-->
</script>
</head>
<body>
<form action="/cgi-bin/test.cgi" name="myForm"
onsubmit="return(validate());">
<table cellspacing="2" cellpadding="2" border="1">
<tr>
<td align="right">Name</td>
<td><input type="text" name="Name" /></td>
</tr>
<tr>
<td align="right">EMail</td>
<td><input type="text" name="EMail" /></td>
</tr>
<tr>
<td align="right">Zip Code</td>
<td><input type="text" name="Zip" /></td>
</tr>
<tr>
<td align="right">Country</td>
<td>
<select name="Country">
<option value="-1" selected>[choose yours]</option>
<option value="1">USA</option>
<option value="2">UK</option>
<option value="3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 210
SZABIST jstc Shaheed Benazirabad
Basic Form Validation:
First we will show how to do a basic form validation. In the above form we are calling validate()
function to validate data when onsubmit event is occurring. Following is the implementation of
this validate() function:
<script type="text/javascript">
<!-// Form validation code will come here.
function validate()
{
if( document.myForm.Name.value == "" )
{
alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.EMail.value == "" )
{
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ;
return false;
}
if( document.myForm.Zip.value == "" ||
isNaN( document.myForm.Zip.value ) ||
document.myForm.Zip.value.length != 5 )
{
alert( "Please provide a zip in the format #####." );
document.myForm.Zip.focus() ;
return false;
}
if( document.myForm.Country.value == "-1" )
{
alert( "Please provide your country!" );
return false;
}
return( true );
}
//-->
</script>
Data Format Validation:
Now we will see how we can validate our entered form data before submitting it to the web
server.
This example shows how to validate an entered email address which means email address must
contain at least an @ sign and a dot (.). Also, the @ must not be the first character of the email
address, and the last dot must at least be one character after the @ sign
:
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 211
SZABIST jstc Shaheed Benazirabad
<script type="text/javascript">
<!-function validateEmail()
{
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email ID")
document.myForm.EMail.focus() ;
return false;
}
return( true );
}
//-->
</script>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 212
SZABIST jstc Shaheed Benazirabad
PHP Introduction
The PHP Hypertext Preprocessor (PHP) is a programming language that allows web
developers to create dynamic content that interacts with databases.
PHP is basically used for developing web based software applications.
PHP started out as a small open source project that evolved as more and more people found out
how useful it was. Rasmus Lerdorf unleashed the first version of PHP way back in 1994.
 PHP is a recursive acronym for "PHP: Hypertext Preprocessor".
 PHP is a server side scripting language that is embedded in HTML. It is used to manage
dynamic content, databases, session tracking, even build entire e-commerce sites.
 It is integrated with a number of popular databases, including MySQL, PostgreSQL,
Oracle, Sybase, Informix, and Microsoft SQL Server.
 PHP is pleasingly zippy in its execution, especially when compiled as an Apache module
on the Unix side. The MySQL server, once started, executes even very complex queries
with huge result sets in record-setting time.
 PHP supports a large number of major protocols such as POP3, IMAP, and LDAP. PHP4
added support for Java and distributed object architectures (COM and CORBA), making
n-tier development a possibility for the first time.
 PHP is forgiving: PHP language tries to be as forgiving as possible.
 PHP Syntax is C-Like.
Common uses of PHP:






PHP performs system functions, i.e. from files on a system it can create, open, read,
write, and close them.
PHP can handle forms, i.e. gather data from files, save data to a file, thru email you can
send data, return data to the user.
You add, delete, modify elements within your database thru PHP.
Access cookies variables and set cookies.
Using PHP, you can restrict users to access some pages of your website.
It can encrypt data.
Characteristics of PHP
Five important characteristics make PHP's practical nature possible:
 Simplicity
 Efficiency
 Security
 Flexibility
 Familiarity
"Hello World" Script in PHP:
To get a feel for PHP, first start with simple PHP scripts. Since "Hello, World!" is an essential
example, first we will create a friendly little "Hello, World!" script.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 213
SZABIST jstc Shaheed Benazirabad
As mentioned earlier, PHP is embedded in HTML. That means that in amongst your normal
HTML (or XHTML if you're cutting-edge) you'll have PHP statements like this:
<html>
<head>
<title>Hello World</title>
<body>
<?php echo "Hello, World!";?>
</body>
</html>
It will produce following result:
Hello, World!
If you examine the HTML output of the above example, you'll notice that the PHP code is not
present in the file sent from the server to your Web browser. All of the PHP present in the Web
page is processed and stripped from the page; the only thing returned to the client from the Web
server is pure HTML output.
All PHP code must be included inside one of the three special markup tags ate are recognised by
the PHP Parser.
<?php PHP code goes here ?>
<?
PHP code goes here ?>
<script language="php"> PHP code goes here </script>
Most common tag is the <?php...?> and we will also use same tag in our tutorial.
PHP Environment Setup
In order to develop and run PHP Web pages three vital components need to be installed on your
computer system.
 Web Server - PHP will work with virtually all Web Server software, including
Microsoft's Internet Information Server (IIS) but then most often used is freely availble
Apache Server. Download Apache for free here: http://httpd.apache.org/download.cgi
 Database - PHP will work with virtually all database software, including Oracle and
Sybase but most commonly used is freely available MySQL database. Download MySQL
for free here: http://www.mysql.com/downloads/index.html
 PHP Parser - In order to process PHP script instructions a parser must be installed to
generate HTML output that can be sent to the Web Browser. This tutorial will guide you
how to install PHP parser on your computer.
PHP Parser Installation:
Before you proceed it is important to make sure that you have proper environment setup on your
machine to develop your web programs using PHP.
Type the following address into your browser's address box.
http://127.0.0.1/info.php
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 214
SZABIST jstc Shaheed Benazirabad
If this displays a page showing your PHP installation related information then it means you have
PHP and Webserver installed properly. Otherwise you have to follow given procedure to install
PHP on your computer.
This section will guide you to install and configure PHP over the following four platforms:
 PHP Installation on Linux or Unix with Apache
 PHP Installation on Mac OS X with Apache
 PHP Installation on Windows NT/2000/XP with IIS
 PHP Installation on Windows NT/2000/XP with Apache
Apache Configuration:
If you are using Apache as a Web Server then this section will guide you to edit Apache
Configuration Files.
Just Check it here : PHP Configuration in Apache Server
PHP.INI File Configuration:
The PHP configuration file, php.ini, is the final and most immediate way to affect PHP's
functionality.
Just Check it here: PHP.INI File Configuration
Windows IIS Configuration:
To configure IIS on your Windows machine you can refer your IIS Reference Manual shipped
along with IIS.
PHP Syntax Overview
This chapter will give you an idea of very basic syntax of PHP and very important to make your
PHP foundation strong.
Escaping to PHP:
The PHP parsing engine needs a way to differentiate PHP code from other elements in the page.
The mechanism for doing so is known as 'escaping to PHP.' There are four ways to do this:
Canonical PHP tags:
The most universally effective PHP tag style is:
<?php...?>
If you use this style, you can be positive that your tags will always be correctly interpreted.
Short-open (SGML-style) tags:
Short or short-open tags look like this:
<?...?>
Short tags are, as one might expect, the shortest option You must do one of two things to enable
PHP to recognize the tags:
 Choose the --enable-short-tags configuration option when you're building PHP.
 Set the short_open_tag setting in your php.ini file to on. This option must be disabled to
parse XML with PHP because the same syntax is used for XML tags.
ASP-style tags:
ASP-style tags mimic the tags used by Active Server Pages to delineate code blocks. ASP-style
tags look like this:
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 215
SZABIST jstc Shaheed Benazirabad
<%...%>
To use ASP-style tags, you will need to set the configuration option in your php.ini file.
HTML script tags:
HTML script tags look like this:
<script language="PHP">...</script>
Commenting PHP Code:
A comment is the portion of a program that exists only for the human reader and stripped out
before displaying the programs result. There are two commenting formats in PHP:
Single-line comments: They are generally used for short explanations or notes relevant to the
local code. Here are the examples of single line comments.
<?
# This is a comment, and
# This is the second line of the comment
// This is a comment too. Each style comments only
print "An example with single line comments";
?>
Multi-lines printing: Here are the examples to print multiple lines in a single print statement:
<?
# First Example
print <<<END
This uses the "here document" syntax to output
multiple lines with $variable interpolation. Note
that the here document terminator must appear on a
line with just a semicolon no extra whitespace!
END;
# Second Example
print "This spans
multiple lines. The newlines will be
output as well";
?>
Multi-lines comments: They are generally used to provide pseudocode algorithms and more
detailed explanations when necessary. The multiline style of commenting is the same as in C.
Here are the example of multi lines comments.
<?
/* This is a comment with multiline
Author : Mohammad Mohtashim
Purpose: Multiline Comments Demo
Subject: PHP
*/
print "An example with multi line comments";
?>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 216
SZABIST jstc Shaheed Benazirabad
PHP is whitespace insensitive:
Whitespace is the stuff you type that is typically invisible on the screen, including spaces, tabs,
and carriage returns (end-of-line characters).
PHP whitespace insensitive means that it almost never matters how many whitespace characters
you have in a row.one whitespace character is the same as many such characters
For example, each of the following PHP statements that assigns the sum of 2 + 2 to the variable
$four is equivalent:
$four
$four
$four
2+
2; //
= 2 + 2; // single spaces
<tab>=<tab2<tab>+<tab>2 ; // spaces and tabs
=
multiple lines
PHP is case sensitive:
Yeah it is true that PHP is a case sensitive language. Try out following example:
<html>
<body>
<?
$capital = 67;
print("Variable capital is $capital<br>");
print("Variable CaPiTaL is $CaPiTaL<br>");
?>
</body>
</html>
This will produce following result:
Variable capital is 67
Variable CaPiTaL is
Statements are expressions terminated by semicolons:
A statement in PHP is any expression that is followed by a semicolon (;).Any sequence of valid
PHP statements that is enclosed by the PHP tags is a valid PHP program. Here is a typical
statement in PHP, which in this case assigns a string of characters to a variable called $greeting:
$greeting = "Welcome to PHP!";
Expressions are combinations of tokens:
The smallest building blocks of PHP are the indivisible tokens, such as numbers (3.14159),
strings (.two.), variables ($two), constants (TRUE), and the special words that make up the
syntax of PHP itself like if, else, while, for and so forth
Braces make blocks:
Although statements cannot be combined like expressions, you can always put a sequence of
statements anywhere a statement can go by enclosing them in a set of curly braces.
Here both statements are equivalent:
if (3 == 2 + 1)
print("Good - I haven't totally lost my mind.<br>");
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 217
SZABIST jstc Shaheed Benazirabad
if (3 == 2 + 1)
{
print("Good - I haven't totally");
print("lost my mind.<br>");
}
Running PHP Script from Command Prompt:
Yes you can run your PHP script on your command prompt. Assuming you have following
content in test.php file
<?php
echo "Hello PHP!!!!!";
?>
Now run this script as command prompt as follows:
$ php test.php
It will produce following result:
Hello PHP!!!!!
Hope now you have basic knowledge of PHP Syntax.
PHP Variable Types
The main way to store information in the middle of a PHP program is by using a variable.
Here are the most important things to know about variables in PHP.
 All variables in PHP are denoted with a leading dollar sign ($).
 The value of a variable is the value of its most recent assignment.
 Variables are assigned with the = operator, with the variable on the left-hand side and the
expression to be evaluated on the right.
 Variables can, but do not need, to be declared before assignment.
 Variables in PHP do not have intrinsic types - a variable does not know in advance
whether it will be used to store a number or a string of characters.
 Variables used before they are assigned have default values.
 PHP does a good job of automatically converting types from one to another when
necessary.
 PHP variables are Perl-like.
PHP has a total of eight data types which we use to construct our variables:
 Integers: are whole numbers, without a decimal point, like 4195.
 Doubles: are floating-point numbers, like 3.14159 or 49.1.
 Booleans: have only two possible values either true or false.
 NULL: is a special type that only has one value: NULL.
 Strings: are sequences of characters, like 'PHP supports string operations.'
 Arrays: are named and indexed collections of other values.
 Objects: are instances of programmer-defined classes, which can package up both other
kinds of values and functions that are specific to the class.
 Resources: are special variables that hold references to resources external to PHP (such
as database connections).
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 218
SZABIST jstc Shaheed Benazirabad
The first five are simple types, and the next two (arrays and objects) are compound - the
compound types can package up other arbitrary values of arbitrary type, whereas the simple
types cannot.
We will explain only simile data type in this chapters. Array and Objects will be explained
separately.
Integers:
They are whole numbers, without a decimal point, like 4195. They are the simplest type .they
correspond to simple whole numbers, both positive and negative. Integers can be assigned to
variables, or they can be used in expressions, like so:
$int_var = 12345;
$another_int = -12345 + 12345;
Integer can be in decimal (base 10), octal (base 8), and hexadecimal (base 16) format. Decimal
format is the default, octal integers are specified with a leading 0, and hexadecimals have a
leading 0x.
For most common platforms, the largest integer is (2**31 . 1) (or 2,147,483,647), and the
smallest (most negative) integer is . (2**31 . 1) (or .2,147,483,647).
Doubles:
They like 3.14159 or 49.1. By default, doubles print with the minimum number of decimal
places needed. For example, the code:
$many = 2.2888800;
$many_2 = 2.2111200;
$few = $many + $many_2;
print(.$many + $many_2 = $few<br>.);
It produces the following browser output:
2.28888 + 2.21112 = 4.5
Boolean:
They have only two possible values either true or false. PHP provides a couple of constants
especially for use as Booleans: TRUE and FALSE, which can be used like so:
if (TRUE)
print("This will always print<br>");
else
print("This will never print<br>");
Interpreting other types as Booleans:
Here are the rules for determine the "truth" of any value not already of the Boolean type:
 If the value is a number, it is false if exactly equal to zero and true otherwise.
 If the value is a string, it is false if the string is empty (has zero characters) or is the string
"0", and is true otherwise.
 Values of type NULL are always false.
 If the value is an array, it is false if it contains no other values, and it is true otherwise.
For an object, containing a value means having a member variable that has been assigned
a value.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 219
SZABIST jstc Shaheed Benazirabad

Valid resources are true (although some functions that return resources when they are
successful will return FALSE when unsuccessful).
 Don't use double as Booleans.
Each of the following variables has the truth value embedded in its name when it is used in a
Boolean context.
$true_num = 3 + 0.14159;
$true_str = "Tried and true"
$true_array[49] = "An array element";
$false_array = array();
$false_null = NULL;
$false_num = 999 - 999;
$false_str = "";
NULL:
NULL is a special type that only has one value: NULL. To give a variable the NULL value,
simply assign it like this:
$my_var = NULL;
The special constant NULL is capitalized by convention, but actually it is case insensitive; you
could just as well have typed:
$my_var = null;
A variable that has been assigned NULL has the following properties:
 It evaluates to FALSE in a Boolean context.
 It returns FALSE when tested with IsSet() function.
Strings:
They are sequences of characters, like "PHP supports string operations". Following are valid
examples of string
$string_1 = "This is a string in double quotes";
$string_2 = "This is a somewhat longer, singly quoted string";
$string_39 = "This string has thirty-nine characters";
$string_0 = ""; // a string with zero characters
Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables
with their values as well as specially interpreting certain character sequences.
<?
$variable = "name";
$literally = 'My $variable will not print!\\n';
print($literally);
$literally = "My $variable will print!\\n";
print($literally);
?>
This will produce following result:
My $variable will not print!\n
My name will print
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 220
SZABIST jstc Shaheed Benazirabad
There are no artificial limits on string length - within the bounds of available memory, you ought
to be able to make arbitrarily long strings.
Strings that are delimited by double quotes (as in "this") are preprocessed in both the following
two ways by PHP:
 Certain character sequences beginning with backslash (\) are replaced with special
characters
 Variable names (starting with $) are replaced with string representations of their values.
The escape-sequence replacements are:
 \n is replaced by the newline character
 \r is replaced by the carriage-return character
 \t is replaced by the tab character
 \$ is replaced by the dollar sign itself ($)
 \" is replaced by a single double-quote (")
 \\ is replaced by a single backslash (\)
Here Document:
You can assign multiple lines to a single string variable using here document:
<?php
$channel =<<<_XML_
<channel>
<title>What's For Dinner<title>
<link>http://menu.example.com/<link>
<description>Choose what to eat tonight.</description>
</channel>
_XML_;
echo <<<END
This uses the "here document" syntax to output
multiple lines with variable interpolation. Note
that the here document terminator must appear on a
line with just a semicolon. no extra whitespace!
<br />
END;
print $channel;
?>
This will produce following result:
This uses the "here document" syntax to output
multiple lines with variable interpolation. Note
that the here document terminator must appear on a
line with just a semicolon. no extra whitespace!
<channel>
<title>What's For Dinner<title>
<link>http://menu.example.com/<link>
<description>Choose what to eat tonight.</description>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 221
SZABIST jstc Shaheed Benazirabad
Variable Scope:
Scope can be defined as the range of availability a variable has to the program in which it is
declared. PHP variables can be one of four scope types:
 Local variables
 Function parameters
 Global variables
 Static variables
Variable Naming:
Rules for naming a variable is:
 Variable names must begin with a letter or underscore character.
 A variable name can consist of numbers, letters, underscores but you cannot use
characters like + , - , % , ( , ) . & , etc
There is no size limit for variables.
PHP Constants
A constant is a name or an identifier for a simple value. A constant value cannot change during
the execution of the script. By default a constant is case-sensitiv. By convention, constant
identifiers are always uppercase. A constant name starts with a letter or underscore, followed by
any number of letters, numbers, or underscores. If you have defined a constant, it can never be
changed or undefined.
To define a constant you have to use define() function and to retrieve the value of a constant, you
have to simply specifying its name. Unlike with variables, you do not need to have a constant
with a $. You can also use the function constant() to read a constant's value if you wish to obtain
the constant's name dynamically.
constant() function:
As indicated by the name, this function will return the value of the constant.
This is useful when you want to retrieve value of a constant, but you do not know its name, i.e. It
is stored in a variable or returned by a function.
constant() example:
<?php
define("MINSIZE", 50);
echo MINSIZE;
echo constant("MINSIZE"); // same thing as the previous line
?>
Only scalar data (boolean, integer, float and string) can be contained in constants.
Differences between constants and variables are:
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 222
SZABIST jstc Shaheed Benazirabad




There is no need to write a dollar sign ($) before a constant, where as in Variable one has
to write a dollar sign.
Constants cannot be defined by simple assignment, they may only be defined using the
define() function.
Constants may be defined and accessed anywhere without regard to variable scoping
rules.
Once the Constants have been set, may not be redefined or undefined.
Valid and invalid constant names:
// Valid constant names
define("ONE",
"first thing");
define("TWO2",
"second thing");
define("THREE_3", "third thing")
// Invalid constant names
define("2TWO",
"second thing");
define("__THREE__", "third value");
PHP Magic constants:
PHP provides a large number of predefined constants to any script which it runs.
There are five magical constants that change depending on where they are used. For example, the
value of __LINE__ depends on the line that it's used on in your script. These special constants
are case-insensitive and are as follows:
A few "magical" PHP constants ate given below:
Name
Description
__LINE__
The current line number of the file.
__FILE__
The full path and filename of the file. If used inside an include,the name of
the included file is returned. Since PHP 4.0.2, __FILE__ always contains an
absolute path whereas in older versions it contained relative path under
some circumstances.
The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns
__FUNCTION__ the function name as it was declared (case-sensitive). In PHP 4 its value is
always lowercased.
__CLASS__
The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the
class name as it was declared (case-sensitive). In PHP 4 its value is always
lowercased.
__METHOD__
The class method name. (Added in PHP 5.0.0) The method name is returned
as it was declared (case-sensitive).
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 223
SZABIST jstc Shaheed Benazirabad
PHP Operator Types
What is Operator? Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and
5 are called operands and + is called operator. PHP language supports following type of
operators.
 Arithmetic Operators
 Comparision Operators
 Logical (or Relational) Operators
 Assignment Operators
 Conditional (or ternary) Operators
Lets have a look on all operators one by one.
Arithmatic Operators:
There are following arithmatic operators supported by PHP language:
Assume variable A holds 10 and variable B holds 20 then:
Show Examples
Operator
Description
Example
+
Adds two operands
A + B will give 30
-
Subtracts second operand from the first
A - B will give -10
*
Multiply both operands
A * B will give 200
/
Divide numerator by denumerator
B / A will give 2
%
Modulus Operator and remainder of after an
integer division
B % A will give 0
++
Increment operator, increases integer value
by one
A++ will give 11
--
Decrement operator, decreases integer value
A-- will give 9
by one
Comparison Operators:
There are following comparison operators supported by PHP language
Assume variable A holds 10 and variable B holds 20 then:
Show Examples
Operator
Description
Example
==
Checks if the value of two operands are equal
(A == B) is not true.
or not, if yes then condition becomes true.
!=
Checks if the value of two operands are equal
or not, if values are not equal then condition (A != B) is true.
becomes true.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 224
SZABIST jstc Shaheed Benazirabad
>
Checks if the value of left operand is greater
than the value of right operand, if yes then
condition becomes true.
(A > B) is not true.
<
Checks if the value of left operand is less
than the value of right operand, if yes then
condition becomes true.
(A < B) is true.
>=
Checks if the value of left operand is greater
than or equal to the value of right operand, if (A >= B) is not true.
yes then condition becomes true.
<=
Checks if the value of left operand is less
than or equal to the value of right operand, if (A <= B) is true.
yes then condition becomes true.
Logical Operators:
There are following logical operators supported by PHP language
Assume variable A holds 10 and variable B holds 20 then:
Show Examples
Operator
Description
Example
And
Called Logical AND operator. If both the
operands are true then then condition
becomes true.
(A and B) is true.
Or
Called Logical OR Operator. If any of the two
operands are non zero then then condition
becomes true.
(A or B) is true.
&&
Called Logical AND operator. If both the
operands are non zero then then condition
becomes true.
(A && B) is true.
||
Called Logical OR Operator. If any of the two
operands are non zero then then condition
becomes true.
(A || B) is true.
!
Called Logical NOT Operator. Use to reverses
the logical state of its operand. If a condition
is true then Logical NOT operator will make
false.
!(A && B) is false.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 225
SZABIST jstc Shaheed Benazirabad
Assignment Operators:
There are following assignment operators supported by PHP language:
Show Examples
Operator
Description
Example
=
Simple assignment operator, Assigns
values from right side operands to left
side operand
C = A + B will assigne value of A + B into C
+=
Add AND assignment operator, It adds
right operand to the left operand and
assign the result to left operand
C += A is equivalent to C = C + A
-=
Subtract AND assignment operator, It
subtracts right operand from the left
operand and assign the result to left
operand
C -= A is equivalent to C = C - A
*=
Multiply AND assignment operator, It
multiplies right operand with the left
operand and assign the result to left
operand
C *= A is equivalent to C = C * A
/=
Divide AND assignment operator, It
divides left operand with the right
operand and assign the result to left
operand
C /= A is equivalent to C = C / A
%=
Modulus AND assignment operator, It
takes modulus using two operands and
assign the result to left operand
C %= A is equivalent to C = C % A
Conditional Operator
There is one more operator called conditional operator. This first evaluates an expression for a
true or false value and then execute one of the two given statements depending upon the result of
the evaluation. The conditional operator has this syntax:
Show Examples
Operator
?:
Description
Conditional Expression
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Example
If Condition is true ? Then value X : Otherwise
value Y
Page 226
SZABIST jstc Shaheed Benazirabad
Operators Categories:
All the operators we have discussed above can be categorised into following categories:
 Unary prefix operators, which precede a single operand.
 Binary operators, which take two operands and perform a variety of arithmetic and
logical operations.
 The conditional operator (a ternary operator), which takes three operands and evaluates
either the second or third expression, depending on the evaluation of the first expression.
 Assignment operators, which assign a value to a variable.
Precedence of PHP Operators:
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator:
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher
precedence than + so it first get multiplied with 3*2 and then adds into 7.
Here operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Category
Operator
Associativity
Unary
! ++ --
Right to left
Multiplicative
*/%
Left to right
Additive
+-
Left to right
Relational
< <= > >=
Left to right
Equality
== !=
Left to right
Logical AND
&&
Left to right
Logical OR
||
Left to right
Conditional
?:
Right to left
Assignment
= += -= *= /= %=
Right to left
PHP Decision Making
The if, elseif ...else and switch statements are used to take decision based on the different
condition.
You can use conditional statements in your code to make your decisions. PHP supports
following threedecision making statements:


if...else statement - use this statement if you want to execute a set of code when a condition is
true and another if the condition is not true
elseif statement - is used with the if...else statement to execute a set of code if one of several
condition are true
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 227
SZABIST jstc Shaheed Benazirabad

switch statement - is used if you want to select one of many blocks of code to be executed, use
the Switch statement. The switch statement is used to avoid long blocks of if..elseif..else code.
The If...Else Statement
If you want to execute some code if a condition is true and another code if a condition is false,
use the if....else statement.
Syntax
if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
Example
The following example will output "Have a nice weekend!" if the current day is Friday,
otherwise it will output "Have a nice day!":
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
else
echo "Have a nice day!";
?>
</body>
</html>
If more than one line should be executed if a condition is true/false, the lines should be enclosed
within curly braces:
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
{
echo "Hello!<br />";
echo "Have a nice weekend!";
echo "See you on Monday!";
}
?>
</body>
</html>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 228
SZABIST jstc Shaheed Benazirabad
The ElseIf Statement
If you want to execute some code if one of several conditions are true use the elseif statement
Syntax
if (condition)
code to be executed if condition is true;
elseif (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
Example
The following example will output "Have a nice weekend!" if the current day is Friday, and
"Have a nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice day!":
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
elseif ($d=="Sun")
echo "Have a nice Sunday!";
else
echo "Have a nice day!";
?>
</body>
</html>
The Switch Statement
If you want to select one of many blocks of code to be executed, use the Switch statement.
The switch statement is used to avoid long blocks of if..elseif..else code.
Syntax
switch (expression)
{
case label1:
code to be executed if expression = label1;
break;
case label2:
code to be executed if expression = label2;
break;
default:
code to be executed
if expression is different
from both label1 and label2;
}
Example
The switch statement works in an unusual way. First it evaluates given expression then seeks a
lable to match the resulting value. If a matching value is found then the code associated with the
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 229
SZABIST jstc Shaheed Benazirabad
matching label will be executed or if none of the lables match then statement will will execute
any specified default code.
<html>
<body>
<?php
$d=date("D");
switch ($d)
{
case "Mon":
echo "Today is Monday";
break;
case "Tue":
echo "Today is Tuesday";
break;
case "Wed":
echo "Today is Wednesday";
break;
case "Thu":
echo "Today is Thursday";
break;
case "Fri":
echo "Today is Friday";
break;
case "Sat":
echo "Today is Saturday";
break;
case "Sun":
echo "Today is Sunday";
break;
default:
echo "Wonder which day is this ?";
}
?>
</body>
</html>
PHP Loop Types
Loops in PHP are used to execute the same block of code a specified number of times. PHP
supports following four loop types.




for - loops through a block of code a specified number of times.
while - loops through a block of code if and as long as a specified condition is true.
do...while - loops through a block of code once, and then repeats the loop as long as a special
condition is true.
foreach - loops through a block of code for each element in an array.
We will discuss about continue and break keywords used to control the loops execution.
The for loop statement
The for statement is used when you know how many times you want to execute a statement or a
block of statements.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 230
SZABIST jstc Shaheed Benazirabad
Syntax
for (initialization; condition; increment)
{
code to be executed;
}
The initializer is used to set the start value for the counter of the number of loop iterations. A
variable may be declared here for this purpose and it is traditional to name it $i.
Example
The following example makes five iterations and changes the assigned value of two variables on
each pass of the loop:
<html>
<body>
<?php
$a = 0;
$b = 0;
for( $i=0; $i<5; $i++ )
{
$a += 10;
$b += 5;
}
echo ("At the end of the loop a=$a and b=$b" );
?>
</body>
</html>
This will produce following result:
At the end of the loop a=50 and b=25
The while loop statement
The while statement will execute a block of code if and as long as a test expression is true.
If the test expression is true then the code block will be executed. After the code has executed the
test expression will again be evaluated and the loop will continue until the test expression is
found to be false.
Syntax
while (condition)
{
code to be executed;
}
Example
This example decrements a variable value on each iteration of the loop and the counter
increments until it reaches 10 when the evaluation is false and the loop ends.
<html>
<body>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 231
SZABIST jstc Shaheed Benazirabad
<?php
$i = 0;
$num = 50;
while( $i < 10)
{
$num--;
$i++;
}
echo ("Loop stopped at i = $i and num = $num" );
?>
</body>
</html>
This will produce following result:
Loop stopped at i = 10 and num = 40
The do...while loop statement
The do...while statement will execute a block of code at least once - it then will repeat the loop as
long as a condition is true.
Advertisements
Syntax
do
{
code to be executed;
}while (condition);
Example
The following example will increment the value of i at least once, and it will continue
incrementing the variable i as long as it has a value of less than 10:
<html>
<body>
<?php
$i = 0;
$num = 0;
do
{
$i++;
}while( $i < 10 );
echo ("Loop stopped at i = $i" );
?>
</body>
</html>
This will produce following result:
Loop stopped at i = 10
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 232
SZABIST jstc Shaheed Benazirabad
The foreach loop statement
The foreach statement is used to loop through arrays. For each pass the value of the current array
element is assigned to $value and the array pointer is moved by one and in the next pass next
element will be processed.
Advertisements
Syntax
foreach (array as value)
{
code to be executed;
}
Example
Try out following example to list out the values of an array.
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
echo "Value is $value <br />";
}
?>
</body>
</html>
This will produce following result:
Value
Value
Value
Value
Value
is
is
is
is
is
1
2
3
4
5
The break statement
The PHP break keyword is used to terminate the execution of a loop prematurely.
The break statement is situated inside the statement block. If gives you full control and
whenever you want to exit from the loop you can come out. After coming out of a loop
immediate statement to the loop will be executed.
Example
In the following example condition test becomes true when the counter value reaches 3 and loop
terminates.
<html>
<body>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 233
SZABIST jstc Shaheed Benazirabad
<?php
$i = 0;
while( $i < 10)
{
$i++;
if( $i == 3 )break;
}
echo ("Loop stopped at i = $i" );
?>
</body>
</html>
This will produce following result:
Loop stopped at i = 3
The continue statement
The PHP continue keyword is used to halt the current iteration of a loop but it does not terminate
the loop.
Just like the break statement the continue statement is situated inside the statement block
containing the code that the loop executes, preceded by a conditional test. For the pass
encountering continue statement, rest of the loop code is skipped and next pass starts.
Example
In the following example loop prints the value of array but for which condition becomes true it
just skip the code and next value is printed.
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
if( $value == 3 )continue;
echo "Value is $value <br />";
}
?>
</body>
</html>
This will produce following result
Value
Value
Value
Value
is
is
is
is
1
2
4
5
PHP Arrays
An array is a data structure that stores one or more similar type of values in a single value. For
example if you want to store 100 numbers then instead of defining 100 variables its easy to
define an array of 100 length.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 234
SZABIST jstc Shaheed Benazirabad
There are three different kind of arrays and each array value is accessed using an ID c which is
called array index.



Numeric array - An array with a numeric index. Values are stored and accessed in linear fashion
Associative array - An array with strings as index. This stores element values in association with
key values rather than in a strict linear index order.
Multidimensional array - An array containing one or more arrays and values are accessed using
multiple indices
NOTE: Built-in array functions is given in function reference PHP Array Functions
Numeric Array
These arrays can store numbers, strings and any object but their index will be prepresented by
numbers. By default array index starts from zero.
Example
Following is the example showing how to create and access numeric arrays.
Here we have used array() function to create array. This function is explained in function
reference.
<html>
<body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
foreach( $numbers as $value )
{
echo "Value is $value <br />";
}
/* Second method to create array. */
$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";
foreach( $numbers as $value )
{
echo "Value is $value <br />";
}
?>
</body>
</html>
This will produce following result:
Value
Value
Value
Value
Value
Value
Value
is
is
is
is
is
is
is
1
2
3
4
5
one
two
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 235
SZABIST jstc Shaheed Benazirabad
Value is three
Value is four
Value is five
Associative Arrays
The associative arrays are very similar to numeric arrays in term of functionality but they are
different in terms of their index. Associative array will have their index as string so that you can
establish a strong association between key and values.
To store the salaries of employees in an array, a numerically indexed array would not be the best
choice. Instead, we could use the employees names as the keys in our associative array, and the
value would be their respective salary.
NOTE: Don't keep associative array inside double quote while printing otheriwse it would not
return any value.
Example
<html>
<body>
<?php
/* First method to associate create array. */
$salaries = array(
"mohammad" => 2000,
"qadir" => 1000,
"zara" => 500
);
echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
/* Second method to create array. */
$salaries['mohammad'] = "high";
$salaries['qadir'] = "medium";
$salaries['zara'] = "low";
echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
?>
</body>
</html>
This will produce following result:
Salary
Salary
Salary
Salary
Salary
Salary
of
of
of
of
of
of
mohammad is 2000
qadir is 1000
zara is 500
mohammad is high
qadir is medium
zara is low
Multidimensional Arrays
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 236
SZABIST jstc Shaheed Benazirabad
A multi-dimensional array each element in the main array can also be an array. And each
element in the sub-array can be an array, and so on. Values in the multi-dimensional array are
accessed using multiple index.
Example
In this example we create a two dimensional array to store marks of three students in three
subjects:
This example is an associative array, you can create numeric array in the same fashion.
<html>
<body>
<?php
$marks = array(
"mohammad" => array
(
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
"qadir" => array
(
"physics" => 30,
"maths" => 32,
"chemistry" => 29
),
"zara" => array
(
"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);
/* Accessing multi-dimensional array values */
echo "Marks for mohammad in physics : " ;
echo $marks['mohammad']['physics'] . "<br />";
echo "Marks for qadir in maths : ";
echo $marks['qadir']['maths'] . "<br />";
echo "Marks for zara in chemistry : " ;
echo $marks['zara']['chemistry'] . "<br />";
?>
</body>
</html>
This will produce following result:
Marks for mohammad in physics : 35
Marks for qadir in maths : 32
Marks for zara in chemistry : 39
PHP Strings
They are sequences of characters, like "PHP supports string operations".
NOTE: Built-in string functions is given in function reference PHP String Functions
Following are valid examples of string
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 237
SZABIST jstc Shaheed Benazirabad
$string_1 = "This is a string in double quotes";
$string_2 = "This is a somewhat longer, singly quoted string";
$string_39 = "This string has thirty-nine characters";
$string_0 = ""; // a string with zero characters
Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables
with their values as well as specially interpreting certain character sequences.
<?
$variable = "name";
$literally = 'My $variable will not print!\\n';
print($literally);
$literally = "My $variable will print!\\n";
print($literally);
?>
This will produce following result:
My $variable will not print!\n
My name will print
There are no artificial limits on string length - within the bounds of available memory, you ought
to be able to make arbitrarily long strings.
Strings that are delimited by double quotes (as in "this") are preprocessed in both the following
two ways by PHP:
 Certain character sequences beginning with backslash (\) are replaced with special
characters
 Variable names (starting with $) are replaced with string representations of their values.
The escape-sequence replacements are:
 \n is replaced by the newline character
 \r is replaced by the carriage-return character
 \t is replaced by the tab character
 \$ is replaced by the dollar sign itself ($)
 \" is replaced by a single double-quote (")
 \\ is replaced by a single backslash (\)
String Concatenation Operator
To concatenate two string variables together, use the dot (.) operator:
<?php
$string1="Hello World";
$string2="1234";
echo $string1 . " " . $string2;
?>
This will produce following result:
Hello World 1234
If we look at the code above you see that we used the concatenation operator two times. This is
because we had to insert a third string.
Between the two string variables we added a string with a single character, an empty space, to
separate the two variables.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 238
SZABIST jstc Shaheed Benazirabad
Using the strlen() function
The strlen() function is used to find the length of a string.
Let's find the length of our string "Hello world!":
<?php
echo strlen("Hello world!");
?>
This will produce following result:
12
The length of a string is often used in loops or other functions, when it is important to know
when the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the
string)
Using the strpos() function
The strpos() function is used to search for a string or character within a string.
If a match is found in the string, this function will return the position of the first match. If no
match is found, it will return FALSE.
Let's see if we can find the string "world" in our string:
<?php
echo strpos("Hello world!","world");
?>
This will produce following result:
6
As you see the position of the string "world" in our string is position 6. The reason that it is 6,
and not 7, is that the first position in the string is 0, and not 1.
PHP Web Concepts
This session demonstrates how PHP can provide dynamic content according to browser type,
randomly generated numbers or User Input. It also demonstrated how the client borwser can be
redirected.
Identifying Browser & Platform
PHP creates some useful environment variables that can be seen in the phpinfo.php page that
was used to setup the PHP environment.
One of the environemnt variables set by PHP is HTTP_USER_AGENT which identifies the
user's browser and operating system.
PHP provides a function getenv() to access the value of all the environment variables. The
information contained in the HTTP_USER_AGENT environment variable can be used to create
dynamic content appropriate to the borwser.
Following example demonstrates how you can identify a client borwser and operating system.
NOTE: The function preg_match()is discussed in PHP Regular expression session.
<html>
<body>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 239
SZABIST jstc Shaheed Benazirabad
<?php
$viewer = getenv( "HTTP_USER_AGENT" );
$browser = "An unidentified browser";
if( preg_match( "/MSIE/i", "$viewer" ) )
{
$browser = "Internet Explorer";
}
else if( preg_match( "/Netscape/i", "$viewer" ) )
{
$browser = "Netscape";
}
else if( preg_match( "/Mozilla/i", "$viewer" ) )
{
$browser = "Mozilla";
}
$platform = "An unidentified OS!";
if( preg_match( "/Windows/i", "$viewer" ) )
{
$platform = "Windows!";
}
else if ( preg_match( "/Linux/i", "$viewer" ) )
{
$platform = "Linux!";
}
echo("You are using $browser on $platform");
?>
</body>
</html>
This is producing following result on my machine. This result may be different for your
computer depnding on what you are using.
You are using Mozilla! on Windows!
Display Images Randomly
The PHP rand() function is used to generate a random number.i This function can generate
numbers with-in a given range. The random number generator should be seeded to prevent a
regular pattern of numbers being generated. This is achieved using the srand() function that
specifiies the seed number as its argument.
Following example demonstrates how you can display different image each time out of four
images:
<html>
<body>
<?php
srand( microtime() * 1000000 );
$num = rand( 1, 4 );
switch( $num )
{
case 1: $image_file = "/home/images/alfa.jpg";
break;
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 240
SZABIST jstc Shaheed Benazirabad
case 2: $image_file = "/home/images/ferrari.jpg";
break;
case 3: $image_file = "/home/images/jaguar.jpg";
break;
case 4: $image_file = "/home/images/porsche.jpg";
break;
}
echo "Random Image : <img src=$image_file />";
?>
</body>
</html>
Using HTML Forms
The most important thing to notice when dealing with HTML forms and PHP is that any form
element in an HTML page will automatically be available to your PHP scripts.
Try out following example by putting the source code in test.php script.
<?php
if( $_POST["name"] || $_POST["age"] )
{
echo "Welcome ". $_POST['name']. "<br />";
echo "You are ". $_POST['age']. " years old.";
exit();
}
?>
<html>
<body>
<form action="<?php $_PHP_SELF ?>" method="POST">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>


The PHP default variable $_PHP_SELF is used for the PHP script name and when you
click "submit" button then same PHP script will be called and will produce following
result:
The method = "POST" is used to post user data to the server script. There are two
methods of posting data to the server script which are discussed in PHP GET & POST
chapter.
Browser Redirection
The PHP header() function supplies raw HTTP headers to the browser and can be used to
redirect it to another location. The redirection script should be at the very top of the page to
prevent any other part of the page from loading.
The target is specified by the Location: header as the argument to the header() function. After
calling this function the exit() function can be used to halt parsing of rest of the code.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 241
SZABIST jstc Shaheed Benazirabad
Following example demonstrates how you can redirect a borwser request to another web page.
Try out this example by puttingthe source code in test.php script.
<?php
if( $_POST["location"] )
{
$location = $_POST["location"];
header( "Location:$location" );
exit();
}
?>
<html>
<body>
<p>Choose a site to visit :</p>
<form action="<?php $_PHP_SELF ?>" method="POST">
<select name="location">
<option value="http://w3c.org">
World Wise Web Consortium
</option>
<option value="http://www.google.com">
Google Search Page
</option>
</select>
<input type="submit" />
</form>
</body>
</html>
Displaying "File Download" Dialog Box
Sometime it is desired that you want to give option where a use will click a link and it will pop
up a "File Download" box to the user in stead of displaying actual content. This is very easy and
will be achived through HTTP header.
The HTTP header will be different from the actual header where we send Content-Type as
text/html\n\n. In this case content type will be application/octet-stream and actual file name
will be concatenated alongwith it.
For example,if you want make a FileName file downloadable from a given link then its syntax
will be as follows.
#!/usr/bin/perl
# HTTP Header
print "Content-Type:application/octet-stream; name=\"FileName\"\r\n";
print "Content-Disposition: attachment; filename=\"FileName\"\r\n\n";
# Actual File Content
open( FILE, "<FileName" );
while(read(FILE, $buffer, 100) )
{
print("$buffer");
}
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 242
SZABIST jstc Shaheed Benazirabad
PHP GET and POST Methods
There are two ways the browser client can send information to the web server.
 The GET Method
 The POST Method
Before the browser sends the information, it encodes it using a scheme called URL encoding. In
this scheme, name/value pairs are joined with equal signs and different pairs are separated by the
ampersand.
name1=value1&name2=value2&name3=value3
Spaces are removed and replaced with the + character and any other nonalphanumeric characters
are replaced with a hexadecimal values. After the information is encoded it is sent to the server.
The GET Method
The GET method sends the encoded user information appended to the page request. The page
and the encoded information are separated by the ? character.
http://www.test.com/index.htm?name1=value1&name2=value2

The GET method produces a long string that appears in your server logs, in the browser's
Location: box.
 The GET method is restricted to send upto 1024 characters only.
 Never use GET method if you have password or other sensitive information to be sent to
the server.
 GET can't be used to send binary data, like images or word documents, to the server.
 The data sent by GET method can be accessed using QUERY_STRING environment
variable.
 The PHP provides $_GET associative array to access all the sent information using GET
method.
Try out following example by putting the source code in test.php script.
<?php
if( $_GET["name"] || $_GET["age"] )
{
echo "Welcome ". $_GET['name']. "<br />";
echo "You are ". $_GET['age']. " years old.";
exit();
}
?>
<html>
<body>
<form action="<?php $_PHP_SELF ?>" method="GET">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
The POST Method
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 243
SZABIST jstc Shaheed Benazirabad
The POST method transfers information via HTTP headers. The information is encoded as
described in case of GET method and put into a header called QUERY_STRING.
 The POST method does not have any restriction on data size to be sent.
 The POST method can be used to send ASCII as well as binary data.
 The data sent by POST method goes through HTTP header so security depends on HTTP
protocol. By using Secure HTTP you can make sure that your information is secure.
 The PHP provides $_POST associative array to access all the sent information using
GET method.
Try out following example by putting the source code in test.php script.
<?php
if( $_POST["name"] || $_POST["age"] )
{
echo "Welcome ". $_POST['name']. "<br />";
echo "You are ". $_POST['age']. " years old.";
exit();
}
?>
<html>
<body>
<form action="<?php $_PHP_SELF ?>" method="POST">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
The $_REQUEST variable
The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE.
We will discuss $_COOKIE variable when we will explain about cookies.
The PHP $_REQUEST variable can be used to get the result from form data sent with both
the GET and POST methods.
Try out following example by putting the source code in test.php script.
<?php
if( $_REQUEST["name"] || $_REQUEST["age"] )
{
echo "Welcome ". $_REQUEST['name']. "<br />";
echo "You are ". $_REQUEST['age']. " years old.";
exit();
}
?>
<html>
<body>
<form action="<?php $_PHP_SELF ?>" method="POST">
Name: <input type="text" name="name" />
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 244
SZABIST jstc Shaheed Benazirabad
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
Here $_PHP_SELF variable contains the name of self script in which it is being called.
PHP File Inclusion
You can include the content of a PHP file into another PHP file before the server executes it.
There are two PHP functions which can be used to included one PHP file into another PHP file.


The include() Function
The require() Function
This is a strong point of PHP which helps in creating functions, headers, footers, or elements that
can be reused on multiple pages. This will help developers to make it easy to change the layout
of complete website with minimal effort. If there is any change required then instead of changing
thousand of files just change included file.
The include() Function
The include() function takes all the text in a specified file and copies it into the file that uses the
include function. If there is any problem in loading a file then the include() function generates a
warning but the script will continue execution.
Assume you want to create a common menu for your website. Then create a file menu.php with
the following content.
<a
<a
<a
<a
href="http://www.tutorialspoint.com/index.htm">Home</a> href="http://www.tutorialspoint.com/ebxml">ebXML</a> href="http://www.tutorialspoint.com/ajax">AJAX</a> href="http://www.tutorialspoint.com/perl">PERL</a> <br />
Now create as many pages as you like and include this file to create header. For example now
your test.php file can have following content.
<html>
<body>
<?php include("menu.php"); ?>
<p>This is an example to show how to include PHP file!</p>
</body>
</html>
This will produce following result
Home - ebXML - AJAX - PERL
This is an example to show how to include PHP file. You can include mean.php file in as many
as files you like!
The require() Function
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 245
SZABIST jstc Shaheed Benazirabad
The require() function takes all the text in a specified file and copies it into the file that uses the
include function. If there is any problem in loading a file then the require() function generates a
fatal error and halt the execution of the script.
So there is no difference in require() and include() except they handle error conditions. It is
recommended to use the require() function instead of include(), because scripts should not
continue executing if files are missing or misnamed.
You can try using above example with require() function and it will generate same result. But if
you will try following two examples where file does not exist then you will get different results.
<html>
<body>
<?php include("xxmenu.php"); ?>
<p>This is an example to show how to include wrong PHP file!</p>
</body>
</html>
This will produce following result
This is an example to show how to include wrong PHP file!
Now lets try same example with require() function.
<html>
<body>
<?php require("xxmenu.php"); ?>
<p>This is an example to show how to include wrong PHP file!</p>
</body>
</html>
This time file execution halts and nothing is displayed.
NOTE: You may get plain warning messages or fatal error messages or nothing at all. This
depends on your PHP Server configuration.
PHP Files & I/O
This chapter will explain following functions related to files:




Opening a file
Reading a file
Writing a file
Closing a file
Opening and Closing Files
The PHP fopen() function is used to open a file. It requires two arguments stating first the file
name and then mode in which to operate.
Files modes can be specified as one of the six options in this table.
Mode
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Purpose
Page 246
SZABIST jstc Shaheed Benazirabad
r
Opens the file for reading only.
Places the file pointer at the beginning of the file.
r+
Opens the file for reading and writing.
Places the file pointer at the beginning of the file.
w
Opens the file for writing only.
Places the file pointer at the beginning of the file.
and truncates the file to zero length. If files does not
exist then it attemts to create a file.
w+
Opens the file for reading and writing only.
Places the file pointer at the beginning of the file.
and truncates the file to zero length. If files does not
exist then it attemts to create a file.
a
Opens the file for writing only.
Places the file pointer at the end of the file.
If files does not exist then it attemts to create a file.
a+
Opens the file for reading and writing only.
Places the file pointer at the end of the file.
If files does not exist then it attemts to create a file.
If an attempt to open a file fails then fopen returns a value of false otherwise it returns a file
pointer which is used for further reading or writing to that file.
After making a changes to the opened file it is important to close it with the fclose() function.
The fclose() function requires a file pointer as its argument and then returns true when the
closure succeeds or false if it fails.
Reading a file
Once a file is opened using fopen() function it can be read with a function called fread(). This
function requires two arguments. These must be the file pointer and the length of the file
expressed in bytes.
The files's length can be found using the filesize() function which takes the file name as its
argument and returns the size of the file expressed in bytes.
So here are the steps required to read a file with PHP.
 Open a file using fopen() function.
 Get the file's length using filesize() function.
 Read the file's content using fread() function.
 Close the file with fclose() function.
The following example assigns the content of a text file to a variable then displays those contents
on the web page.
<html>
<head>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 247
SZABIST jstc Shaheed Benazirabad
<title>Reading a file using PHP</title>
</head>
<body>
<?php
$filename = "/home/user/guest/tmp.txt";
$file = fopen( $filename, "r" );
if( $file == false )
{
echo ( "Error in opening file" );
exit();
}
$filesize = filesize( $filename );
$filetext = fread( $file, $filesize );
fclose( $file );
echo ( "File size : $filesize bytes" );
echo ( "<pre>$filetext</pre>" );
?>
</body>
</html>
Writing a file
A new file can be written or text can be appended to an existing file using the PHP fwrite()
function. This function requires two arguments specifying a file pointer and the string of data
that is to be written. Optionally a third integer argument can be included to specify the length of
the data to write. If the third argument is included, writing would will stop after the specified
length has been reached.
The following example creates a new text file then writes a short text heading insite it. After
closing this file its existence is confirmed using file_exist() function which takes file name as an
argument
<?php
$filename = "/home/user/guest/newfile.txt";
$file = fopen( $filename, "w" );
if( $file == false )
{
echo ( "Error in opening new file" );
exit();
}
fwrite( $file, "This is a simple test\n" );
fclose( $file );
?>
<html>
<head>
<title>Writing a file using PHP</title>
</head>
<body>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 248
SZABIST jstc Shaheed Benazirabad
<?php
if( file_exist( $filename ) )
{
$filesize = filesize( $filename );
$msg = "File created with name $filename ";
$msg .= "containing $filesize bytes";
echo ($msg );
}
else
{
echo ("File $filename does not exit" );
}
?>
</body>
</html>
We have covered all the function related to file input and out in PHP File System Function
chapter.
PHP Functions
PHP functions are similar to other programming languages. A function is a piece of code which
takes one more input in the form of parameter and does some processing and returns a value.
You already have seen many functions like fopen() and fread() etc. They are built-in functions
but PHP gives you option to create your own functions as well.
There are two parts which should be clear to you:
 Creating a PHP Function
 Calling a PHP Function
In fact you hardly need to create your own PHP function because there are already more than
1000 of built-in library functions created for different area and you just need to call them
according to your requirement.
Please refer to PHP Function Reference for a complete set of useful functions.
Creating PHP Function:
Its very easy to create your own PHP function. Suppose you want to create a PHP function which
will simply write a simple message on your browser when you will call it. Following example
creates a function called writeMessage() and then calls it just after creating it.
Note that while creating a function its name should start with keyword function and all the PHP
code should be put inside { and } braces as shown in the following example below:
<html>
<head>
<title>Writing PHP Function</title>
</head>
<body>
<?php
/* Defining a PHP Function */
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 249
SZABIST jstc Shaheed Benazirabad
function writeMessage()
{
echo "You are really a nice person, Have a nice time!";
}
/* Calling a PHP Function */
writeMessage();
?>
</body>
</html>
This will display following result:
You are really a nice person, Have a nice time!
PHP Functions with Parameters:
PHP gives you option to pass your parameters inside a function. You can pass as many as
parameters your like. These parameters work like variables inside your function. Following
example takes two integer parameters and add them together and then print them.
<html>
<head>
<title>Writing PHP Function with Parameters</title>
</head>
<body>
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
</body>
</html>
This will display following result:
Sum of the two numbers is : 30
Passing Arguments by Reference:
It is possible to pass arguments to functions by reference. This means that a reference to the
variable is manipulated by the function rather than a copy of the variable's value.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 250
SZABIST jstc Shaheed Benazirabad
Any changes made to an argument in these cases will change the value of the original variable.
You can pass an argument by reference by adding an ampersand to the variable name in either
the function call or the function definition.
Following example depicts both the cases.
<html>
<head>
<title>Passing Argument by Reference</title>
</head>
<body>
<?php
function addFive($num)
{
$num += 5;
}
function addSix(&$num)
{
$num += 6;
}
$orignum = 10;
addFive( &$orignum );
echo "Original Value is $orignum<br />";
addSix( $orignum );
echo "Original Value is $orignum<br />";
?>
</body>
</html>
This will display following result:
Original Value is 15
Original Value is 21
PHP Functions retruning value:
A function can return a value using the return statement in conjunction with a value or object.
return stops the execution of the function and sends the value back to the calling code.
You can return more than one value from a function using return array(1,2,3,4).
Following example takes two integer parameters and add them together and then returns their
sum to the calling program. Note that return keyword is used to return a value from a function.
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
return $sum;
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 251
SZABIST jstc Shaheed Benazirabad
}
$return_value = addFunction(10, 20);
echo "Returned value from the function : $return_value
?>
</body>
</html>
This will display following result:
Returned value from the function : 30
Setting Default Values for Function Parameters:
You can set a parameter to have a default value if the function's caller doesn't pass it.
Following function prints NULL in case use does not pass any value to this function.
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>
<?php
function printMe($param = NULL)
{
print $param;
}
printMe("This is test");
printMe();
?>
</body>
</html>
This will produce following result:
This is test
Dynamic Function Calls:
It is possible to assign function names as strings to variables and then treat these variables
exactly as you would the function name itself. Following example depicts this behaviour.
<html>
<head>
<title>Dynamic Function Calls</title>
</head>
<body>
<?php
function sayHello()
{
echo "Hello<br />";
}
$function_holder = "sayHello";
$function_holder();
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 252
SZABIST jstc Shaheed Benazirabad
?>
</body>
</html>
This will display following result:
Hello
PHP Cookies
Cookies are text files stored on the client computer and they are kept of use tracking purpose.
PHP transparently supports HTTP cookies.
There are three steps involved in identifying returning users:
 Server script sends a set of cookies to the browser. For example name, age, or
identification number etc.
 Browser stores this information on local machine for future use.
 When next time browser sends any request to web server then it sends those cookies
information to the server and server uses that information to identify the user.
This chapter will teach you how to set cookies, how to access them and how to delete them.
The Anatomy of a Cookie:
Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on
a browser). A PHP script that sets a cookie might send headers that look something like this:
HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT;
path=/; domain=tutorialspoint.com
Connection: close
Content-Type: text/html
As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a
domain. The name and value will be URL encoded. The expires field is an instruction to the
browser to "forget" the cookie after the given time and date.
If the browser is configured to store cookies, it will then keep this information until the expiry
date. If the user points the browser at any page that matches the path and domain of the cookie, it
will resend the cookie to the server.The browser's headers might look something like this:
GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz
A PHP script will then have access to the cookie in the environmental variables $_COOKIE or
$HTTP_COOKIE_VARS[] which holds all cookie names and values. Above cookie can be
accessed using $HTTP_COOKIE_VARS["name"].
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 253
SZABIST jstc Shaheed Benazirabad
Setting Cookies with PHP:
PHP provided setcookie() function to set a cookie. This function requires upto six arguments and
should be called before <html> tag. For each cookie this function has to be called separately.
setcookie(name, value, expire, path, domain, security);
Here is the detail of all the arguments:
 Name - This sets the name of the cookie and is stored in an environment variable called
HTTP_COOKIE_VARS. This variable is used while accessing cookies.
 Value -This sets the value of the named variable and is the content that you actually want
to store.
 Expiry - This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970.
After this time cookie will become inaccessible. If this parameter is not set then cookie
will automatically expire when the Web Browser is closed.
 Path -This specifies the directories for which the cookie is valid. A single forward slash
character permits the cookie to be valid for all directories.
 Domain - This can be used to specify the domain name in very large domains and must
contain at least two periods to be valid. All cookies are only valid for the host and domain
which created them.
 Security - This can be set to 1 to specify that the cookie should only be sent by secure
transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular
HTTP.
Following example will create two cookies name and age these cookies will be expired after one
hour.
<?php
setcookie("name", "John Watkin", time()+3600, "/","", 0);
setcookie("age", "36", time()+3600, "/", "", 0);
?>
<html>
<head>
<title>Setting Cookies with PHP</title>
</head>
<body>
<?php echo "Set Cookies"?>
</body>
</html>
Accessing Cookies with PHP
PHP provides many ways to access cookies.Simplest way is to use either $_COOKIE or
$HTTP_COOKIE_VARS variables. Following example will access all the cookies set in above
example.
<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 254
SZABIST jstc Shaheed Benazirabad
echo $_COOKIE["name"]. "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"]. "<br />";
echo $_COOKIE["age"] . "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"] . "<br />";
?>
</body>
</html>
You can use isset() function to check if a cookie is set or not.
<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
if( isset($_COOKIE["name"]))
echo "Welcome " . $_COOKIE["name"] . "<br />";
else
echo "Sorry... Not recognized" . "<br />";
?>
</body>
</html>
Deleting Cookie with PHP
Officially, to delete a cookie you should call setcookie() with the name argument only but this
does not always work well, however, and should not be relied on.
It is safest to set the cookie with a date that has already expired:
<?php
setcookie( "name", "", time()- 60, "/","", 0);
setcookie( "age", "", time()- 60, "/","", 0);
?>
<html>
<head>
<title>Deleting Cookies with PHP</title>
</head>
<body>
<?php echo "Deleted Cookies" ?>
</body>
</html>
PHP Sessions
An alternative way to make data accessible across the various pages of an entire website is to use
a PHP Session.
A session creates a file in a temporary directory on the server where registered session variables
and their values are stored. This data will be available to all pages on the site during that visit.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 255
SZABIST jstc Shaheed Benazirabad
The location of the temporary file is determined by a setting in the php.ini file called
session.save_path. Bore using any session variable make sure you have setup this path.
When a session is started following things happen:
 PHP first creates a unique identifier for that particular session which is a random string of
32 hexadecimal numbers such as 3c7foj34c3jj973hjkop2fc937e3443.
 A cookie called PHPSESSID is automatically sent to the user's computer to store unique
session identification string.
 A file is automatically created on the server in the designated temporary directory and
bears the name of the unique identifier prefixed by sess_ ie
sess_3c7foj34c3jj973hjkop2fc937e3443.
When a PHP script wants to retrieve the value from a session variable, PHP automatically gets
the unique session identifier string from the PHPSESSID cookie and then looks in its temporary
directory for the file bearing that name and a validation can be done by comparing both values.
A session ends when the user loses the browser or after leaving the site, the server will terminate
the session after a predetermined period of time, commonly 30 minutes duration.
Starting a PHP Session:
A PHP session is easily started by making a call to the session_start() function.This function
first checks if a session is already started and if none is started then it starts one. It is
recommended to put the call to session_start() at the beginning of the page.
Session variables are stored in associative array called $_SESSION[]. These variables can be
accessed during lifetime of a session.
The following example starts a session then register a variable called counter that is incremented
each time the page is visited during the session.
Make use of isset() function to check if session variable is already set or not.
Put this code in a test.php file and load this file many times to see the result:
<?php
session_start();
if( isset( $_SESSION['counter'] ) )
{
$_SESSION['counter'] += 1;
}
else
{
$_SESSION['counter'] = 1;
}
$msg = "You have visited this page ".
$msg .= "in this session.";
?>
<html>
<head>
<title>Setting up a PHP session</title>
</head>
<body>
<?php echo ( $msg ); ?>
</body>
</html>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
$_SESSION['counter'];
Page 256
SZABIST jstc Shaheed Benazirabad
Destroying a PHP Session:
A PHP session can be destroyed by session_destroy() function. This function does not need any
argument and a single call can destroy all the session variables. If you want to destroy a single
session variable then you can use unset() function to unset a session variable.
Here is the example to unset a single variable:
<?php
unset($_SESSION['counter']);
?>
Here is the call which will destroy all the session variables:
<?php
session_destroy();
?>
Turning on Auto Session:
You don't need to call start_session() function to start a session when a user visits your site if you
can set session.auto_start variable to 1 in php.ini file.
Sessions without cookies:
There may be a case when a user does not allow to store cookies on their machine. So there is
another method to send session ID to the browser.
Alternatively, you can use the constant SID which is defined if the session started. If the client
did not send an appropriate session cookie, it has the form session_name=session_id. Otherwise,
it expands to an empty string. Thus, you can embed it unconditionally into URLs.
The following example demonstrates how to register a variable, and how to link correctly to
another page using SID.
<?php
session_start();
if (isset($_SESSION['counter'])) {
$_SESSION['counter'] = 1;
} else {
$_SESSION['counter']++;
}
?>
$msg = "You have visited this page ".
$msg .= "in this session.";
echo ( $msg );
$_SESSION['counter'];
<p>
To continue click following link <br />
<a href="nextpage.php?<?php echo htmlspecialchars(SID); >">
</p>
The htmlspecialchars() may be used when printing the SID in order to prevent XSS related
attacks.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 257
SZABIST jstc Shaheed Benazirabad
PHP - Sending Emails
PHP must be configured correctly in the php.ini file with the details of how your system sends
email. Open php.ini file available in /etc/ directory and find the section headed [mail function].
Windows users should ensure that two directives are supplied. The first is called SMTP that
defines your email server address. The second is called sendmail_from which defines your own
email address.
The configuration for Windows should look something like this:
[mail function]
; For Win32 only.
SMTP = smtp.secureserver.net
; For win32 only
sendmail_from = webmaster@tutorialspoint.com
Linux users simply need to let PHP know the location of their sendmail application. The path
and any desired switches should be specified to the sendmail_path directive.
The configuration for Linux should look something like this:
[mail function]
; For Win32 only.
SMTP =
; For win32 only
sendmail_from =
; For Unix only
sendmail_path = /usr/sbin/sendmail -t -i
Now you are ready to go:
Sending plain text email:
PHP makes use of mail() function to send an email. This function requires three mandatory
arguments that specify the recipient's email address, the subject of the the message and the actual
message additionally there are other two optional parameters.
mail( to, subject, message, headers, parameters );
Here is the description for each parameters.
Parameter
Description
to
Required. Specifies the receiver / receivers of the email
subject
Required. Specifies the subject of the email. This parameter cannot contain
any newline characters
message
Required. Defines the message to be sent. Each line should be separated with
a LF (\n). Lines should not exceed 70 characters
headers
Optional. Specifies additional headers, like From, Cc, and Bcc. The
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 258
SZABIST jstc Shaheed Benazirabad
additional headers should be separated with a CRLF (\r\n)
parameters
Optional. Specifies an additional parameter to the sendmail program
As soon as the mail function is called PHP will attempt to send the email then it will return true
if successful or false if it is failed.
Multiple recipients can be specified as the first argument to the mail() function in a comma
separated list.
Example:
Following example will send an HTML email message to xyz@somedomain.com. You can code
this program in such a way that it should receive all content from the user and then it should send
an email.
<html>
<head>
<title>Sending email using PHP</title>
</head>
<body>
<?php
$to = "xyz@somedomain.com";
$subject = "This is subject";
$message = "This is simple text message.";
$header = "From:abc@somedomain.com \r\n";
$retval = mail ($to,$subject,$message,$header);
if( $retval == true )
{
echo "Message sent successfully...";
}
else
{
echo "Message could not be sent...";
}
?>
</body>
</html>
Sending HTML email:
When you send a text message using PHP then all the content will be treated as simple text. Even
if you will include HTML tags in a text message, it will be displayed as simple text and HTML
tags will not be formatted according to HTML syntax. But PHP provides option to send an
HTML message as actual HTML message.
While sending an email message you can specify a Mime version, content type and character set
to send an HTML email.
Example:
Following example will send an HTML email message to xyz@somedomain.com copying it to
afgh@somedomain.com. You can code this program in such a way that it should recieve all
content from the user and then it should send an email.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 259
SZABIST jstc Shaheed Benazirabad
<html>
<head>
<title>Sending HTML email using PHP</title>
</head>
<body>
<?php
$to = "xyz@somedomain.com";
$subject = "This is subject";
$message = "<b>This is HTML message.</b>";
$message .= "<h1>This is headline.</h1>";
$header = "From:abc@somedomain.com \r\n";
$header = "Cc:afgh@somedomain.com \r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";
$retval = mail ($to,$subject,$message,$header);
if( $retval == true )
{
echo "Message sent successfully...";
}
else
{
echo "Message could not be sent...";
}
?>
</body>
</html>
Sending attachments with email:
To send an email with mixed content requires to set Content-type header to multipart/mixed.
Then text and attachment sections can be specified within boundaries.
A boundary is started with two hyphens followed by a unique number which can not appear in
the message part of the email. A PHP function md5() is used to create a 32 digit hexadecimal
number to create unique number. A final boundary denoting the email's final section must also
end with two hyphens.
Attached files should be encoded with the base64_encode() function for safer transmission and
are best split into chunks with the chunk_split() function. This adds \r\n inside the file at regular
intervals, normally every 76 characters.
Following is the example which will send a file /tmp/test.txt as an attachment. you can code
your program to receive an uploaded file and send it.
<html>
<head>
<title>Sending attachment using PHP</title>
</head>
<body>
<?php
$to = "xyz@somedomain.com";
$subject = "This is subject";
$message = "This is test message.";
# Open a file
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 260
SZABIST jstc Shaheed Benazirabad
$file = fopen( "/tmp/test.txt", "r" );
if( $file == false )
{
echo "Error in opening file";
exit();
}
# Read the file into a variable
$size = filesize("/tmp/test.txt");
$content = fread( $file, $size);
# encode the data for safe transit
# and insert \r\n after every 76 chars.
$encoded_content = chunk_split( base64_encode($content));
# Get a random 32 bit number using time() as seed.
$num = md5( time() );
# Define the main headers.
$header = "From:xyz@somedomain.com\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; ";
$header .= "boundary=$num\r\n";
$header .= "--$num\r\n";
# Define the message section
$header .= "Content-Type: text/plain\r\n";
$header .= "Content-Transfer-Encoding:8bit\r\n\n";
$header .= "$message\r\n";
$header .= "--$num\r\n";
# Define the attachment section
$header .= "Content-Type: multipart/mixed; ";
$header .= "name=\"test.txt\"\r\n";
$header .= "Content-Transfer-Encoding:base64\r\n";
$header .= "Content-Disposition:attachment; ";
$header .= "filename=\"test.txt\"\r\n\n";
$header .= "$encoded_content\r\n";
$header .= "--$num--";
# Send email now
$retval = mail ( $to, $subject, "", $header );
if( $retval == true )
{
echo "Message sent successfully...";
}
else
{
echo "Message could not be sent...";
}
?>
</body>
</html>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 261
SZABIST jstc Shaheed Benazirabad
You try all the above examples. If you face any problem then you can post that problem in
discussion forum.
PHP File Uploading
A PHP script can be used with a HTML form to allow users to upload files to the server. Initially
files are uploaded into a temporary directory and then relocated to a target destination by a PHP
script.
Information in the phpinfo.php page describes the temporary directory that is used for file
uploads as upload_tmp_dir and the maximum permitted size of files that can be uploaded is
stated as upload_max_filesize. These parameters are set into PHP configuration file php.ini
The process of uploading a file follows these steps
 The user opens the page containing a HTML form featuring a text files, a browse button
and a submit button.
 The user clicks the browse button and selects a file to upload from the local PC.
 The full path to the selected file appears in the text filed then the user clicks the submit
button.
 The selected file is sent to the temporary directory on the server.
 The PHP script that was specified as the form handler in the form's action attribute
checks that the file has arrived and then copies the file into an intended directory.
 The PHP script confirms the success to the user.
As usual when writing files it is necessary for both temporary and final locations to have
permissions set that enable file writing. If either is set to be read-only then process will fail.
An uploaded file could be a text file or image file or any document.
Creating an upload form:
The following HTM code below creates an uploader form. This form is having method attribute
set to post and enctype attribute is set to multipart/form-data
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="/php/file_uploader.php" method="post"
enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>
This will display following result:
File Upload:
Select a file to upload:
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 262
SZABIST jstc Shaheed Benazirabad
NOTE: This is just dummy form and would not work.
Creating an upload script:
There is one global PHP variable called $_FILES. This variable is an associate double
dimension array and keeps all the information related to uploaded file. So if the value assigned to
the input's name attribute in uploading form was file, then PHP would create following five
variables:
 $_FILES['file']['tmp_name']- the uploaded file in the temporary directory on the web
server.
 $_FILES['file']['name'] - the actual name of the uploaded file.
 $_FILES['file']['size'] - the size in bytes of the uploaded file.
 $_FILES['file']['type'] - the MIME type of the uploaded file.
 $_FILES['file']['error'] - the error code associated with this file upload.
The following example below attempts to copy a file uploaded by the HTML Form listed in
previous section page to /var/www/html directory which is document root of your PHP server
and it will display all the file's detail upon completion. Please note that if you are going to
display uploaded file then don't try with binary files like images or word document.
Here is the code of uploader.php script which will take care of uploading a file.
<?php
if( $_FILES['file']['name'] != "" )
{
copy( $_FILES['file']['name'], "/var/www/html" )
die( "Could not copy file!");
}
else
{
die("No file specified!");
}
?>
<html>
<head>
<title>Uploading Complete</title>
</head>
<body>
<h2>Uploaded File Info:</h2>
<ul>
<li>Sent file: <?php echo $_FILES['file']['name'];
<li>File size: <?php echo $_FILES['file']['size'];
<li>File type: <?php echo $_FILES['file']['type'];
</ul>
</body>
</html>
or
?>
?> bytes
?>
When you will upload a file using upload form and upload script, it will display following result:
Uploaded File Info:
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 263
SZABIST jstc Shaheed Benazirabad

Sent file: uploadedfile.txt

File size: 2003 bytes

File type: image/jpg
PHP File Handling
Opening a File
The fopen() function is used to open files in PHP.
The first parameter of this function contains the name of the file to be opened and the second
parameter specifies in which mode the file should be opened:
<html>
<body>
<?php
$file=fopen("welcome.txt","r");
?>
</body>
</html>
The file may be opened in one of the following modes:
Modes
R
r+
W
w+
a
a+
x
x+
Description
Read only. Starts at the beginning of the file
Read/Write. Starts at the beginning of the file
Write only. Opens and clears the contents of file; or creates a new file if it doesn't
exist
Read/Write. Opens and clears the contents of file; or creates a new file if it
doesn't exist
Append. Opens and writes to the end of the file or creates a new file if it doesn't
exist
Read/Append. Preserves file content by writing to the end of the file
Write only. Creates a new file. Returns FALSE and an error if file already exists
Read/Write. Creates a new file. Returns FALSE and an error if file already exists
Note: If the fopen() function is unable to open the specified file, it returns 0 (false).
Example
The following example generates a message if the fopen() function is unable to open the
specified file:
<html>
<body>
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
?>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 264
SZABIST jstc Shaheed Benazirabad
</body>
</html>
Closing a File
The fclose() function is used to close an open file:
<?php
$file = fopen("test.txt","r");
//some code to be executed
fclose($file);
?>
Check End-of-file
The feof() function checks if the "end-of-file" (EOF) has been reached.
The feof() function is useful for looping through data of unknown length.
Note: You cannot read from files opened in w, a, and x mode!
if (feof($file)) echo "End of file";
Reading a File Line by Line
The fgets() function is used to read a single line from a file.
Note: After a call to this function the file pointer has moved to the next line.
Example
The example below reads a file line by line, until the end of file is reached:
<?php
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
{
echo fgets($file). "<br>";
}
fclose($file);
?>
Reading a File Character by Character
The fgetc() function is used to read a single character from a file.
Note: After a call to this function the file pointer moves to the next character.
Example
The example below reads a file character by character, until the end of file is reached:
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 265
SZABIST jstc Shaheed Benazirabad
while (!feof($file))
{
echo fgetc($file);
}
fclose($file);
?>
PHP - Coding Standard
Every company follows a different coding standard based on their best practices. Coding
standard is required because there may be many developers working on different modules so if
they will start inventing their own standards then source will become very un-manageable and it
will become difficult to maintain that source code in future.
Here are several reasons why to use coding specifications:
 Your peer programmers have to understand the code you produce. A coding standard acts
as the blueprint for all the team to decipher the code.
 Simplicity and clarity achieved by consistent coding saves you from common mistakes.
 If you revise your code after some time then it becomes easy to understand that code.
 Its industry standard to follow a particular standard to being more quality in software.
There are few guidelines which can be followed while coding in PHP.
 Indenting and Line Length - Use an indent of 4 spaces and don't use any tab because
different computers use different setting for tab. It is recommended to keep lines at
approximately 75-85 characters long for better code readability.
 Control Structures - These include if, for, while, switch, etc. Control statements should
have one space between the control keyword and opening parenthesis, to distinguish
them from function calls. You are strongly encouraged to always use curly braces even in
situations where they are technically optional.
Examples:
if ((condition1) || (condition2)) {
action1;
} elseif ((condition3) && (condition4)) {
action2;
} else {
default action;
}
You can writ eswitch statements as follows:
switch (condition) {
case 1:
action1;
break;
case 2:
action2;
break;
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 266
SZABIST jstc Shaheed Benazirabad
default:
defaultaction;
break;
}

Function Calls - Functions should be called with no spaces between the function name,
the opening parenthesis, and the first parameter; spaces between commas and each
parameter, and no space between the last parameter, the closing parenthesis, and the
semicolon. Here's an example:
$var = foo($bar, $baz, $quux);

Function Definitions - Function declarations follow the "BSD/Allman style":
function fooFunction($arg1, $arg2 = '')
{
if (condition) {
statement;
}
return $val;
}

Comments - C style comments (/* */) and standard C++ comments (//) are both fine. Use
of Perl/shell style comments (#) is discouraged.
 PHP Code Tags - Always use <?php ?> to delimit PHP code, not the <? ?> shorthand.
This is required for PHP compliance and is also the most portable way to include PHP
code on differing operating systems and setups.
 Variable Names o Use all lower case letters
o Use '_' as the word separator.
o Global variables should be prepended with a 'g'.
o Global constants should be all caps with '_' separators.
o Static variables may be prepended with 's'.
 Make Functions Reentrant - Functions should not keep static variables that prevent a
function from being reentrant.
 Alignment of Declaration Blocks - Block of declarations should be aligned.
 One Statement Per Line - There should be only one statement per line unless the
statements are very closely related.
 Short Methods or Functions - Methods should limit themselves to a single page of
code.
There could be many more points which should be considered while writing your PHP program.
Over all intension should be to be consistent throughout of the code programming and it will be
possible only when you will follow any coding standard. YOu can device your own standard if
you like something different.
PHP Date and Time
Dates are so much part of everyday life that it becomes easy to work with them without thinking.
PHP also provides powerful tools for date arithmetic that make manipulating dates easy.
Getting the Time Stamp with time():
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 267
SZABIST jstc Shaheed Benazirabad
PHP's time() function gives you all the information that you need about the current date and
time. It requires no arguments but returns an integer.
The integer returned by time() represents the number of seconds elapsed since midnight GMT on
January 1, 1970. This moment is known as the UNIX epoch, and the number of seconds that
have elapsed since then is referred to as a time stamp.
<?php
print time();
?>
It will produce following result:
948316201
This is something difficult to understand. But PHP offers excellent tools to convert a time stamp
into a form that humans are comfortable with.
Converting a Time Stamp with getdate():
The function getdate() optionally accepts a time stamp and returns an associative array
containing information about the date. If you omit the time stamp, it works with the current time
stamp as returned by time().
Following table lists the elements contained in the array returned by getdate().
Key
Description
Example
seconds
Seconds past the minutes (0-59)
20
minutes
Minutes past the hour (0 - 59)
29
hours
Hours of the day (0 - 23)
22
mday
Day of the month (1 - 31)
11
wday
Day of the week (0 - 6)
4
mon
Month of the year (1 - 12)
7
year
Year (4 digits)
1997
yday
Day of year ( 0 - 365 )
19
weekday Day of the week
Thursday
month
Month of the year
January
0
Timestamp
948370048
Now you have complete control over date and time. You can format this date and time in
whatever format you wan.
Example:
Try out following example
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 268
SZABIST jstc Shaheed Benazirabad
<?php
$date_array = getdate();
foreach ( $date_array as $key => $val )
{
print "$key = $val<br />";
}
$formated_date = "Today's date: ";
$formated_date .= $date_array[mday] . "/";
$formated_date .= $date_array[mon] . "/";
$formated_date .= $date_array[year];
print $formated_date;
?>
It will produce following result:
seconds = 27
minutes = 25
hours = 11
mday = 12
wday = 6
mon = 5
year = 2007
yday = 131
weekday = Saturday
month = May
0 = 1178994327
Today's date: 12/5/2007
Converting a Time Stamp with date():
The date() function returns a formatted string representing a date. You can exercise an enormous
amount of control over the format that date() returns with a string argument that you must pass to
it.
date(format,timestamp)
The date() optionally accepts a time stamp if ommited then current date and time will be used.
Any other data you include in the format string passed to date() will be included in the return
value.
Following table lists the codes that a format string can contain:
Format
Description
Example
a
'am' or 'pm' lowercase
pm
A
'AM' or 'PM' uppercase
PM
d
Day of month, a number with leading zeroes
20
D
Day of week (three letters)
Thu
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 269
SZABIST jstc Shaheed Benazirabad
F
Month name
January
h
Hour (12-hour format - leading zeroes)
12
H
Hour (24-hour format - leading zeroes)
22
g
Hour (12-hour format - no leading zeroes)
12
G
Hour (24-hour format - no leading zeroes)
22
i
Minutes ( 0 - 59 )
23
j
Day of the month (no leading zeroes
20
l (Lower 'L')
Day of the week
Thursday
L
Leap year ('1' for yes, '0' for no)
1
m
Month of year (number - leading zeroes)
1
M
Month of year (three letters)
Jan
r
The RFC 2822 formatted date
Thu, 21 Dec 2000
16:01:07 +0200
n
Month of year (number - no leading zeroes)
2
s
Seconds of hour
20
U
Time stamp
948372444
y
Year (two digits)
06
Y
Year (four digits)
2006
z
Day of year (0 - 365)
206
Z
Offset in seconds from GMT
+5
Example:
Try out following example
<?php
print date("m/d/y G.i:s<br>", time());
print "Today is ";
print date("j of F Y, \a\\t g.i a", time());
?>
It will produce following result:
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 270
SZABIST jstc Shaheed Benazirabad
01/20/00 13.27:55
Today is 20 of January 2000, at 1.27 pm
Hope you have good understanding on how to format date and time according to your
requirement. For your reference a complete list of all the date and time functions is given in PHP
Date & Time Functions.
PHP and MySQL
Object Oriented Programming in PHP
We can imagine our universe made of different objects like sun, earth, moon etc. Similarly we
can imagine our car made of different objects like wheel, steering, gear etc. Same way there is
object oriented programming concepts which assume everything as an object and implement a
software using different objects.
Object Oriented Concepts:
Before we go in detail, lets define important terms related to Object Oriented Programming.
 Class: This is a programmer-defined datatype, which includes local functions as well as
local data. You can think of a class as a template for making many instances of the same
kind (or class) of object.
 Object: An individual instance of the data structure defined by a class. You define a class
once and then make many objects that belong to it. Objects are also known as instance.
 Member Variable: These are the variables defined inside a class. This data will be
invisible to the outside of the class and can be accessed via member functions. These
variables are called attribute of the object once an object is created.
 Member function: These are the function defined inside a class and are used to access
object data.
 Inheritance: When a class is defined by inheriting existing function of a parent class
then it is called inheritance. Here child class will inherit all or few member functions and
variables of a parent class.
 Parent class: A class that is inherited from by another class. This is also called a base
class or super class.
 Child Class: A class that inherits from another class. This is also called a subclass or
derived class.
 Polymorphism: This is an object oriented concept where same function can be used for
different purposes. For example function name will remain same but it make take
different number of arguments and can do different task.
 Overloading: a type of polymorphism in which some or all of operators have different
implementations depending on the types of their arguments. Similarly functions can also
be overloaded with different implementation.
 Data Abstraction: Any representation of data in which the implementation details are
hidden (abstracted).
 Encapsulation: refers to a concept where we encapsulate all the data and member
functions together to form an object.
 Constructor: refers to a special type of function which will be called automatically
whenever there is an object formation from a class.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 271
SZABIST jstc Shaheed Benazirabad

Destructors: refers to a special type of function which will be called automatically
whenever an object is deleted or goes out of scope.
Defining PHP Classes:
The general form for defining a new class in PHP is as follows:
<?php
class phpClass{
var $var1;
var $var2 = "constant string";
function myfunc ($arg1, $arg2) {
[..]
}
[..]
}
?>
Here is the description of each line:
 The special form class, followed by the name of the class that you want to define.
 A set of braces enclosing any number of variable declarations and function definitions.
 Variable declarations start with the special form var, which is followed by a conventional
$ variable name; they may also have an initial assignment to a constant value.
 Function definitions look much like standalone PHP functions but are local to the class
and will be used to set and access object data.
Example:
Here is an example which defines a class of Books type:
<?php
class Books{
/* Member variables */
var $price;
var $title;
/* Member functions */
function setPrice($par){
$this->price = $var;
}
function getPrice(){
echo $this->price ."<br/>";
}
function setTitle($par){
$this->title = $par;
}
function getTitle(){
echo $this->title ." <br/>";
}
}
?>
The variable $this is a special variable and it refers to the same object ie. itself.
Creating Objects in PHP
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 272
SZABIST jstc Shaheed Benazirabad
Once you defined your class, then you can create as many objects as you like of that class type.
Following is an example of how to create object using new operator.
$physics = new Books;
$maths = new Books;
$chemistry = new Books;
Here we have created three objects and these objects are independent of each other and they will
have their existance separately. Next we will see how to access member function and process
member variables.
Calling Member Functions
After creating your objects, you will be able to call member functions related to that object. One
member function will be able to process member variable of related object only.
Following example shows how to set title and prices for the three books by calling member
functions.
$physics->setTitle( "Physics for High School" );
$chemistry->setTitle( "Advanced Chemistry" );
$maths->setTitle( "Algebra" );
$physics->setPrice( 10 );
$chemistry->setPrice( 15 );
$maths->setPrice( 7 );
Now you call another member functions to get the values set by in above example:
$physics->getTitle();
$chemistry->getTitle();
$maths->getTitle();
$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();
This will produce follwoing result:
Physics for High School
Advanced Chemistry
Algebra
10
15
7
Constructor Functions:
Constructor Functions are special type of functions which are called automatically whenever an
object is created. So we take full advantage of this behaviour, by initializing many things through
constructor functions.
PHP provides a special function called __construct() to define a constructor. You can pass as
many as arguments you like into the constructor function.
Following example will create one constructor for Books class and it will initialize price and title
for the book at the time of object creation.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 273
SZABIST jstc Shaheed Benazirabad
function __construct( $par1, $par2 ){
$this->price = $par1;
$this->title = $par2;
}
Now we don't need to call set function separately to set price and title. We can initialize these
two member variables at the time of object creation only. Check following example below:
$physics = new Books( "Physics for High School", 10 );
$maths = new Books ( "Advanced Chemistry", 15 );
$chemistry = new Books ("Algebra", 7 );
/* Get those set values */
$physics->getTitle();
$chemistry->getTitle();
$maths->getTitle();
$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();
This will produce following result:
Physics for High School
Advanced Chemistry
Algebra
10
15
7
Destructor:
Like a constructor function you can define a destructor function using function __destruct().
You can release all the resourceses with-in a destructor.
Inheritance:
PHP class definitions can optionally inherit from a parent class definition by using the extends
clause. The syntax is as follows:
class Child extends Parent {
<definition body>
}
The effect of inheritance is that the child class (or subclass or derived class) has the following
characteristics:
 Automatically has all the member variable declarations of the parent class.
 Automatically has all the same member functions as the parent, which (by default) will
work the same way as those functions do in the parent.
Following example inherit Books class and adds more functionality based on the requirement.
class Novel extends Books{
var publisher;
function setPublisher($par){
$this->publisher = $par;
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 274
SZABIST jstc Shaheed Benazirabad
}
function getPublisher(){
echo $this->publisher. "<br />";
}
}
Now apart from inherited functions, class Novel keeps two additional member functions.
Function Overriding:
Function definitions in child classes override definitions with the same name in parent classes. In
a child class, we can modify the definition of a function inherited from parent class.
In the follwoing example getPrice and getTitle functions are overriden to retrun some values.
function getPrice(){
echo $this->price . "<br/>";
return $this->price;
}
function getTitle(){
echo $this->title . "<br/>";
return $this->title;
}
Public Members:
Unless you specify otherwise, properties and methods of a class are public. That is to say, they
may be accessed in three possible situations:
 From outside the class in which it is declared
 From within the class in which it is declared
 From within another class that implements the class in which it is declared
Till now we have seen all members as public members. If you wish to limit the accessibility of
the members of a class then you define class members as private or protected.
Private members:
By designating a member private, you limit its accessibility to the class in which it is declared.
The private member cannot be referred to from classes that inherit the class in which it is
declared and cannot be accessed from outside the class.
A class member can be made private by using private keyword infront of the member.
class MyClass {
private $car = "skoda";
$driver = "SRK";
function __construct($par) {
// Statements here run every time
// an instance of the class
// is created.
}
function myPublicFunction() {
return("I'm visible!");
}
private function myPrivateFunction() {
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 275
SZABIST jstc Shaheed Benazirabad
return("I'm
not visible outside!");
}
}
When MyClass class is inherited by another class using extends, myPublicFunction() will be
visible, as will $driver. The extending class will not have any awareness of or access to
myPrivateFunction and $car, because they are declared private.
Protected members:
A protected property or method is accessible in the class in which it is declared, as well as in
classes that extend that class. Protected members are not available outside of those two kinds of
classes. A class member can be made protected by using protected keyword infront of the
member.
Here is different version of MyClass:
class MyClass {
protected $car = "skoda";
$driver = "SRK";
function __construct($par) {
// Statements here run every time
// an instance of the class
// is created.
}
function myPublicFunction() {
return("I'm visible!");
}
protected function myPrivateFunction() {
return("I'm visible in child class!");
}
}
Interfaces:
Interfaces are defined to provide a common function names to the implementors. Different
implementors can implement those interfaces according to theri requirements. You can say,
interfaces are skeltons which are implemented by developers.
As of PHP5, it is possible to define an interface, like this:
interface Mail {
public function sendMail();
}
Then, if another class implemented that interface, like this:
class Report implements Mail {
// sendMail() Definition goes here
}
Constants:
A constant is somewhat like a variable, in that it holds a value, but is really more like a function
because a constant is immutable. Once you declare a constant, it does not change.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 276
SZABIST jstc Shaheed Benazirabad
Declaring one constant is easy, as is done in this version of MyClass:
class MyClass {
const requiredMargin = 1.7;
function __construct($incomingValue) {
// Statements here run every time
// an instance of the class
// is created.
}
}
In this class, requiredMargin is a constant. It is declared with the keyword const, and under no
circumstances can it be changed to anything other than 1.7. Note that the constant's name does
not have a leading $, as variable names do.
Abstract Classes:
An abstract class is one that cannot be instantiated, only inherited. You declare an abstract class
with the keyword abstract, like this:
When inheriting from an abstract class, all methods marked abstract in the parent's class
declaration must be defined by the child; additionally, these methods must be defined with the
same visibillity.
abstract class MyAbstractClass {
abstract function myAbstractFunction() {
}
}
Note that function definitions inside an abstract class must also be preceded by the keyword
abstract. It is not legal to have abstract function definitions inside a non-abstract class.
Static Keyword:
Declaring class members or methods as static makes them accessible without needing an
instantiation of the class. A member declared as static can not be accessed with an instantiated
class object (though a static method can).
Try out following example:
<?php
class Foo
{
public static $my_static = 'foo';
public function staticValue() {
return self::$my_static;
}
}
print Foo::$my_static . "\n";
$foo = new Foo();
print $foo->staticValue() . "\n";
Final Keyword:
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 277
SZABIST jstc Shaheed Benazirabad
PHP 5 introduces the final keyword, which prevents child classes from overriding a method by
prefixing the definition with final. If the class itself is being defined final then it cannot be
extended.
Following example results in Fatal error: Cannot override final method
BaseClass::moreTesting()
<?php
class BaseClass {
public function test() {
echo "BaseClass::test() called<br>";
}
final public function moreTesting() {
echo "BaseClass::moreTesting() called<br>";
}
}
class ChildClass extends BaseClass {
public function moreTesting() {
echo "ChildClass::moreTesting() called<br>";
}
}
?>
Calling parent constructors:
Instead of writing an entirely new constructor for the subclass, let's write it by calling the parent's
constructor explicitly and then doing whatever is necessary in addition for instantiation of the
subclass. Here's a simple example:
class Name
{
var $_firstName;
var $_lastName;
function Name($first_name, $last_name)
{
$this->_firstName = $first_name;
$this->_lastName = $last_name;
}
function toString() {
return($this->_lastName .", " .$this->_firstName);
}
}
class NameSub1 extends Name
{
var $_middleInitial;
function NameSub1($first_name, $middle_initial, $last_name) {
Name::Name($first_name, $last_name);
$this->_middleInitial = $middle_initial;
}
function toString() {
return(Name::toString() . " " . $this->_middleInitial);
}
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 278
SZABIST jstc Shaheed Benazirabad
}
In this example, we have a parent class (Name), which has a two-argument constructor, and a
subclass (NameSub1), which has a three-argument constructor. The constructor of NameSub1
functions by calling its parent constructor explicitly using the :: syntax (passing two of its
arguments along) and then setting an additional field. Similarly, NameSub1 defines its
nonconstructor toString() function in terms of the parent function that it overrides.
NOTE: A constructor can be defined with the same name as the name of a class. It is defined in
above example.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 279
SZABIST jstc Shaheed Benazirabad
PHP Database
PHP MySQL Introduction
With PHP, you can connect to and manipulate databases.
MySQL is the most popular database system used with PHP.
What is MySQL?









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 supports 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 MySQL is stored in tables. A table is a collection of related data, and it consists of
columns and rows.
Databases are useful when storing information categorically. A company may have a database
with the following tables:




Employees
Products
Customers
Orders
PHP + MySQL

PHP combined with MySQL are cross-platform (you can develop in Windows and serve on a Unix
platform)
Queries
A query is a question or a request.
We can query a database for specific information and have a recordset returned.
Look at the following query (using standard SQL):
SELECT LastName FROM Employees
The query above selects all the data in the "LastName" column from the "Employees" table.
To learn more about SQL, please visit our SQL tutorial.
Download MySQL Database
If you don't have a PHP server with a MySQL Database, you can download MySQL for free
here: http://www.mysql.com
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 280
SZABIST jstc Shaheed Benazirabad
Facts About MySQL Database
One great thing about MySQL is that it can be scaled down to support embedded database
applications. Maybe it is because of this many people think that MySQL can only handle small
and medium-sized systems.
The truth is that MySQL is the de-facto standard database system for web sites with HUGE
volumes of both data and end users (like Friendster, Yahoo, and Google).
Look at http://www.mysql.com/customers/ for an overview of companies using MySQL.
PHP Connect to the MySQL Server
Use the PHP mysqli_connect() function to open a new connection to the MySQL server.
Open a Connection to the MySQL Server
Before we can access data in a database, we must open a connection to the MySQL server.
In PHP, this is done with the mysqli_connect() function.
Syntax
mysqli_connect(host,username,password,dbname);
Parameter
host
username
password
dbname
Description
Optional. Either a host name or an IP address
Optional. The MySQL user name
Optional. The password to log in with
Optional. The default database to be used when performing queries
Note: There are more available parameters, but the ones listed above are the most important.
In the following example we store the connection in a variable ($con) for later use in the script:
<?php
// Create connection
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Close a Connection
The connection will be closed automatically when the script ends. To close the connection
before, use the mysqli_close() function:
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 281
SZABIST jstc Shaheed Benazirabad
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($con);
?>
PHP Create Database and Tables
A database holds one or more tables.
Create a Database
The CREATE DATABASE statement is used to create a database table in MySQL.
We must add the CREATE DATABASE statement to the mysqli_query() function to execute the
command.
The following example creates a database named "my_db":
<?php
$con=mysqli_connect("example.com","peter","abc123");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Create database
$sql="CREATE DATABASE my_db";
if (mysqli_query($con,$sql))
{
echo "Database my_db created successfully";
}
else
{
echo "Error creating database: " . mysqli_error($con);
}
?>
Create a Table
The CREATE TABLE statement is used to create a table in MySQL.
We must add the CREATE TABLE statement to the mysqli_query() function to execute the
command.
The following example creates a table named "Persons", with three columns. The column names
will be "FirstName", "LastName" and "Age":
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 282
SZABIST jstc Shaheed Benazirabad
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Create table
$sql="CREATE TABLE persons(FirstName CHAR(30),LastName CHAR(30),Age INT)";
// Execute query
if (mysqli_query($con,$sql))
{
echo "Table persons created successfully";
}
else
{
echo "Error creating table: " . mysqli_error($con);
}
?>
Note: When you create a database field of type CHAR, you must specify the maximum length of
the field, e.g. CHAR(50).
The data type specifies what type of data the column can hold. For a complete reference of all
the data types available in MySQL, go to our complete Data Types reference.
Primary Keys and Auto Increment Fields
Each table in a database should have a primary key field.
A primary key is used to uniquely identify the rows in a table. Each primary key value must be
unique within the table. Furthermore, the primary key field cannot be null because the database
engine requires a value to locate the record.
The following example sets the PID field as the primary key field. The primary key field is often
an ID number, and is often used with the AUTO_INCREMENT setting. AUTO_INCREMENT
automatically increases the value of the field by 1 each time a new record is added. To ensure
that the primary key field cannot be null, we must add the NOT NULL setting to the field:
$sql = "CREATE TABLE Persons
(
PID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(PID),
FirstName CHAR(15),
LastName CHAR(15),
Age INT
)";
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 283
SZABIST jstc Shaheed Benazirabad
PHP MySQL Insert Into
The INSERT INTO statement is used to insert new records in a table.
Insert Data Into a Database Table
The INSERT INTO statement is used to add new records to a database table.
Syntax
It is possible to write the INSERT INTO statement in two forms.
The first form doesn't specify the column names where the data will be inserted, only their
values:
INSERT INTO table_name
VALUES (value1, value2, value3,...)
The second form specifies both the column names and the values to be inserted:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
To learn more about SQL, please visit our SQL tutorial.
To get PHP to execute the statements above we must use the mysqli_query() function. This
function is used to send a query or command to a MySQL connection.
Example
In the previous chapter we created a table named "Persons", with three columns; "FirstName",
"LastName" and "Age". We will use the same table in this example. The following example adds
two new records to the "Persons" table:
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Peter', 'Griffin',35)");
mysqli_query($con,"INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Glenn', 'Quagmire',33)");
mysqli_close($con);
?>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 284
SZABIST jstc Shaheed Benazirabad
Insert Data From a Form Into a Database
Now we will create an HTML form that can be used to add new records to the "Persons" table.
Here is the HTML form:
<html>
<body>
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
Age: <input type="text" name="age">
<input type="submit">
</form>
</body>
</html>
When a user clicks the submit button in the HTML form in the example above, the form data is
sent to "insert.php".
The "insert.php" file connects to a database, and retrieves the values from the form with the PHP
$_POST variables.
Then, the mysqli_query() function executes the INSERT INTO statement, and a new record will
be added to the "Persons" table.
Here is the "insert.php" page:
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 285
SZABIST jstc Shaheed Benazirabad
PHP MySQL Select
The SELECT statement is used to select data from a database.
Select Data From a Database Table
The SELECT statement is used to select data from a database.
Syntax
SELECT column_name(s)
FROM table_name
To learn more about SQL, please visit our SQL tutorial.
To get PHP to execute the statement above we must use the mysqli_query() function. This
function is used to send a query or command to a MySQL connection.
Example
The following example selects all the data stored in the "Persons" table (The * character selects
all the data in the table):
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br>";
}
mysqli_close($con);
?>
The example above stores the data returned by the mysqli_query() function in the $result
variable.
Next, we use the mysqli_fetch_array() function to return the first row from the recordset as an
array. Each call to mysqli_fetch_array() returns the next row in the recordset. The while loop
loops through all the records in the recordset. To print the value of each row, we use the PHP
$row variable ($row['FirstName'] and $row['LastName']).
The output of the code above will be:
Peter Griffin
Glenn Quagmire
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 286
SZABIST jstc Shaheed Benazirabad
Display the Result in an HTML Table
The following example selects the same data as the example above, but will display the data in
an HTML table:
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
The output of the code above will be:
Firstname Lastname
Glenn
Quagmire
Peter
Griffin
PHP MySQL The Where Clause
The WHERE clause is used to filter records.
The WHERE clause
The WHERE clause is used to extract only those records that fulfill a specified criterion.
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 287
SZABIST jstc Shaheed Benazirabad
Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator value
To learn more about SQL, please visit our SQL tutorial.
To get PHP to execute the statement above we must use the mysqli_query() function. This
function is used to send a query or command to a MySQL connection.
Example
The following example selects all rows from the "Persons" table where "FirstName='Peter'":
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons
WHERE FirstName='Peter'");
while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br>";
}
?>
The output of the code above will be:
Peter Griffin
PHP MySQL Order By Keyword
The ORDER BY keyword is used to sort the data in a recordset.
The ORDER BY Keyword
The ORDER BY keyword is used to sort the data in a recordset.
The ORDER BY keyword sort the records in ascending order by default.
If you want to sort the records in a descending order, you can use the DESC keyword.
Syntax
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC
To learn more about SQL, please visit our SQL tutorial.
Example
The following example selects all the data stored in the "Persons" table, and sorts the result by
the "Age" column:
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 288
SZABIST jstc Shaheed Benazirabad
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons ORDER BY age");
while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'];
echo " " . $row['LastName'];
echo " " . $row['Age'];
echo "<br>";
}
mysqli_close($con);
?>
The output of the code above will be:
Glenn Quagmire 33
Peter Griffin 35
PHP MySQL Update
The UPDATE statement is used to modify data in a table.
Update Data In a Database
The UPDATE statement is used to update existing records in a table.
Syntax
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which record or
records that should be updated. If you omit the WHERE clause, all records will be updated!
To learn more about SQL, please visit our SQL tutorial.
To get PHP to execute the statement above we must use the mysqli_query() function. This
function is used to send a query or command to a MySQL connection.
Example
Earlier in the tutorial we created a table named "Persons". Here is how it looks:
FirstName LastName Age
Peter
Griffin
35
Glenn
Quagmire 33
The following example updates some data in the "Persons" table:
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 289
SZABIST jstc Shaheed Benazirabad
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"UPDATE Persons SET Age=36
WHERE FirstName='Peter' AND LastName='Griffin'");
mysqli_close($con);
?>
After the update, the "Persons" table will look like this:
FirstName LastName Age
Peter
Griffin
36
Glenn
Quagmire 33
PHP MySQL Delete
The DELETE statement is used to delete records in a table.
Delete Data In a Database
The DELETE FROM statement is used to delete records from a database table.
Syntax
DELETE FROM table_name
WHERE some_column = some_value
Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which record or
records that should be deleted. If you omit the WHERE clause, all records will be deleted!
To learn more about SQL, please visit our SQL tutorial.
To get PHP to execute the statement above we must use the mysqli_query() function. This
function is used to send a query or command to a MySQL connection.
Example
Look at the following "Persons" table:
FirstName LastName Age
Peter
Griffin
35
Glenn
Quagmire 33
The following example deletes all the records in the "Persons" table where LastName='Griffin':
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"DELETE FROM Persons WHERE LastName='Griffin'");
mysqli_close($con);
?>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 290
SZABIST jstc Shaheed Benazirabad
After the deletion, the table will look like this:
FirstName LastName Age
Glenn
Quagmire 33
PHP Database ODBC
ODBC is an Application Programming Interface (API) that allows you to connect to a data
source (e.g. an MS Access database).
Create an ODBC Connection
With an ODBC connection, you can connect to any database, on any computer in your network,
as long as an ODBC connection is available.
Here is how to create an ODBC connection to a MS Access Database:
1.
2.
3.
4.
5.
6.
7.
8.
Open the Administrative Tools icon in your Control Panel.
Double-click on the Data Sources (ODBC) icon inside.
Choose the System DSN tab.
Click on Add in the System DSN tab.
Select the Microsoft Access Driver. Click Finish.
In the next screen, click Select to locate the database.
Give the database a Data Source Name (DSN).
Click OK.
Note that this configuration has to be done on the computer where your web site is located. If
you are running Internet Information Server (IIS) on your own computer, the instructions above
will work, but if your web site is located on a remote server, you have to have physical access to
that server, or ask your web host to to set up a DSN for you to use.
Connecting to an ODBC
The odbc_connect() function is used to connect to an ODBC data source. The function takes four
parameters: the data source name, username, password, and an optional cursor type.
The odbc_exec() function is used to execute an SQL statement.
Example
The following example creates a connection to a DSN called northwind, with no username and
no password. It then creates an SQL and executes it:
$conn=odbc_connect('northwind','','');
$sql="SELECT * FROM customers";
$rs=odbc_exec($conn,$sql);
Retrieving Records
The odbc_fetch_row() function is used to return records from the result-set. This function returns
true if it is able to return rows, otherwise false.
The function takes two parameters: the ODBC result identifier and an optional row number:
odbc_fetch_row($rs)
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 291
SZABIST jstc Shaheed Benazirabad
Retrieving Fields from a Record
The odbc_result() function is used to read fields from a record. This function takes two
parameters: the ODBC result identifier and a field number or name.
The code line below returns the value of the first field from the record:
$compname=odbc_result($rs,1);
The code line below returns the value of a field called "CompanyName":
$compname=odbc_result($rs,"CompanyName");
Closing an ODBC Connection
The odbc_close() function is used to close an ODBC connection.
odbc_close($conn);
An ODBC Example
The following example shows how to first create a database connection, then a result-set, and
then display the data in an HTML table.
<html>
<body>
<?php
$conn=odbc_connect('northwind','','');
if (!$conn)
{exit("Connection Failed: " . $conn);}
$sql="SELECT * FROM customers";
$rs=odbc_exec($conn,$sql);
if (!$rs)
{exit("Error in SQL");}
echo "<table><tr>";
echo "<th>Companyname</th>";
echo "<th>Contactname</th></tr>";
while (odbc_fetch_row($rs))
{
$compname=odbc_result($rs,"CompanyName");
$conname=odbc_result($rs,"ContactName");
echo "<tr><td>$compname</td>";
echo "<td>$conname</td></tr>";
}
odbc_close($conn);
echo "</table>";
?>
</body>
</html>
Course Facilitator: Waqas Ahmed Khilji
BS(CS),MS(IT)QUEST
Page 292
Download