Sei sulla pagina 1di 246

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA WWW.ATHENA.EDU.VN.

TEL : 1900 54 54 56 090 7879 477

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

Enjoy PHPing AND ATHENA!

TABLE OF CONTENTS
Chapter 1. Web Design Basic ..........................................................................................7 Web Design Toolbox..................................................................................................... 9 HTML Editor Dreamweaver CS3 .............................................................................. 16 HTML Basics................................................................................................................ 22 HTML Form ................................................................................................................. 23 CSS .............................................................................................................................. 27 Javascript .................................................................................................................... 28 Chapter 2. PHP Workspace ...........................................................................................31 PHP Introduction ........................................................................................................ 33 AppServ Installation ................................................................................................... 35 Using AppServ ............................................................................................................ 37 PHP IDE - PhpEd.......................................................................................................... 38 Using PHP Interactive ................................................................................................. 42 Chapter 3. PHP Basics ...................................................................................................45 PHP Syntax.................................................................................................................. 47 Data Types .................................................................................................................. 48 Variable & Constant ................................................................................................... 49 Operators ................................................................................................................... 50
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477 Control Structure ........................................................................................................ 51 Chapter 4. Function ......................................................................................................55 Introduction................................................................................................................ 57 Syntax ......................................................................................................................... 57 Parameter & Argument .............................................................................................. 58 Useful Functions ......................................................................................................... 61 Chapter 5. Array ...........................................................................................................63 Declaration ................................................................................................................. 65 Array Operation .......................................................................................................... 65 Iteration (Looping)...................................................................................................... 67 Sorting ........................................................................................................................ 68 More Functions .......................................................................................................... 70 Chapter 6. String Manipulation ....................................................................................73 Declaration ................................................................................................................. 75 Comparision ............................................................................................................... 75 Searching .................................................................................................................... 76 Replacement............................................................................................................... 76 Splitting....................................................................................................................... 77 Formatting .................................................................................................................. 78 Regular Expression RegEx ........................................................................................ 79 Chapter 7. HTTP Basic...................................................................................................83 HTTP Fundamentals.................................................................................................... 85 File Upload.................................................................................................................. 88 Cookie ......................................................................................................................... 90 Session ........................................................................................................................ 91 Chapter 8. OOP Object Oriented Programming .........................................................93 OOP Fundamentals..................................................................................................... 95 Properties ................................................................................................................... 96 Methods ..................................................................................................................... 97 Inheritance & Overriding .......................................................................................... 101 Chapter 9. File Handling ............................................................................................. 107 File Handle ................................................................................................................ 109 File Manipulation...................................................................................................... 110 Directory ................................................................................................................... 112 File & Directory Constants........................................................................................ 113
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477 Chapter 10. MySQL..................................................................................................... 115 DBMS Fundamentals ................................................................................................ 117 MySQL Fundamentals............................................................................................... 118 MySQL Basics ............................................................................................................ 122 Using phpMyAdmin .................................................................................................. 125 MySQL in PHP ........................................................................................................... 138 Chapter 11. Logging & Debugging .............................................................................. 141 Log Configuration ..................................................................................................... 143 PhpEd Debugger Installation .................................................................................... 143 Debugging................................................................................................................. 145 Chapter 12. OOP Advanced ........................................................................................ 149 Interface ................................................................................................................... 151 Abstract Class, Method ............................................................................................ 152 Final Class, Method .................................................................................................. 153 Lazy Loading ............................................................................................................. 154 Magic Methods......................................................................................................... 154 Chapter 13. MySQL Advanced .................................................................................... 159 Table Joining ............................................................................................................. 161 PHP Data Object (PDO) ............................................................................................. 164 Chapter 14. Software Engineering Basic ..................................................................... 167 Requirement Gathering............................................................................................ 169 Use-Case Diagram .................................................................................................... 171 Class Diagram ........................................................................................................... 177 Chapter 15. XML & Web Service ................................................................................. 181 XML Basics ................................................................................................................ 183 SimpleXML Class ....................................................................................................... 184 Web Services Basics.................................................................................................. 185 SOAP ......................................................................................................................... 186 JSON Overview ......................................................................................................... 189 Chapter 16. Security ................................................................................................... 191 Security Basics .......................................................................................................... 193 Database Security ..................................................................................................... 193 Website Security....................................................................................................... 194 Session Security ........................................................................................................ 199 File System Security.................................................................................................. 201
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477 Chapter 17. Advanced PHP Topics .............................................................................. 203 PHP.INI File Overview ............................................................................................... 205 Date & Time.............................................................................................................. 206 Email Sending ........................................................................................................... 208 Image Processing ...................................................................................................... 209 cURL library .............................................................................................................. 210 Smarty ...................................................................................................................... 211 Different between PHP5 & PHP4 ............................................................................. 212 Chapter 18. Design Pattern ........................................................................................ 215 Fundamentals ........................................................................................................... 217 Singleton Pattern ...................................................................................................... 217 Factory Pattern ......................................................................................................... 218 Strategy Pattern ....................................................................................................... 220 Model-View-Controller (MVC) Pattern .................................................................... 221 Chapter 19. E-Commerce Website .............................................................................. 225 E-Commerce Fundamentals ..................................................................................... 227 Website Optimization............................................................................................... 228 SEO Basics ................................................................................................................. 228 Website Analytic Google Analytic Setup ............................................................... 230 Chapter 20. Zend PHP 5 Certification ZCE (Zend Certified Engineer)........................ 243 Zend Certification Introduction ................................................................................ 245 Zend PHP 5 Certification Exam ................................................................................. 246 Further Reading.......................................................................................................... 249 UseFul Websites ......................................................................................................... 250

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

Chapter 1

Web Design Basics


Keywords: Web design, editor, tool, photo, form, html, tag, style, javascript. Subjects: 1.1. Web Design Toolbox 1.2. HTML Editor Dreamweaver CS3 1.3. HTML Basics 1.4. HTML Form 1.5. CSS 1.6. Javascript

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

1.1. Web Design Toolbox:


1.1.1. Image Manipulating: Photoshop, GIMP, Illustrator

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

1.1.2. Animation Creator: Photoshop, Flash, Flex, Maya, 3DS Max

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

10

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

11

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

1.1.3. HTML Editor: Dreamweaver, Notepad++

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

12

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

13

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

1.1.4. CSS Editor: Dreamweaver, Rapid CSS, Notepad++

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

14

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

15

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

1.1.5. Javascript Editor: Dreamweaver, 1st Javascript Editor, Notepad++

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

16

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

1.2. HTML Editor Dreamweaver CS3:


- Main Dreamweaver CS3 interface

- Auto-complete function

- Collapse selected script:


VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

17

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

- Property Inspector Panel:

- Create a Local Site:

Or:

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

18

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

Or:

- After creating site, the FILES panel will become:

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

19

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

- Open an Local Site:

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

20

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

- Manage Site Files: In the Files Panel, right click the root (top level) and select your function (New File, New Folder)

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

21

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

- Create new file

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

22

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

1.3. HTML Basics:


VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

23

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

1.3.1. HTML Structure:


<html> <head> <title>Four Square Cafe</title> </head> <body> Four Square Caf is located at the intersection of Melrose and Sunset Avenues in Los Angeles. We are a cafe with our own bakery, and also have a charcuterie for your favorite meats and cheeses. We offer breakfasts and made to order sandwiches. You can buy fresh, hot from the oven bread for your home twice a day, at 8 am and 5 am daily. In our Caf, we are also famous for fresh organic coffee and tea made with mountain water. Each cup is in its own single cone and paper filter and dripped right into your cup. We then start over for the next customer. Today's Specials ....................content deleted ..............................

</body> </html>

1.3.2. Popular HTML Tag:


- Break line: br - Heading: h1, h2, h3, h4, h5, h6. - Paragraph: p - Link: a - Image: img - Text formatting: b, i, strong - Tables: table, tr, th, td - List: ul, ol, dl, li - Form: form, input, textarea, select
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

24

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

- DIV, SPAN Tag: div, span

1.3.3. HTML Meta Tag:


<meta name="description" content="Free Web tutorials" /> <meta name="keywords" content="HTML,CSS,XML,JavaScript" /> <meta name="author" content="Duy Tuan" /> <meta http-equiv="refresh" content="4;URL=http://example.com/"> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />

1.4. HTML Form:


1.4.1. Using Dreamweaver to insert Form element:

1.4.2. Form Elements:


VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

25

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

1.4.2.1. Text Field:


<form method="post" action="mailto:youremail@email.com"> Name: <input type="text" size="10" maxlength="40" name="name"> <br /> Password: <input type="password" size="10" maxlength="10" name="password"> </form>

1.4.2.2. Button:
<form method="post" action="mailto:youremail@email.com"> Name: <input type="text" size="10" maxlength="40" name="name"> <br /> Password: <input type="password" size="10" maxlength="10" name="password"><br /> <input type="submit" value="Send"> </form>

1.4.2.3. Radio button:


<form method="post" action="mailto:youremail@email.com"> What kind of shirt are you wearing? <br /> Shade: <input type="radio" name="shade" value="dark">Dark <input type="radio" name="shade" value="light">Light <br /> Size: <input <input <input <input </form> type="radio" name="size" value="small">Small type="radio" name="size" value="medium">Medium type="radio" name="size" value="large">Large <br /> type="submit" value="Email Myself">

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

26

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

1.4.2.4. Check box:


<form method="post" action="mailto:youremail@email.com"> Select your favorite cartoon characters. <input type="checkbox" name="toon" value="Goofy">Goofy <input type="checkbox" name="toon" value="Donald">Donald <input type="checkbox" name="toon" value="Bugs">Bugs Bunny <input type="checkbox" name="toon" value="Scoob">Scooby Doo <input type="submit" value="Email Myself"> </form>

1.4.2.5. Dropdown list:


<form method="post" action="mailto:youremail@email.com"> College Degree? <select name="degree"> <option>Choose One</option> <option>Some High School</option> <option>High School Degree</option> <option>Some College</option> <option>Bachelor's Degree</option> <option>Doctorate</option> </select> <input type="submit" value="Email Yourself"> </form>

1.4.2.6. Selection form:


<form method="post" action="mailto:youremail@email.com"> Musical Taste <select multiple name="music" size="4"> <option value="emo" selected>Emo</option> <option value="metal/rock" >Metal/Rock</option> <option value="hiphop" >Hip Hop</option>
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

27

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


<option value="ska" >Ska</option> <option value="jazz" >Jazz</option> <option value="country" >Country</option> <option value="classical" >Classical</option> <option value="alternative" >Alternative</option> <option value="oldies" >Oldies</option> <option value="techno" >Techno</option> </select> <input type="submit" value="Email Yourself"> </form>

1.4.2.7. Upload form:


<input type="hidden" name="MAX_FILE_SIZE" value="100" /> <input name="file" type="file" />

1.4.2.8. Text Area:


<form method="post" action="mailto:youremail@email.com"> <textarea rows="5" cols="20" name="comments"> Enter Comments Here </textarea> <input type="submit" value="Email Yourself"> </form>

1.5. CSS:
1.5.1. CSS Selector:
- The selector name creates a direct relationship with the HTML tag you want to edit. - Many types of selector: type, class, id, child, universal
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

28

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

- Ex: <div id="container" class="bluebox largebox"></div>

1.5.2. CSS Syntax:


SELECTOR { PROPERTY: VALUE }

1.5.3. Embed CSS to HTML page:


- Internal CSS:
<style type="text/css"> p {color: white; } body {background-color: black; } </style>

- External CSS:
<link rel="stylesheet" type="text/css" href="test.css" />

- Inline CSS:
<p style="background: blue; color: white;"> Text </p>

1.6. Javascript:
1.6.1. Embed Javascript to HTML page:
- Internal:
<script type="text/javascript"> //script here </script>

- External:
<script type="text/javascript" src="file.js"></script>

- Inline:
<img src="button.gif" onclick="alert('test');" />
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

29

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

1.6.2. Javascript Basics:


1.6.2.1. Comments:
// this is a comment /* so is this */

1.6.2.2. Function:
function anExample(param1,param2) { alert(param1+param2); } <a href="javascript:void(0)" onClick="anExample("Ec","Lios") > Example </a>

1.6.2.3. IF Statement:
function anIfExample(param) { if (param==1) {alert("Hello Philip");} else if (param==2) {alert("Hello Terrance");} else {alert("Hello everyone");} } <a href="javascript:void(0)" onClick="anIfExample(1)" > Example 1</a> <br> <a href="javascript:void(0)" onClick="anIfExample(1)" > Example 2</a> <br> <a href="javascript:void(0)" onClick="anIfExample(2)" > Example 3</a>

1.6.2.4. SWITCH Statement:


function aSwitchExample(param) { switch(param) { case 1: alert("Hello John"); break; case 2: alert("Hello Peter"); case 3: alert("Hello Moose"); break;
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

30

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


default: alert("ahhh no moosi"); break; } } <a href="javascript:void(0)" onClick="aSwitchExample(1)" > Example 1</a> <br> <a href="javascript:void(0)" onClick="aSwitchExample(1)" > Example 2</a> <br> <a href="javascript:void(0)" onClick="aSwitchExample(2)" > Example 3</a>

1.6.2.5. WHILE Statement:


function aWhileExample(param) { counter=0; while(counter<param) { alert("round we go " + counter); counter++; // this adds one to the counter, could have typed // counter=counter+1; } } <a href="javascript:void(0)" onClick="aWhileExample(0)" > Example 1</a> <br> <a href="javascript:void(0)" onClick="aWhileExample(1)" > Example 2</a> <br> <a href="javascript:void(0)" onClick="aWhileExample(3)" > Example 3</a>

1.6.2.6. DO Statement:
function aDoExample(param) { counter=0; do { alert("round we go " + counter); counter++; // this adds one to the counter, could have typed // counter=counter+1; } while (counter<param) } <a href="javascript:void(0)" onClick="aDoExample(0)" > Example 1</a> <br> <a href="javascript:void(0)" onClick="aDoExample(1)" > Example 2</a> <br>
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

31

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


<a href="javascript:void(0)" onClick="aDoExample(3)" > Example 3</a>

1.6.2.7. FOR Statement:


function aForExample(param) { for(counter=0; counter<param; counter++) { alert("round we go " + counter); } } <a href="javascript:void(0)" onClick="aForExample(0)" > Example 1</a> <br> <a href="javascript:void(0)" onClick="aForExample(1)" > Example 2</a> <br> <a href="javascript:void(0)" onClick="aForExample(3)" > Example 3</a>

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

32

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

Chapter 2

PHP Workspace
Keywords: installation, IDE, server-side, scripting, interpreter, opensource, CLI, service, GUI, code navigator, DB Client, php interactive, request, response. Subjects: 2.1. PHP Introduction 2.2. AppServ Installation 2.3. Using AppServ 2.4. PHP IDE - PhpEd 2.5. Using PHP Interactive

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

33

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

2.1. PHP Introduction:


- How PHP Works:

- PHP stands for "PHP Hypertext Preprocessor" - PHP is a widely used open source. Stable version is PHP 5.3.0 (PHP6 beta) - Runs on Server -> Server-Side Scripting language - It's fast, free, easy to use, run on many Operating Systems(OS), secure, customizable, support community. - PHP supports many database (MySQL, Oracle, Sybase, PostgreSQL) - File extension: ".php", ".php3", ".php5" or ".phtml"

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

34

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

interacting via browser

Working via CLI (command-line interface)

Working via GUI(Graphical User Interface) Desktop Application

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

35

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

Working via web services (no need interface)

2.2. AppServ Installation:


- It will install Apache, PHP, MySQL in one window executive file (.exe) - Best solution for creating an environment to learning, developing and testing website. - Download AppServ at: http://www.appservnetwork.com/ - Install like a normal window application.

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

36

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

37

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

38

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

2.3. Using AppServ:


2.3.1. AppServ 2.10 Directory Structure:

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

39

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

2.3.2. Edit Server config using start menu:

2.3.3. Restart/ Stop / Start Apache / MySQL Services using start menu:

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

40

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

2.4. PHP IDE - PhpEd


- Main Software interface: + Menu Bar + Toolbar (File, navigator, HTML element, Debugger) + Code Explorer Panel (Left) + Source code editor (Center) + Code navigator Panel (Rignt)

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

41

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

- Some main features: + Autocomplete code:

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

42

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

+ Full screen support + Database Client

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

43

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

+ Support HTML, CSS, JS language

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

44

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

+ Debuging & Profiling tool

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

45

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

+ Collapse / Expand Selected code.

2.5. Using PHP Interactive


2.5.1. Introduction:
PHP Interactive is a simple PHP program that lets the user to write code in a text area (actually multiple text areas, with tabs to switch), and see the output of the code just pressing the update button. The scripts are persistent, and the program supports a raw and html output mode, in order to see the raw script output or to interpret it as html.

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

46

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

2.5.2. Installation:
- Download at: http://www.hping.org/phpinteractive/ - Unzip and copy to www folder and rename to "phpa".

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

47

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

- Access php interactive using URL: http://localhost/phpa/

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

48

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

49

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

Chapter 3

PHP Basics
Keywords: syntax, data type, variable, constant, type casting, operator, control structure, condition, loop, precidence, priority, expression. Subjects: 3.1. PHP Syntax 3.2. Data Types 3.3. Variable & Constant 3.4. Operators 3.5. Control Structure

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

50

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

3.1. PHP Syntax:


3.1.1. PHP Tags:
- PHP code can be inserted directly into a text file (.php). The interpreter will output any text outside the tags, and execute the code that is between the tags

3.1.2. PHP Source code:


- Every PHP script is made up of statements: function calls, variable assignments, data outputMost of the time, these statements must be terminatd with a semicolon(;). PHP is whitespace-intensitive.

3.1.3. Comments:
- PHP has many types of comment
//Single line comment #Single line comment /* Multi-line comment */ /** * API Documentation Example * * @param string $bar
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

51

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


*/ Function foo($bar){}

<?php

//this is the end tag "?>" of PHP ?>

3.1.4. Code Block: is a series of statements enclosed between two braces


{ //Some comments f(); //a function call }

3.2. Data Types:


3.2.1. Numeric Value:
- Integer numbers: . Decimal: normally used numbers. Ex: 10; -100 (invalid: 1 000) . Octal: begin with zero. Ex: 0666; 0777 . Hexadecimal: Begin with "0x" or "0X". Ex: 0x12; 0xAF; 0XFF - Floating-point numbers: have a fractional component. . Decimal: 0.12; 3.45 . Exponential: 4E6; 1e2

3.2.2. String: A series of single characters, such as Vietnam. 3.2.3. Boolean: A TRUE or FALSE value. 3.2.4. Array: can store any other data type. 3.2.5. Object: containers of both data and code. 3.2.6. Other types:
- NULL : indicates that a variable has no value. - resource: used to indicate external resources. Such as handing files, manipulating images
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

52

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

3.2.7.Type casting: can be done automatically or manually.


Ex: $a = 1.5; $b = (int)$a;
// $b will be assigned 1

3.3. Variable & Constant:


3.3.1. Variables:
- Can contain any type of data, such as strings, integers, objects, arraysPHP is loosely typed. - Identified by a dollar sign $ - Variable name must be using only letters (a-z, A-Z), numbers and the underscore character "_". - Variable name must start with a letter or an underscore - Case-sensitive. - Examples:
$var = "ok"; // Valid name $_var = "ok"; // Valid name $4var = "not ok"; //Invalid name, starts with a number

3.3.2. Variable Variables:


- Variable whose name is contained in another variable. Example:
$var = 'name'; $$var = 'I love php'; echo $name; // Displays 'I love php'

3.3.3. Constants:
- Can be accessed for any scope within a script - They can only contain numeric values, strings and booleans. - Naming like rule of variable name, but not start with dollar sign $
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

53

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

- It's usually defined constants using only upper-case names. - Examples:


define('EMAIL', 'myemail@example.com'); echo EMAIL; // Displays 'myemail@example.com' define('5CLASS, 'some value); // Invalid name

3.4. Operators:
3.4.1. Assignment Operator: assigning data to variables. Ex:
$a = 1; // Assign the integer 1 to $a

3.4.2. Arithmetic Operators: performing basic math functions. Ex:


$a = 5 + 6; $b = $a 1;

3.4.3. String Operators: joining two or more strings. Ex:


$myString = 'hello' . '-' . 'world'; // $myString will be string 'hello-world'

3.4.4. Comparison Operators: comparing two pieces of data. Ex:


$a = 10; echo $a == 10; // outputs 1

3.4.5. Logical Operators: performing logical operations on Boolean values.


$a = false; echo !$a; //outputs 1

3.4.6. Bitwise Operators: manipulating bits using boolean math. Ex:


$x = 1; echo $x << 1; // Outputs 2; echo $x << 2; // Outputs 4;

3.4.7. Error Control Operators: Suppressing errors. Prepending @ to an expression,


this operator causes PHP to ignore almost all error messages that occur that expression is being evaluated. Ex:
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

54

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


$x = @mysql_connect();

3.4.8. Execution Operators: executing system commands. Backtick operator (`) makes
it possible to execute a shell command and retrieve its output. Ex:
echo `dir c:\\`; // outputs info like open command window, type "dir c:\"

3.4.9. Incrementing/Decrementing Operators: incrementing and decrementing


numerical values. Ex:
$a = 1; echo $a++; echo ++$a; // Outputs 1, $a is now equal to 2 //Outputs 3, $a is now equal to 3 instanceof operator

3.4.10. Type Operators:

is used to determine whether a PHP variable is an instantiated object of a certain class. Ex:
echo $a instanceof MyClass;

3.4.11. Operator Precedence and Associativity:

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

55

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

3.5. Control Structure:


3.5.1. Conditional Structures:
3.5.1.1. IfElse Statement:
if (condition_1) { statement_1 } [elseif (condition_2) { statement_2 }] ... [elseif (condition_n_1) { statement_n_1 }] [else {

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

56

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


statement_n }]

3.5.1.2. Switch Statement:


switch (expression) { case label_1: statements_1 [break;] case label_2: statements_2 [break;] ... default: statements_n [break;] }

3.5.2. Loop Structures:


3.5.2.1. While Loop:
while (condition) { code to be executed; }

3.5.2.2. DoWhile Loop:


do { code to be exected; } while (condition);

3.5.2.3. For Loop:


for (initialization; condition; increment) {

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

57

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


code to be executed; }

3.5.2.4. Foreach Loop:


foreach (array as value) { code to be executed; } foreach (array as key => value) { code to be executed; }

3.5.3. Break & Continue Statements


3.5.3.1. break: used to immediately exit a loop. It takes an optional parameter, which allows you to exit from multiple nested loops. Ex:
$i = 0; $j = 0; while ($i < 10) { while ($j < 10) { if ($j == 5) {break 2;} // breaks out of two while loops $j++; } $i++; }

3.5.3.2. continue: want to skip over the remainder of an iteration and immediately skip over to the next. Like with break, you can provide it an integer parameter to specify the level of nesting to which the it applies. Ex:
for ($i=0; $i<=10; $i++) { if (i==3){continue;} echo "The number is ".$i; echo "<br />"; }

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

58

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

Chapter Exercise: A> Research typing casting on resource data type. B> What is the function used to check a declared variable? Is it always true in all situations?

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

59

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

Chapter 4

Functions
Keywords: function, parameter, argument, reference, value, global, static, scope, return, null, empty, language construct. Subjects: 4.1. Introduction 4.2. Syntax 4.3. Parameter & Argument 4.4. Useful Functions

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

60

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

4.1. Introduction:
- Function is the heart of PHP programming. - Encapsulate any piece of code in a way that it can be called again and again. - Classify between Language constructs and Functions.

Fastest things in PHP are the language constructs. They are highly optimized in the interpreter Dont require calling external libraries Dont call a function if there is a language construct. As an example, using a casting operator like (int) $total is much more efficient than using the function intval($foo) Function calling generate considerably amount of overhead. Using a language construct avoid isset() and unset() are both language constructs, even though they mostly act like functions. However calling them does not generate the function overhead. Common language construct: echo() empty() isset() unset() eval() exit() die() include() include_once() require() require_once() return

4.2. Syntax:
4.2.1. Create function: function name is case-intensitive.
function name() { //your code here }

Ex:
function hello() {
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

61

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


echo 'Hello World'; } hello(); // Displays "Hello World"; HeLLo(); // Displays "Hello World";

4.2.2. Return values:


- All functions in PHP return a value (event if you don't using return keyword, it will return NULL) - return keyword allows you to interrupt the execution of a function and exit it. - Ex:
function hello() { return 'Hello World'; } $str = hello(); // Assigns return value "Hello World" to $str echo hello(); // Displays "Hello World"

- Functions can be declared so that they return by reference, usually resource type. Ex:
function &query() { $result = mysql_query('SELECT email FROM users'); return $result; }

4.3. Parameter & Argument:


4.3.1. Different between Parameter and Argument:
- The term parameter refers to any declaration within the parentheses following the function name in a function declaration or definition; the term argument refers to any expression within the parentheses of a function call. - This example demonstrates the difference between a parameter and an argument:
// $var is a parameter function test($var) {
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

62

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


foo(5, 'a'); //5 and 'a' are arguments return 0; }

4.3.2. Passing by value: by default, function arguments are passed by value (so that if the
value of the argument within the function is changed, it does not get changed outside of the function). Ex:
function myFunc($str) { $str = 'bob'; echo $str; } $str = 'jack'; myFunc($str); // Displays "bob" echo $str; // Displays 'jack'

4.3.3. Passing by reference: to allow function to modify its arguments, they must be
passed by reference.Ex:
function myFunc(&$str) { $str = 'bob'; echo $str; } $str = 'jack'; myFunc($str); // Displays "bob" echo $str; // Displays 'bob

4.3.4. Default argument values: Set default value for an argument if it's not passed to
function. Ex:
function myFunc($str = 'mother') { echo $str; } $str = 'jack'; myFunc($str); // Displays "jack" myFunc(); // Displays "mother"

Question: What will output when running this script?


VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

63

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


function myFunc(&$str = 'mother') { // } $str = 'jack'; myFunc($str); echo $str;

4.3.5. Variable Scope: is the context within which it is defined. Most part all PHP
variables only have a single scope. View this script:
$a = 1; /* global scope */ function test() { echo $a; /* reference to local scope variable */ } test(); // Not display "1"

4.3.5.1. Using global scope variables: - Using global keyword. Ex:


$a = 1; $b = 2; function Sum() { global $a, $b; $b = $a + $b; } Sum(); echo $b;

// Display "3"

- Using $GLOBALS $a = 1; $b = 2;

variable. Ex:

function Sum() { $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b']; }

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

64

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


Sum(); echo $b;

// Display "3"

4.3.6. Static variables: A static variable exists only in a local function scope, but it does
not lose its value when program execution leaves this scope. - Ex1:
function test() { $a = 0; echo $a; $a++; } test(); // Display "0"; test(); // Display "0";

- Ex2:
function test() { static $a = 0; echo $a; $a++; } test(); // Display "0"; test(); // Display "1";

- Note: static variable must not be declared as the result of an expression, it will cause a parse error. Ex:
static $var = 1+2; // wrong (as it is an expression) static $var = sqrt(2); //wrong (as it is an expression)

4.4. Useful Functions:


4.4.1. func_num_args(): returns the number of arguments passed to the function. 4.4.2. func_get_arg(int $index): returns an item from the argument list. 4.4.3. func_get_args(): returns an array comprising a function's argument list.

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

65

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

4.4.4. function_exists(string $function_name): return TRUE if the given function


has been defined.

Chapter Exercise: A> Write a script to calculate and return the sum of all arguments (the number of argument is unknown) of a function. Example: $a = calculate(1,2,3,4,6,2); // $a = 18 B> List 3 global scope variables beside $GLOBALS

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

66

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

Chapter 5

Array
Keywords: array, element, index, key, value, associate, sort, shuffle, random, iteration, loop, stack, queue, pop, push, shift. Subjects: 5.1. Declaration 5.2. Array Operation 5.3. Iteration (Looping) 5.4. Sorting 5.5. More Functions

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

67

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

5.1. Declaration:
5.1.1. Declare an array variable:
$a $a $a $a = = = = array(10, 20, 30); array('a' => 10, 'b' => 20, 'key' => 30); array(5 => 1, 3=> 2, 1=>3, ); array();

5.1.2. Array operator []:


$a[] = 10; $a['key'] = 'value'; echo $a['key']; // Displays "value"

5.1.3. Multi-dimension Arrays: element of an array is an array too. Ex:


$a = array( array('red', 'green', 'blue'), array('small', 'medium', 'large') );

5.2. Array Operation:


5.2.1. Printing array:
- Using print_r() to print only one array. Ex:
$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z')); print_r($a); // Outputs: Array ( [a] => apple [b] => banana [c] => Array ( [0] => x [1] => y [2] => z ) )
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

68

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

- Using var_dump() can print more than one array.


$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z')); $b = array('x', 'y'); var_dump($a, $b); // Outputs: array(3) { ["a"]=> string(5) "apple" ["b"]=> string(6) "banana" ["c"]=> array(3) { [0]=> string(1) "x" [1]=> string(1) "y" [2]=> string(1) "z" } } array(2) { [0]=> string(1) "x" [1]=> string(1) "y" }

5.2.2. Counting array elements: using count() function. Ex:


$a = array(5,6,7); $element = count($a); // $element will be 3

5.2.3. Checking a variable is an array: using is_array() function. Ex:


$a = array(5,6,7); $result = is_array($a); var_dump($result); // Displays "bool(true)"

5.2.4. Checking an element exists: using isset() function.


VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

69

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

- Note: if element value equal NULL, isset() still return FALSE. Ex:
$a = array('a' => NULL, 'b' => 2); $test = isset($a['a']); // $test will be assigned FALSE

In this case, using array_key_exists() function. Ex:


$a = array('a' => NULL, 'b' => 2); $test = array_key_exists('a', $a);

// $test will be TRUE

5.2.5. Deleting an element: using unset() function. Ex:


$a = array('a', 'b', 'c'); unset($a[1]); print_r($a); // Outputs: Array ( [0] => a [2] => c )

5.3. Iteration (Looping):


5.3.1. Array Pointer: using key(),
function. Ex:
$a = array('a', 'b', 'c'); while(key($a) !== null) { echo key($a) . ': ' . current($a) . PHP_EOL; // Move pointer to next element next($a); } current(), next(), prev(), reset(), end()

// 0: 1: 2:

Outputs: a b c

It's not a common way for iteration array.


VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

70

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

5.3.2. Using for() and foreach() function:


- Ex 1:
$a = array(3, 5, 7); $iCount = count($a); for($i = 0; $i < $iCount; $i++) { echo $a[$i] . '.'; } // Displays "3, 5, 7, "

- Ex 2:
$a = array('blue' => 'small', 'green' => 'large'); foreach($a as $key => $value) { echo $key. ' : ' . $value . ','; } //Displays "blue : small, green : large, "

5.4. Sorting:
Function name
sort() rsort() asort() arsort() natsort() natcasesort() ksort() krsort()

Sorts by

Maintains key association

Order of sort

Related functions

Value Value Value Value Value Value Key Key

No No Yes Yes Yes Yes Yes Yes

Low to high High to low Low to high High to low Natural Natural, case insensitive Low to high High to low

rsort() sort() arsort() asort() natcasesort() natsort() asort() ksort()

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

71

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


usort() uasort() uksort() shuffle() array_multisort()

Value Value Key Value Value

No Yes Yes No Associative yes, numeric no

User defined User defined User defined Random First array or sort options

uasort() uksort() uasort() array_rand() array_walk()

Example of using sort() function:


$fruits = array( 'a' => 'lemon', 'c' => 'orange', 'd' => 'banana', 'b' => 'apple');

sort($fruits); foreach ($fruits as $key => $val) { echo "fruits[" . $key . "] = " . $val . "\n"; } // Outputs: fruits[0] = fruits[1] = fruits[2] = fruits[3] =

apple banana lemon orange

Example of using asort():


$fruits = array( 'a' => 'lemon', 'c' => 'orange', 'd' => 'banana', 'b' => 'apple'); asort($fruits); foreach ($fruits as $key => $val) { echo "fruits[" . $key . "] = " . $val . "\n"; } // Outputs: fruits[b] = fruits[d] = fruits[a] = fruits[c] =

apple banana lemon orange


PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

VO DUY TUAN

72

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

Example of using ksort():


$fruits = array( 'a' => 'lemon', 'c' => 'orange', 'd' => 'banana', 'b' => 'apple'); ksort($fruits); foreach ($fruits as $key => $val) { echo "fruits[" . $key . "] = " . $val . "\n"; } // Outputs: fruits[a] = fruits[b] = fruits[c] = fruits[d] =

lemon apple orange banana

5.5. More Functions:


5.5.1. list() : assign variables as if they were an array. 5.5.2. array_merge(): merge one or more arrays. 5.5.3. array_slice(): extract a slice of the array. 5.5.4. array_diff_*() group: computes the difference of arrays 5.5.5. array_intersect_*() group: computes the intersection of arrays. 5.5.6. array_push(),
array_pop(), array_shift(), array_unshift(): insert/

remove an element from array using queue and stack operation. STACK OPERATION
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

73

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

QUEUE OPERATION

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

74

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

Chapter Exercise: A> Can we use arithmetic operator (+, -, *, /) between 2 arrays. If yes, what is the result? B> Simulate the game "nh bi Ti n ln" of Vietnamese, there are 4 people in game, each has 13 cards. Using functions from beginning to this chapter to write the action of shuffle cards and give each one 13 random cards. ***** difficult : write the function to find the number of "3 i thng" in 13 cards of each person.

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

75

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

Chapter 6

String Manipulation
Keywords: string, haystack, needle, text, character, case-sensitive, caseinsensitive, HEREDOC, escape character, compare, search, extract, replace, position, format, regular expression, expression, match, pattern, delimiter, PCRE, overhead. Subjects: 6.1. Declaration 6.2. Comparision 6.3. Searching 6.4. Replacement 6.5. Splitting 6.6. Formatting
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

76

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

6.7. Regular Expression RegEx

6.1. Declaration:
6.1.1. Normal Assignment:
1. 2. 3. 4. 5. 6. 7. 8. 9. $a = "Using double quote"; $b = 'Using single quote'; $c = "control characters in \n double quote only"; $c2 = "\052"; $c3 = "\x2a"; $num = 1; $d = "$num is parsed"; // $d equals "1 is parsed" $e = "$numx is not parsed"; // $e equals " is not parsed" $f = "{$num}x is parsed"; // $f equals "1x is parsed"

6.1.2. HEREDOC:
$who = "World"; $str = <<<TEXT Hello $who TEXT; // Displays "Hello World"

6.2. Comparision:
6.2.1. Comparison Operator : using operators
== , !=, ===, !==

. Ex:

$a = '123abc'; $b = '123Abc'; $c = 123; $test1 = ($a == $b); // $test1 equals FALSE $test2 = ($a == $c); // $test2 equals TRUE $test3 = ($a === $c); // $test3 equals FALSE

6.2.2. Using strcmp() : compare two string, it's case-sensitive. Using strcasecmp() to
compare two string, it's case-insensitive. Ex:
$str = 'Hello world';
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

77

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


$test1 = strcmp($str, 'hello world'); // $test1 equals -1 $test2 = strcasecmp($str, 'hello world'); // $test2 equals 0 $test3 = strcmp('a', 'A'); // $test3 equals 1;

6.3. Searching:
6.3.1. strpos(): Find position of first occurrence of a string. It's case-sensitive.
- Ex:
$pos = strpos('mystring', 'str'); // $pos equals 2 $pos = strpos('mystring', 'hi'); // $pos === FALSE

6.3.2. strrpos(): Find position of last occurrence of a char in a string. It's case-sensitive.
Ex:
$pos = strrpos('mystringmy', 'my'); // $pos equals 8

6.3.3. strstr(): Find first occurrence of a string. It's case-sensitive.


Ex:
$pos = strstr('mystring', 'str'); // $pos equals "string" $pos = strstr('mystring', 'hi'); // $pos === FALSE

6.3.4. stripos() is the case-insensitive version of strpos(). 6.3.5. strripos() is the case-insensitive version of strrpos(). 6.3.6. stristr() is the case-insensitive version of strstr().

6.4. Replacement:

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

78

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

6.4.1. str_replace(): replace all occurrences of the search string with the replacement
string, it's case-sensitive. str_ireplace() is the case-insensitive of str_replace(). Ex:
echo str_replace('abc', 'z', 'abcdef' ); echo str_replace('ABC', 'z', 'abcdef'); echo str_ireplace('ABC', 'z', 'abcdef'); //Displays "zdef" // Displays "abcdef" // Display "zdef"

6.4.2. substr_replace(): replace text within a portion of a string.


Ex:
echo substr_replace('012345abcdef', 'zzz', 5); // Displays "01234zzz"

6.5. Splitting:
6.5.1. Retun part of string: using
Ex:
echo substr('abcdef', 1); // echo substr('abcdef', 1, 3); echo substr('abcdef', 0, 4); echo substr('abcdef', 0, 8); echo substr('abcdef', -1, 1); bcdef // bcd // abcd // abcdef // f substr().

6.5.2. Split string to array: using explode() and split() function.


Ex:
$s1 = 'a,b,c,d'; $a1 = explode(',', $s1); print_r($a1); $s2 = '1,2,3,4'; $a2 = split(',', $s2, 2); print_r($a2); //Displays: Array (
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

79

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


[0] [1] [2] [3] => => => => a b c d

) Array ( [0] => 1 [1] => 2,3,4 )

Question: what displays when running this script:


echo count(split('/', '///'));

6.5.3. Join array elements to a string: using implode() and join() function.
Ex:
$array = array('lastname', 'email', 'phone'); $comma_separated = implode(",", $array); echo $comma_separated; // displays "lastname,email,phone"

6.6. Formatting:
6.6.1. Number formatting: using number_format() to formatting numerical value.
Ex:
echo number_format("100000.123", 2, '.', ','); // Displays "100,000.12"

6.6.2. Output formatting: using printf() to print a string in a specified format.


Ex:

- %s, %d, %f: Specifiers.


VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

80

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

Specifier
b c d u f o x X

Format The argument is treated as an integer and is presented as an integer in binary form. The argument is treated as an integer and is presented as the ASCII character for that value. The argument is treated as an integer and presented as a signed integer. The argument is treated as an integer and presented as an unsigned integer. The argument is treated as a floating-point number and presented as a floating-point number. The argument is treated as an integer and presented as its octal representation. The argument is treated as an integer and presented as a hexadecimal number (using lowercase letters). The argument is treated as an integer and presented as a hexadecimal number (using uppercase letters).

- Formatting functions: Function


printf sprintf vprintf vsprintf fprintf

Arguments Format, args Format, args Format, array of args Format, array of args Stream resource, format, args

Result Writes output Return result Writes output Returns result Writes output to stream

6.7. Regular Expression RegEx:


- The most powerful tools in the string manipulation toolbox are regular expressions

6.7.1. Introduction:

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

81

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

6.7.2. Character Class: allow a pattern to match multiple characters simultaneously


Metacharacter
\d \D \w \W \s \S . ^ $

Characters Matched Digits 0-9 Anything not a digit Any alphanumeric character or an underscore (_) Anything not an alphanumeric character or an underscore Any whitespace (spaces, tabs, newlines) Any non-whitespace character Any character except for a newline Match the start of the string Match the end of the string

Ex 1: the expression /ab[cd]e/ matches abce and abde. Ex 2: the expression /ab[c-e\d]/ will match abc, abd, abe and any combination of ab followed by a digit.

6.7.3. Quantifiers: allows you to specify the number of times a particular character or
metacharacter can appear in a matched string. 4 types of quantifiers:
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

82

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


* + ? {n,m}

The character can appear zero or more times The character can appear one or more times The character can appear zero or one times The character can appear at least n times, and no more than m. Either parameter can be omitted to indicated a minimum limit with no maximum, or a maximum limit without a minimum, but not both

Ex: the expression /ab?c/ matches both ac and abc, while ab{1,3}c matches abc, abbc, abbbc.

6.7.4. Match & Extract strings: preg_match() and preg_match_all(). Ex:


$str = 'foobar: 2008 - hello: 2009'; preg_match('/(?<name>\w+): (?<digit>\d+)/', $str, $matches); print_r($matches); //Displays: Array ( [0] => foobar: 2008 [name] => foobar [1] => foobar [digit] => 2008 [2] => 2008 )

Ex 2:
$str = 'foobar: 2008 - hello: 2009'; preg_match_all('/(\w+): (\d+)/', $str, $matches); print_r($matches); //Displays: Array ( [0] => Array ( [0] => foobar: 2008 [1] => hello: 2009 ) [1] => Array ( [0] => foobar [1] => hello ) [2] => Array
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

83

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


( [0] => 2008 [1] => 2009 ) )

6.7.5. Replace string with Regex: preg_replace().


Ex:
$string = 'April 15, 2003'; $pattern = '/(\w+) (\d+), (\d+)/i'; $replacement = '${1}x,$3'; echo preg_replace($pattern, $replacement, $string); // Displays "Aprilx,2003"

6.7.6. Split string by a regular expression: using preg_split().


Ex:
$keywords = preg_split("/[\d\s,]+/", "hyper1 lang2, prog"); print_r($keywords); // Displays Array ( [0] => hyper [1] => lang [2] => prog )

Chapter Exercise: A> Write the function to check the file is the image or not. Input: filename, return TRUE/FALSE. Valid image type: jpg, jpeg, png, gif, bmp. B> Write the regular expression pattern to match an URI of an image. Example: http://www.example.com/photo/some-directory/imagename.gif C> Write the regular expression pattern to match an email address.

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

84

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

Chapter 7

HTTP Basic
Keywords: http, html, header, form, request, response, get, post, cookie, session, authentication, domain, timeout, expire, redirect, caching, file upload, apache, rewrite rule, htaccess. Subjects: 7.1. HTTP Fundamentals 7.2. File Upload 7.3. Cookie 7.4. Session

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

85

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

7.1. HTTP Fundamentals:


7.1.1. How HTTP works: (RFC 2616)

7.1.2. GET Method:


- Change URL after submit form - using global variable $_GET or $_REQUEST to access data in form. Ex:
$firstName = $_GET['FirstName']; $salary = $_GET['Salary']; $contractor = $_GET['Contractor'];

7.1.3. POST Method:


- Not change URL after submit form - using global variable $_POST or $_REQUEST to access data in form.
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

86

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

Ex:
$firstName = $_POST['FirstName']; $salary = $_POST['Salary']; $contractor = $_POST['Contractor'];

7.1.4. HTTP Request:


- Sample of request:

-------------------------------------------------------------------------------------------------------GET Header Request:


GET /dumprequest HTTP/1.1 Host: djce.org.uk User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.12) Gecko/2009070611 Firefox/3.0.12 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive Referer: http://www.google.com.vn/search?hl=vi&client=firefox-a&rls=org.mozilla:enUS:official&um=1&q=http%20request&ndsp=21&ie=UTF-8&sa=N&tab=iw

POST Header Request:


VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

87

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

POST /path/script.cgi HTTP/1.0 From: frog@jmarshall.com User-Agent: HTTPTool/1.0 Content-Type: application/x-www-form-urlencoded Content-Length: 32 home=Mosby&favorite+flavor=flies

7.1.5. HTTP Response:

HTTP/1.1 200 OK Date: Sun, 08 Oct 2000 18:46:12 GMT Server: Apache/1.3.6 (Unix) Keep-Alive: timeout=5, max=120 Connection: Keep-Alive Content-Type: text/html <html>...

Some HTTP 1.1 status code: Status Reason Code Phrase 200 OK 201 301 Created Moved Permanently

Description Generic successful request message response. This is the code sent most often when a request is filled normally. The request was successful and resulted in a resource being created. This would be a typical response to a PUT method. The resource requested has been moved to a new URL permanently. Any future requests for this resource should use the new URL.

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

88

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

302 304

Found Not Modified

400

Bad request

401

Unauthorized

404

Not Found

500 502

Internal Server Error Bad Gateway

503

Service Unavailable Gateway Timeout

504

This is the proper method of handling situations where a file on a server is renamed or moved to a new directory. Most people don't bother setting this up, which is why URLs break so often, resulting in 404 errors as discussed below. The resource requested is temporarily using a different URL. The client should continue to use the original URL. The client sent a conditional GET request, but the resource has not been modified since the specified date/time, so the server has not sent it. Server says, huh? Generic response when the request cannot be understood or carried out due to a problem on the client's end. The client is not authorized to access the resource. Often returned if an attempt is made to access a resource protected by a password or some other means without the appropriate credentials. The most common HTTP error message, returned when the server cannot locate the requested resource. Usually occurs due to either the server having moved/removed the resource, or the client giving an invalid URL (misspellings being the most common cause.) Generic error message indicating that the request could not be fulfilled due to a server problem. The server, while acting as a gateway or proxy, received an invalid response from another server it tried to access on the client's behalf. The server is temporarily unable to fulfill the request for internal reasons. This is often returned when a server is overloaded or down for maintenance. The server, while acting as a gateway or proxy, timed out while waiting for a response from another server it tried to access on the client's behalf.

7.1.6. Header:
- Using function header() to send a HTTP header. Ex:
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

89

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


header('Location: http://www.php.net/'); header("HTTP/1.0 404 Not Found");

7.2. File Upload:


7.2.1. Prepare form:
<form method="post" enctype="multipart/form-data" action="upload.php"> File to upload: <input type="file" name="myfile"><BR> <input type="submit" value="Submit"> </FORM>

7.2.2. Upload a file:


- Get uploaded file's data using $_FILES. Ex:
$name = $_FILES[myfile]['name']; $type = $_FILES[myfile][type]; $size = $_FILES[myfile][size]; $tmpname = $_FILES[myfile][tmp_name]; $error = $_FILES[myfile][error]; $uploadPath = 'uploads/photos/'.$name; // Begin to upload fileif (move_uploaded_file($tmpname, $uploadPath)) { echo 'Upload successfully!'; }

7.2.3. Upload multiple files:


- HTML form:
File to upload: <input type="file" name="myfile[]"><BR> File to upload: <input type="file" name="myfile[]"><BR>

- PHP script:
$nameA = $_FILES[myfile]['name'][0]; $tmpnameA = $_FILES[myfile][tmp_name][0];
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

90

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


$uploadPathA = 'uploads/photos/'.$nameA; $nameB = $_FILES[myfile]['name'][1]; $tmpnameA = $_FILES[myfile][tmp_name][1]; $uploadPathB = 'uploads/photos/'.$nameB; // Begin to upload files

7.3. Cookie:
7.3.1. How cookies work:

7.3.2. Create cookies: using setcookie() function. Ex:


VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

91

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


$value = 'something from somewhere'; setcookie("test", $value); setcookie("test", $value, time()+3600); /* expire in 1 hour */ setcookie("test", $value, time()+3600, "/~test/", ".example.com", 1);

7.3.3. Get cookies data: using global variables $_COOKIES or $_REQUEST.


Ex:
echo $_COOKIE["test"];

7.3.4. Delete a cookie:


setcookie ("test", "", time() - 3600);

7.4. Session:
7.4.1. How sessions work:

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

92

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

7.4.2. Create sessions: If you are using cookie-based sessions, you must call
session_start() before anything is outputted to the browser.
session_start(); $_SESSION['username'] = 'testing';

7.4.3. Session ID processing:


7.4.3.1. Get the current Session ID: - session_id() : used to get or set the session id for the current session. Ex:
$currentSessID = session_id();

7.4.3.2. Re-generate Session ID: - session_regenerate_id() : Update the current session id with a newly generated one. 7.4.3.3. Example:
session_start(); $old_sessionid = session_id(); session_regenerate_id(); $new_sessionid = session_id(); echo "Old Session: $old_sessionid<br />"; echo "New Session: $new_sessionid<br />";

7.4.4. Delete a session:


session_destroy();

Chapter Exercise:
A> Design a webpage to display form for user login. The username is an email, and the password must be at least 6 characters. Password must be alphanumerical characters (a-z, A-Z, 0-9). If login success, displays the name of the user (extract from email) and the number of page which is refreshed by user. Ex: enter email: rasmus@myemail.com, password: abc3456ad5, website will display:
Hello rasmus !
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

93

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


You refreshed 3 times.

B> Write photo album function for the user (after login) from question A. a. b. c. d. e. Upload images (png,gif,jpeg) 5 images in a submit form Store images in directory "uploads/images/". Max file size: 300KB File name: USERNAME_imagename If image existed, append the letter "i" after name part. Ex: rasmus_image1.gif exists, will be renamed to rasmus_image1i.gif

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

94

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

Chapter 8

OOP
Object-Oriented Programming
Keywords: object, class, instance, inheritance, encapsulation, access, constructor, destructor, property, method, visibility, parent, self, this, override, public, protected, private.

Subjects: 8.1. OOP Fundamentals 8.2. Properties 8.3. Methods 8.4. Inheritance & Overriding

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

95

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

8.1. OOP Fundamentals:


8.1.1. What is OOP ?

- As we mentioned previously, the basic element of OOP is the class. A class contains the definition of data elements (or properties) and functions (or methods) that share some common trait and can be encapsulated in a single structure.

8.1.2. Declaring Class: Class name is case-insensitive


class ClassName { // Some Properties // Some Methods }

8.1.3. Instantiating an Object: To create an instance of a class, a new object must be


created and assigned to a variable. An object will always be assigned when creating a new object unless the object has a constructor defined that throws an exception on error. Classes should be defined before instantiation. - In the class context, it is possible to create a new object by new self and new parent.
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

96

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

Ex:
$myClassInstance = new MyClass(); $copyInstance = $myClassInstance;

8.2. Properties:
8.2.1. Declaration & Visibility: The default value must be a constant expression, not
(for example) a variable, a class member or a function call. Ex:
class foo { //valid declaration public $name; protected $age; private $type; public $var1 = "Test"; // String public $var2 = 1.23; // Numeric value public $var3 = array(1, 2, 3); // Array //invalid declaration $var4 = TRUE; public $var1 = 'hello '.'world'; public $var2 = <<<EOD hello world EOD; public $var3 = 1+2; public $var4 = self::myStaticMethod(); public $var5 = $myVar; }

8.2.2. Constant:
Ex:
class foo { const BAR = 'Hello World'; } echo foo::BAR;

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

97

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

8.3. Methods:
8.3.1. Declaration:
- A class method/functions is the behavior/functionality of a class i.e. they provide the necessary code for the class in which it is defined. - A class method is exactly similar to PHP functions, its just that class functions are declared inside classes and accessed using the -> (arrow operator / dereferencing operator). - Methods can also be declared as either public, protected or private. - Example:
class MyClass { public function myFunction() { echo 'You called MyClass::myFunction'; //call the private function $this->myPrivate(); } private function myPrivate() { echo "\nThis is a private function."; } } $obj = new MyClass(); $obj->myFunction(); //Displays: You called MyClass::myFunction This is a private function.

- A pseudo-variable, $this is available when a method is called from within an object context. Ex:
class Shirt { public $color; private function getColor()
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

98

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


{ echo $this->color; } public function say() { $this->getColor(); } } $redShirt = new Shirt(); $redShirt->color = 'Red'; $blueShirt = new Shirt(); $blueShirt->color = 'Blue'; $redShirt->say(); // Displays 'Red' $blueShirt->say(); // Displays 'Blue'

8.3.2. Constructor: Using __construct() method.


- A constructor is a special function of a class that is automatically executed whenever an object of a class gets instantiated. - It is needed as it provides an opportunity for doing necessary setup operations like initializing class variables, opening database connections or socket connections, etc. In simple terms, it is needed to setup the object before it can be used. - In PHP5 a constructor is defined by implementing the __construct() method. This naming style has been introduced in PHP5. In PHP4, the name of the constructor was the same name as that of the class. So, for example if you had a class Customer, you would have to implement a function Customer(). - PHP5 to be backward complaint also supports the PHP4 rule. When an object is created, PHP5 searches for __construct() first. If __construct() is not defined it then searches for a method with the same that of the class. However, if you define both; PHP5 will first search for __construct() method and execute it if available, otherwise it will execute the same class name function. - Unlike other programming languages where overloaded argument constructors is possible, in PHP5 you cannot overload constructors. - Example:
class Shirt
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

99

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


{ public $color; function __construct($myColor) { $this->color = $myColor; } private function getColor() { echo $this->color; } public function say() { $this->getColor(); } } $redShirt = new Shirt('Red'); $blueShirt = new Shirt('Blue'); $redShirt->say(); // Displays 'Red' $blueShirt->say(); // Displays 'Blue'

8.3.3. Destructor: Using __destruct() method.


- A destructor is a special function of a class that is automatically executed whenever an object of a
class is destroyed:

1. it goes out of scope, 2. when you specifically set it to null, 3. when you unset it or when the program execution is over.
- A PHP5 destructor is defined by implementing the __destruct() method. In PHP4 however, the concept of a destructor did not exist. - A destructor cannot take any arguments. - Example:
class Shirt { public $color;
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

100

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


function __construct($myColor) { $this->color = $myColor; } function __destruct() { echo $this->color . ' is dead'; } private function getColor() { echo $this->color; } public function say() { $this->getColor(); } } $redShirt = new Shirt('Red'); $blueShirt = new Shirt('Blue'); $redShirt->say(); // Displays 'Red' $blueShirt->say(); // Displays 'Blue' $redShirt = null; unset($blueShirt); // Displays 'Red is dead'; // Displays 'Blue is dead';

8.3.4. Static Property & Method:


- Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static can not be accessed with an instantiated class object (though a static method can). - Because static methods are callable without an instance of the object created, the pseudo variable $this is not available inside the method declared as static. - Static properties cannot be accessed through the object using the arrow operator ->. - Example:
class MyClass
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

101

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


{ static $var1 = 'hello'; public static function myFunction() { echo 'Hello World'; } } $obj = new MyClass(); $obj->myFunction(); // Displays "Hello World" echo $obj->var1; // Invalid, it shows a notice MyClass::myFunction(); // Displays "Hello World" echo MyClass::$var1; // Displays "hello"

8.4. Inheritance & Overriding:


8.4.1. Inheritance:
- Inheritance is the mechanism of deriving a new class from an existing class. It allows a subclass / child class to share/inherit the properties and methods of a base-class or parent class. - To inherit in PHP5, you should use the keyword extends in the class definition. In PHP5 only single inheritance is allowed. Ex:
class Person { private $name; private $address; public function getName() { return $this->name; } } class Customer extends Person { private $customer_id; private $record_date;

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

102

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


public getCustomerId() { return $this->customer_id; } public getCustomerName() { return $this->getName();// getName() is in Person } }

8.4.2. Access specifiers in Inheritance:


+ Public: A public access specifier allows the properties and methods to be accessed from anywhere in the script. Please note that if you declare any properties or method without a access specifier it is considered as public. Ex:
Class Person { public $age = 20; } Class Customer extends Person { } $myCustomer = new Customer(); echo $myCustomer->age;

+ Private: A private access specifier is used to hide properties and methods. A method or property declared as private can only be accessed by the class itself and neither the outside program nor the derived class can have access to it. The reason why properties are declared private is to avoid the outside programs to either accidently modify the values without necessary validation. Ex:
class Customer { private $name; public $age; public function __construct($name, $age) { $this->name = $name; $this->age = $age; } } $c = new Customer("Sunil","28"); echo "Name : " . $c->name; // displays an error

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

103

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

+ Protected: A protected access specifier allows the derived class to access the properties and methods of the base class. Ex:
class Person { protected $name; } class Customer extends Person { function setName($name) { //this works as $name is protected in Person $this->name = $name; } } $c1 = new Customer(); $c1->setName("Sunil"); $c1->name = "Sunil"; // Displays an error as $name is protected and not public

8.4.3. Overriding:
- Method overriding is when the method of base class is re-defined with the same name, function signature and access specifier (either public or protected) of the derived class. The reason to override method is to provide additional functionality over and above what has been defined in the base class. Ex:
class Bird { public function fly() { echo "Fly method of Bird Class called"; } } class Eagle extends Bird { public function fly() { echo "Fly method of the Eagle Class called"; } } class Chicken extends Bird {
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

104

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


public function fly() { echo "Fly method of the Chicken Class called"; } } $e = new Eagle(); $c = new Chicken(); $e->fly(); echo "\n"; $c->fly(); // Displays "Fly method of the Eagle Class called" // Displays "Fly method of the Chicken Class called"

- Examples:

class Car { protected $color; protected $hoursepower; protected $seatCount; protected $type; public $size = 'Small'; function __construct() {
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

105

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


$this->type = 'Car'; } public function run() { echo $this->type . ' is running !'; } } class RaceCar extends Car { private $nitro; function __construct() { $this->type = 'Race Car'; $this->size = 'Medium'; } public function run() { Echo $this->type . ' is racing !'; } } class Truck extends Car { private $trailer; protected $type = 'Truck'; } $car = new Car(); $car->run(); // Displays "Car is running!" $racecar = new RaceCar(); $racecar->run(); // Displays "Race Car is racing!" $truck = new Truck(); $truck->run(); // Display ?

8.4.4. Invoke Parent Methods:


- When you override a method of the base class, its functionality is completely hidden unless it has been explicitly invoked from the child class. To invoke a parent class method you should use the keyword parent followed by the scope resolution operator followed by the name of the method as mentioned below. - Syntax:
parent::method_name();
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

106

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

- Example:
class Person { public function showData() { echo "This is Person's showData()\n"; } } class Customer extends Person { public function showData() { parent::showData(); echo "This is Customer's showData()\n"; } } $c = new Customer(); $c->showData(); // Displays This is Persons showData() This is Customers showData()

8.4.5. Invoke Parent Constructor & Destructor:


- We can get the parent PHP5 constructor and PHP5 Destructor to be invoked in the same way as invoking the parent method - Example:
class Person { public function __construct() { echo "This is Person's __construct()\n"; } public function __destruct() { echo "This is Person's __destruct()\n"; } } class Customer extends Person { public function __construct()
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

107

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


{ parent::__construct(); echo "This is Customer's __construct()\n"; } public function __destruct() { parent::__destruct(); echo "This is Customer's __destruct()\n"; } } $c = new Customer(); // Displays This is Persons __construct() This is Customers __construct() This is Persons __destruct() This is Customers __destruct()

Chapter Exercise:
Website: Design a webpage to display form for user login. The username is an email, and the password must be at least 6 characters. Password must be alphanumerical characters (a-z, A-Z, 0-9). If login success, displays the name of the user (extract from email) and the number of page which is refreshed by user. Ex: enter email: rasmus@myemail.com, password: abc3456ad5, website will display: Hello rasmus ! You refreshed 3 times. A> Write photo album function for the user (after login) a. b. c. d. e. Upload images (png,gif,jpeg) 5 images in a submit form Store images in directory "uploads/images/". Max file size: 300KB File name: USERNAME_imagename If image existed, append the letter "i" after name part. Ex: rasmus_image1.gif exists, will be renamed to rasmus_image1i.gif

B> Find all classes in application. Ex: User C> Write the website using Class.

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

108

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

Chapter 9

File Handling
Keywords: file, directory, filename, extension, handle, stream, read, write, permission, file wrapper, protocol, path, append, buffer, socket, open, close, timeout. Subjects: 9.1. File Handle 9.2. File Manipulation 9.3. Directory 9.4. File & Directory Constants

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

109

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

9.1. File Handle:


9.1.1. Create file handle:
- The fopen() function is used to open files in PHP. - The first parameter of this function contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened:
$fileHandle = fopen('counter.txt', 'w+');

9.1.2. File open mode:


Mode r r+ w w+ Description Open for reading only; place the file pointer at the beginning of the file. Open for reading and writing; place the file pointer at the beginning of the file. Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it. Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it. Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it. Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it. Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. Create and open for reading and writing; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it.

a a+ x

x+

9.1.3. Close file handle:


- In PHP it is not system critical to close all your files after using them because the server will close all files after the PHP code finishes execution. However the programmer is still free to make mistakes (i.e. editing a file that you accidentally forgot to close). You should close all files after you have finished with them because it's a good programming practice
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

110

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


fclose($fileHandle);

- After a file has been closed down with fclose it is impossible to read, write or append to that file unless it is once more opened up with the fopen function.

9.2. File Manipulation:

Function file_exists()

Handle

Description Checks whether a file or directory exists. Ex:


if (file_exists('uploads/photo/a.jpg')) { echo "The file exists"; }

is_file()

Tells whether the filename is a regular file. Ex:


var_dump(is_file('uploads/photo/a.jpg')); // Displays "bool(true)" if file exists and is a regular file.

is_readable()

Tells wheter the filename is readable. Ex:


if (is_readable($filename)) { echo 'The file is readable'; }

is_writable() fread()

Yes

Tells whether the filename is writable. Reads data from file, with specified length. Ex:
$contents = fread($handle, 2048);

fwrite()

Yes

Writes data to file. Ex:


$writeByte = fwrite($handle, $ somecontent);

rewind()

Yes

Rewind the position of a file pointer. Ex:


$rewindStatus = rewind($handle);

file_get_contents()
VO DUY TUAN

Reads entire file into a string.


PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

111

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

Ex:
$contents = file_get_contents('config/text.txt');

chmod()

Changes file mode. Ex:


chmod("/somedir/somefile", 0666);

copy()

Copies file. Ex:


if (!copy($file, $newfile)) { echo "failed to copy $file...\n"; }

rename()

Renames a file or directory. Ex:


rename("file.txt", "upload/user.txt");

filesize()

Gets file size. Ex:


$size = filesize('upload/user.txt');

unlink()

Deletes a file. Ex:


if(unlink('upload/user.txt'')) echo 'Delete successfully!';

filemtime()

Gets file modification time. Return the Unix Timestamp. Ex:


$timestamp = filemtime('myfile.jpg');

pathinfo()

Returns information about a file path. Ex:


$path_parts = pathinfo('/www/htdocs/index.html'); echo echo echo echo $path_parts['dirname'], "\n"; $path_parts['basename'], "\n"; $path_parts['extension'], "\n"; $path_parts['filename'], "\n";

// Displays /www/htdocs index.html html


VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

112

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


index

9.3. Directory:
9.3.1. Open directory handle:
$dh = opendir('uploads/photos/');

9.3.2. Useful directory functions:


Function readdir() is_dir() mkdir() Handle Yes Description Reads entry from directory handle Tells whether the filename is a directory Makes directory. Ex:
mkdir("/path/to/my/dir", 0700, true);

rmdir() dirname()

Removes directory. Note: directory must be empty Returns directory name component of path. Ex:
$path = "/etc/passwd"; $file = dirname($path); // $file is set to "/etc"

9.3.3. Close directory handle:


closedir($dh);

9.3.4. Example:
if ($handle = opendir('.')) { while (false !== ($file = readdir($handle))) { if ($file != "." && $file != "..") { echo "$file\n"; } }
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

113

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

closedir($handle); }

9.4. File & Directory Constants:


9.4.1. __FILE__ : get the current executed file. Example:
echo dirname(__FILE__);

9.4.2. DIRECTORY_SEPARATOR : get the directory of the current system. '\' in


Windows and '/' in Linux.

Chapter Exercise: Write the website allows user register, login to system. After logging, users can upload photos, view their uploaded photos, deleting their photos. Each user has a photo directory with his name. a. When register, there is no 2 users with the same name. b. Password using md5() function to store c. Photos must be jpg,gif,png and size is not larger than 300KB d. User information stored in file with format: " rasmus,198792ks90s978jhsludssdf098s9adj,rasmus@a.com,AVATAR_URL bob, lakljliuaklnkajsdoif928379skjad,bobli@b.com,AVATAR_URL "

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

114

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

Chapter 10

MySQL
Keywords: DBMS, database, schema, mysql, table, column, row, index, unique, primary, foreign, key, relationship, create, insert, update, delete, dropping, select, query, statement, condition. Subjects: 10.1. DBMS Fundamentals 10.2. MySQL Fundamentals 10.3. MySQL Basics 10.4. Using phpMyAdmin 10.5. MySQL in PHP

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

115

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

10.1. DBMS Fundamentals:


10.1.1. DBMS Concept:
- A DBMS is a set of software programs that controls the organization, storage, management, and retrieval of data in a database.

10.1.2. DBMS Features:


+ Query Ability + Backup & Replication + Rule enforcement + Security + Computation + Change and access logging + Automated Optimization

10.1.3. Relational DBMS (RDBMS) :


- a database management system (DBMS) that is based on the relational model - Most popular commercial and open source databases currently in use are based on the relational model. - data is stored in the form of tables and the relationship among the data is also stored in the form of tables.

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

116

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

10.2. MySQL Fundamentals:


10.2.1. MySQL Introduction:
- is a relational database management system - Its popularity for use with web applications is closely tied to the popularity of PHP, which is often combined with MySQL - MySQL is commonly used by free software projects which require a full-featured database management system, such as WordPress, phpBB and other software built on the LAMP software stack. It is also used in very high-scale World Wide Web products including Google(not for searches), Facebook, Flickr, Wikipedia, Nokia, YouTube

10.2.2. MySQL Using:

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

117

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

10.2.2.1. Graphical User Interface - GUI: - Navicat MySQL:

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

118

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

- SQLyog:

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

119

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

10.2.2.2. Shell:

10.2.2.3. PHP Scripts:


<?php $username="username"; $password="password"; $database="your_database"; $first=$_POST['first']; $last=$_POST['last']; $phone=$_POST['phone']; $mobile=$_POST['mobile']; $fax=$_POST['fax']; $email=$_POST['email'];
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

120

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


$web=$_POST['web']; mysql_connect("localhost",$username,$password); mysql_select_db($database) or die( "Unable to select database"); $query = "INSERT INTO contacts VALUES ('','$first','$last','$phone','$mobile','$fax','$email','$web')"; mysql_query($query); mysql_close(); ?>

10.2.2.4. phpMyAdmin:

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

121

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

10.3. MySQL Basic:


10.3.1. Create Database:
- A MySQL database is nothing in itself. Rather a MySQL database is a way of organizing a group of tables. If you were going to create a bunch of different tables that shared a common theme, you would group them into one database to make the management process easier. - creates a database with the given name.
CREATE DATABASE database_name

- Ex:
CREATE DATABASE employee

10.3.2. Create Tables:


- In MySQL and other database systems, the goal is to store information in an orderly fashion. The table gets this done by making the table up of columns and rows. - The columns specify what the data is going to be, while the rows contain the actual data. Below is how you could imagine a MySQL table. (C = Column, R = Row)

- Before you can enter data (rows) into a table, you must first define what kinds of data will be stored (columns)
CREATE TABLE example ( id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), name VARCHAR(30), age INT )

- Query description:
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

122

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


+ "id INT NOT NULL AUTO_INCREMENT" :

Here we create a column "id" that will automatically increment each time a new entry is added to the table. This will result in the first row in the table having an id = 1, the second row id = 2, the third row id = 3, and so on.
INT - This stands for integer or whole number. 'id' has been defined to be an integer. NOT NULL - These are actually two keywords, but they combine together to say that this column cannot be null. An entry is NOT NULL only if it has some value, while something with no value is NULL. AUTO_INCREMENT - Each time a new entry is added the value will be incremented by 1.

+ "PRIMARY KEY(id)" :

PRIMARY KEY is used as a unique identifier for the rows. Here we have made "id" the PRIMARY KEY for this table. This means that no two ids can be the same, or else we will run into trouble. Here we make a new column with the name "name"! VARCHAR stands for "variable character". "Character" means that you can put in any kind of typed information in this column (letters, numbers, symbols, etc). It's "variable" because it can adjust its size to store as little as 0 characters and up to a specified maximum number of characters. Our third and final column is age, which stores an integer. Notice that there are no parentheses following "INT"

+ "name VARCHAR(30)" :

+ "age INT" :

10.3.3. Insert values:


- When inserting data it is important to remember the exact names and types of the table's columns.
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);

10.3.4. Retrieve data from database:


- Usually most of the work done with MySQL involves pulling down data from a MySQL database. In MySQL, data is retrieved with the "SELECT" keyword - Syntax:
SELECT [ALL | DISTINCT | DISTINCTROW ] select_expr [, select_expr ...] [FROM table_references [WHERE where_condition] [GROUP BY {col_name | expr | position} [ASC | DESC], ... [WITH ROLLUP]]
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

123

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


[HAVING where_condition] [ORDER BY {col_name | expr | position} [ASC | DESC], ...] [LIMIT {[offset,] row_count | row_count OFFSET offset}]

- Ex:
SELECT * FROM countries ORDER by iso_code IN ('UK', 'US') DESC SELECT *, COUNT(field) FROM table GROUP BY field HAVING COUNT(count)>=1;

10.3.5. Change values:


- Update values of one or more rows in tables - Syntax:
UPDATE table_name SET field = value, Field = value WHERE LIMIT

- Ex:
UPDATE items, month SET items.price = month.price WHERE items.id = month.id;

10.3.6. Delete rows:


- From time to time, you may even need to delete items from your database. Some potential reasons for deleting a record from MySQL include when: someone deletes a post from a forum, an employee leaves a company. - Before performing a large delete on a database, be sure to back up the table/database in case your script takes off a little more than desired. Test your delete queries before even thinking about using them on your table.

- Syntax:
DELETE FROM table_name WHERE LIMIT

- Ex:
DELETE FROM users
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

124

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


WHERE activated = 0 LIMIT 10

10.3.7. Remove tables:


- To remove a table from a MySQL database, and remove all of its data, use the following SQL command:
DROP TABLE table_name

10.3.8. Remove databases:


- Drops all tables in the database and deletes the database. - Be very careful with this statement! To use DROP DATABASE, you need the DROP privilege on the database.
DROP DATABASE database_name

- Ex:
DROP DATABASE mydbtest

10.4. Using phpMyAdmin:


10.4.1. Login to phpMyAdmin:
- Using URL: http://localhost/phpmyadmin/

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

125

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

10.4.2. Create Database:

10.4.3. Creat Table:

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

126

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

10.4.4. Select Database:


- Select the dropdown box on the left panel, click the database you want to working.

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

127

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

10.4.5. Select Table:


- Click a table on the left panel to select

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

128

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

10.4.6. Change Table Structure:


- Select the columns you want to change structure, click Edit button

10.4.7. Insert Value to Table:


VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

129

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

- Select the table you want to insert value - Click the INSERT tab to begin insert data

10.4.8. View All Data of Table:


- Select the table you want to view data - Click the BROWSE tab to view table data

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

130

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

10.4.9. Edit Value of Rows:


- Edit 1 Row by click on the Edit icon ( ) on selected row. - Delete multiple rows by click the checkbox before each row, after that, click the Edit icon ( ) followed the data tables.
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

131

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

- In the Editing page, update your value, and click Go button to save.

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

132

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

10.4.10. Delete Rows in Table:


- Delete 1 Row by click on the Delete icon ( ) on selected row.

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

133

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

- Delete multiple rows by click the checkbox before each row, after that, click the Delete icon ( ) followed the data tables.

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

134

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

10.4.11. Export SQL Data:


- Select the database, click the export tab - choose the tables you want to export and click GO button at the bottom to begin export.

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

135

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

10.4.12. Import SQL Data from File:


- Click the Import Tab to open Import page - Browse the SQL Data file you want to import - Click GO button to begin importing file.

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

136

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

10.4.13. Query Data:


- Click the SQL Tab to open Query page - Type you queries and click GO button to run queries.

10.4.14. Clear All Table Data:


- Select Table you want to clear data - click Empty Tab, it will show a prompt dialog, click OK if you agree to clear table's data.

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

137

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

10.4.15. Drop Table:


- Select Table you want to delete (drop) - click Drop Tab, it will show a prompt dialog, click OK if you agree to drop table.

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

138

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

10.4.16. Drop Database:


- Select the database you want to delete (drop) - Click the Drop TAB, it will show a prompt dialog, click OK if you agree to delete database.

10.5. MySQL in PHP:


10.5.1. Connect to MySQL Server:
- Open a connection to a MySQL Server. - Returns a MySQL link identifier on success, or FALSE on failure. - Ex:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully';

10.5.2. Select MySQL database:


VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

139

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

- Select a MySQL database. - Every subsequent call to mysql_query() will be made on the active database. - Returns TRUE on success or FALSE on failure.
//Select the test database $db_selected = mysql_select_db('test', $link); if (!$db_selected) { die ('Can\'t use foo : ' . mysql_error()); }

10.5.3. Close MySQL connection:


- Close MySQL connection. - Using mysql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution
mysql_close($link);

10.5.4. Some Useful Functions:


Function mysql_query() Description Sends a MySQL query. Ex:
$result = mysql_query('SELECT * FROM employee');

mysql_fetch_row()

Get a result row as an enumerated array. Ex:


$row = mysql_fetch_row($result);

mysql_fetch_array()

Fetch a result row as an associative array, a numeric array, or both. Ex:


$row = mysql_fetch_array($result,MYSQL_ASSOC);

mysql_num_rows()
VO DUY TUAN

Get number of rows in result. Ex:


PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

140

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


$num_rows = mysql_num_rows($result);

mysql_affected_rows()

Get number of affected rows in previous MySQL operation. Ex:


$affectedRows = mysql_affected_rows();

mysql_real_escape_string()

Escapes a string for use in a mysql_query(). Ex:


$securedStr = mysql_real_escape_string($str);

mysql_insert_id()

Get the ID generated from the previous INSERT operation. Ex:


$latestUserId = mysql_insert_id();

mysql_free_result()

Free result memory. Ex:


mysql_free_result($result);

Chapter Exercise: Edit the website at Chapter 9, using MySQL Database instead of Files to store user information.

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

141

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

Chapter 11

Logging & Debugging


Keywords: log, trace, tracking, error, warning, notice, debug, error reporting, phped, debugger, step, breakpoint. Subjects: 11.1. Log Configuration 11.2. PhpEd Debugger Installation 11.3. Debugging

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

142

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

11.1. Log Configuration:


11.1.1. php.ini directives:
error_reporting = E_ALL & ~E_NOTICE error_log = /var/log/php-scripts.log display_errors = Off log_errors = On

11.1.2. Setting on PHP script:


ini_set("log_errors" , "1"); ini_set("error_log" , "Errors.log.txt"); ini_set("display_errors" , "0");

11.2. PhpEd Debugger Installation:


11.2.1. Install PhpEd Debugger:
- Go to debugger folder of phpEd (Ex: "C:\Program Files\nusphere\phped\debugger\server\"), Find the correct platform (Linux, Windows) and correct PHP version on server to copy the extension to the PHP Extension folder on the server. - In this case, my AppServ 2.10 was installed on Windows XP, so, I copy file "nusphere\phped\debugger\server\Windows\x86\dbg-php-5.2.dll" to folder "D:\AppServ\php5\ext\" folder.

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

143

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

11.2.2. php.ini debugger configuration:

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

144

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

- Add the dbg-php-5.2.dll extension to PHP Extension list in PHP.INI File. Insert this line in the extension section:
extension=dbg-php-5.2.dll

- Continue editing the PHP.INI file to active the debuger. Add these lines to PHP.INI File.
[debugger] debugger.enabled=on debugger.profiler_enabled=on debugger.hosts_allow=host1 host2 host3 debugger.hosts_deny=ALL debugger.ports=7869, 10000/16

11.2.3. Using Extension DBGbar Toolbar on Firefox:

11.3. Debugging:
11.3.1. Using Debugging Mode:
- Open PhpEd. - Open website using Firefox, click on the DBGbar, select 'Debug this page' to jump to Debugging Mode of PhpEd.

11.3.2. Step debugging:

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

145

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

11.3.3. Watching Variables value when debugging


- Using Watch Dialog to view the current value of variables. - Type the variable name, and you will get the value of variable.

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

146

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

11.3.4. Using Breakpoint:


VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

147

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

- Breakpoint is the location in programming code that, when reached, triggers a temporary halt in the program. - Programmers use breakpoints to test and debug programs by causing the program to stop at scheduled intervals so that the status of the program can be examined in stages.

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

148

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

Chapter 12

OOP Advanced
Keywords: interface, abstract, final, access, exception, lazy loading. autoload, reflection. Subjects: 12.1. Interface 12.2. Abstract Class, Method 12.3. Final Class, Method 12.4. Lazy Loading 12.5. Magic Methods

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

149

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

12.1. Interface:
12.1.1. Interface Introduction:
- Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled.

12.1.2. Declaration:
- Interfaces are defined using the interface keyword, in the same way as a standard class, but without any of the methods having their contents defined. - All methods declared in an interface must be public, this is the nature of an interface. - Example:
interface IAnimal { function eat(); function say(); }

12.1.3. Implementation:
interface IAnimal { function eat(); function say(); } class Dog implements IAnimal { function eat(){ echo 'Dog is eating'; } function say(){ echo 'I am a dog'; } } class Cat implements IAnimal { function eat(){ echo 'Cat is eating';} function say(){ echo 'I am a cat'; } } $dog = new Dog(); $cat = new Cat(); $dog->say(); $cat->say(); // Display "I am a dog" // Display "I am a cat"
PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

VO DUY TUAN

150

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

12.2. Abstract Class, Method:

- An abstract class defines the basic skeleton for the class. It contains properties and methods but some methods are incomplete and is waiting for some other class to extend it through inheritance so that the derived class provides a full functionality for the incomplete methods. - A abstract class cannot be instantiated and it can only be extended. A class prefix with abstract keywords are abstract class. - If a method is defined as abstract then it cannot be declared as private (it can only be public or protected). - Syntax:
abstract class classname { //properties and methods abstract function methodname(); } class derived extends classname { function methodname(){} }

- Example:
abstract class Review {
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

151

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


abstract function record(); public function normalMethod(){echo 'it is a normal method';} } class CustomerReview extends Review { function record(){ echo 'Customer Review record';} } class EditorialReview extends Review { function record(){echo 'Editorial Review record';} } $cusReview = new CustomerReview(); $cusReview->record(); // Displays "Customer Review record" $review = new Review(); // Fatal Error

12.3. Final Class, Method:


12.3.1. Final Class:
- A final class is a class that cannot be extended. To declare a class as final, you need to prefix the class keyword with final. - You should declare a class as final when you think that you implementation of that class should not change in the derived class. You should do this mainly for Utility classes where you dont want the behavior/implementation of your class to change. - Example:
final class FinalClass { function hello(){echo 'Final class says hello!';} } class ChildFinalClass extends FinalClass { }

12.3.2. Final Method:


- Final method is a method that cannot be overridden. To declare a method as final, you need to prefix the function name with the final keyword

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

152

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

- You should declare a class method as final when you think that the method you develop contains necessary functionality to support your application and any modification or change to the functionality can cause unexpected errors/bugs. - Example:
class NormalClass { final function hello(){echo 'Normal class says hello!';} } class ChildNormalClass extends NormalClass { function hello(){echo 'testing';} }

12.4. Lazy Loading:


12.4.1. Introduction:
- Loading of class on-demand. - When referencing a non-existent class, be it as a type hint, static call, or instantiating an object, PHP will try to call the __autoload() global function so that the script may be given an opportunity to load it.

12.4.2. Magic Method __autoload() :


- The magic method __autoload() function is a convenience that allows you to use classes without having to explicitly write code to include them. - The magic method __autoload() is not included in your class definition as this is to be called once in a script. The best place to put the autoload() file is in your configuration file which is loaded in all your other scripts. -The __autoload() method is called only once for each new class that needs to be loaded. Subsequent instantiation of the Customer class object will not call the __autoload() method again. Therefore, this offers performance improvements in your scripts because, unless the class is needed - files are not loaded. Therefore, the PHP engine does not have to parse and compile an unnecessary file.

12.4.3. Implement Lazy Loading:


VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

153

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


function __autoload($class) { require_once str_replace(" ", "/", $class); } $obj= new Some_Class();

12.5. Magic Methods:


12.5.1. Property Overloading:
12.5.1.1. __get() : reading data from inaccessible properties. Example:
Class test { public $var1 = 'abc'; private $pvar2 = 'hello'; function __get($name) { $privateName = 'p'.$name; if(isset($this->$privateName)) { return $this->$privateName; } else return ''; } } $myTest = new test(); echo $myTest->var1; // Displays "abc" echo $myTest->pvar2; // Displays nothing echo $myTest->var2; // Displays "hello"

12.5.1.2. __set() : writing data to inaccessible properties. Example:


Class test { public $var1 = 'abc'; private $pvar2 = 'hello'; function __get($name) { $privateName = 'p'.$name; if(isset($this->$privateName))
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

154

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


{ return $this->$privateName; } else return ''; }

function __set($name, $value) { $privateName = 'p'.$name; if(isset($this->$privateName)) { //can validate input data here // //assign to private property $this->$privateName = $value; } } } $myTest = new test(); $myTest->var1 = 'def'; // Assigns $var1 = "def" $myTest->pvar2 = 'world'; // Do nothing $myTest->var2 = 'world'; // Assigns $pvar2 = "world" echo $myTest->var2; // Displays "world"

12.5.1.3. __isset() : is triggered when calling isset() or empty() on inaccessible properties. Example:
Class test { public $var1 = 'abc'; private $p = array('var2'=>'hello'); function __isset($name) { if(isset($this->p[$name])) { return true; } else return false; } } $myTest = new test(); var_dump(isset($myTest->var1)); // Displays "bool(true)"
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

155

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


var_dump(isset($myTest->pvar2)); // Displays "bool(false)" var_dump(isset($myTest->var2)); // Displays "bool(true)"

12.5.1.4. __unset() : is triggered when calling unset() on inaccessible properties. Example:


Class test { public $var1 = 'abc'; private $p = array('var2'=>'hello'); function __unset($name) { if(isset($this->p[$name])) { unset($this->p[$name]); } } } $myTest = new test(); unset($myTest->var1); unset($myTest->var2);

12.5.2. Method Overloading:


12.5.2.1. __call() : is triggered when invoking inaccessible methods in an object context. Example:
Class test { public function __call($name, $arguments) { echo "Calling $name(".implode(', ', $arguments).")\n"; } } $myTest = new test(); $myTest->unknowfunction(1,2); // Displays "Calling unknowfunction(1, 2)"

12.5.2.2. __callStatic() : is triggered when invoking inaccessible methods in a static context. Note: PHP Version >= 5.3. Example:
Class test { public function __callStatic($name, $arguments)
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

156

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


{ echo "Calling Static method test::$name(".implode(', ', $arguments).")\n"; } } test::unknowfunction(1,2); // Displays "Calling Static method test::unknowfunction(1, 2)"

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

157

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

Chapter 13

MySQL Advanced
Keywords: MyISAM, InnoDB, join, statement, prepared statement, transaction, PDO. Subjects: 13.1. Table Joining 13.2. PHP Data Object (PDO)

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

158

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

13.1. Table Joining:

13.1.1. Introduction
- Combines records from two or more tables in a database.

13.1.2. Inner Join:


- The INNER JOIN clause tells the database to only return rows where there is a match found between tableA and tableB. An INNER JOIN is most often (but not always) created between the primary key column of one table and the foreign key column of another table.

SELECT * FROM employee INNER JOIN department ON employee.DepartmentID = department.DepartmentID

Or:
SELECT * FROM employee, department WHERE employee.DepartmentID = department.DepartmentID

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

159

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

13.1.3. Left Join:


- The LEFT JOIN keyword returns all rows from the left table (table A), even if there are no matches in the right table (table B).

SELECT * FROM employee LEFT JOIN department ON employee.DepartmentID = department.DepartmentID;

13.1.4. Right Join:


- The RIGHT JOIN keyword Return all rows from the right table (table B), even if there are no matches in the left table (table A).

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

160

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

SELECT * FROM employee RIGHT JOIN department ON employee.DepartmentID = department.DepartmentID

13.1.5. Self Join:


- Table is joined to itself and is made possible by aliasing the original table.

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

161

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

SELECT Employees.EmployeeID, Employees.Name, Employees.Salary, Manager.Name AS Manager FROM Employees LEFT JOIN Employees AS Manager ON Employees.ManagerID = Manager.EmployeeID WHERE (Employees.EmployeeID = '087652';

13.2. PHP Data Object (PDO):


13.2.1. PDO Introduction:
- PDO : PHP Data Object - PHP5 - OOP

13.2.2. Connect to MySQL:


try { $dbh = new PDO("mysql:host=localhost;dbname=test", 'username', 'password'); echo 'Connected to database'; } catch(PDOException $e) { echo $e->getMessage(); } // query here

//close connection $dbh = null;


VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

162

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

13.2.3. Query: 13.2.3.1. Using PDO::exec() method: Execute an SQL statement and return the
number of affected rows.
Ex:
/* Delete some rows from the Employee table */ $count = $dbh->exec("DELETE FROM employee WHERE DepartmentID > 32"); /* Return number of rows that were deleted */ print("Deleted $count rows.\n");

13.2.3.2. Using PDO::query() method: Executes an SQL statement, returning a


result set as a PDOStatement object Ex:
$sql = 'SELECT DepartmentName, DepartmentID FROM department'; foreach ($dbh->query($sql) as $row) { print $row['DepartmentName'] . "\t"; print $row['DepartmentID'] . "\n"; }

13.2.4. Prepared Statement: 13.2.4.1. Using ':field' format:


$sql = 'INSERT INTO employee(LastName, DepartmentID) VALUES(:name, :departmentid)'; $stmt = $dbh->prepare($sql); $stmt->bindParam(':name', $name); $stmt->bindParam(':departmentid', $departmentId); $name = 'Test1'; $departmentId = 35; $stmt->execute();

OR:
$sql = 'INSERT INTO employee(LastName, DepartmentID) VALUES(:name, :departmentid)'; $stmt = $dbh->prepare($sql); $stmt->execute(array(':name' => 'Test1',
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

163

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


':departmentid' => 35));

13.2.4.2. Using '?' character:


$sql = 'INSERT INTO employee(LastName, DepartmentID) VALUES(?, ?)'; $stmt = $dbh->prepare($sql); $stmt->execute(array('Test1', 35));

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

164

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

Chapter 14

Software Engineering Basic


Keywords: UML, Use case, actor, diagram, software engineering, relationship. Subjects: 14.1. Requirement Gathering 14.2. Use-Case Diagram 14.3. Class Diagram

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

165

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

14.1. Requirement Gathering:

14.1.1. General:
1. Where did you hear about us? 2. Do you have a domain name? If not, do you have ideas on one? If so, what is it? 3. What is your company name? Do you want to use the entire name on the site, logo, and graphics? 4. Do you have special features in mind like ECommerce shopping cart, BLOG, RSS, Forms with emails, EZine, Newsletter signup, autoresponders, advertising landing/call-to-action pages, etc.?
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

166

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

14.1.2. Marketing:
1. Who is your intended audience? Are they regional, industry specific, company size specific, etc.? 2. Do you intend to provide a call to action - make a sale, call in to your office, fill out a form, etc? 3. Describe your ideal client and the specific attributes that we'll be targeting in the website. 4. What are your website expectations, main emphasis and primary goals - increased sales, increased leads, etc.? Please prioritize. 5. What separates your company from your competition and what do you expect will draw clients to the website? 6. How do you plan to market the website? 7. What company properties do you want to emphasize on the website? Please prioritize.

14.1.3. Identity:
1. Do you already have a logo and other graphics to be used? If not, do you want to have one created? 2. Have you identified a tagline? 3. What keywords do you want to be found by in the search engines?

14.1.4. Layout:
1. Please provide a list of websites that you like and don't like. Why do you or do you not like these sites? 2. Please provide a list of competitors' websites.
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

167

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

3. Do you have ideas of the colors to be used, and colors you don't like? Please provide example sites. 4. Do you have an intended website screen size - 1024x768, 800x600, or stretch to the entire width of the screen? 5. If the site isn't the entire width of the screen do you have a preference for left or center alignment? 6. Do you have a horizontal or left-side vertical preference for the main navigation? 7. Please provide the main pages you need in the website. 8. Have you created the copy text for any of your pages? 9. Do you have existing business cards or other printed material we need to match? 10. Are you leaning towards custom drawn artwork or photographs?

14.2. Use-Case Diagram:


14.2.1. Introduction:
- The Use case diagram is used to identify the primary elements and processes that form the system. The primary elements are termed as "actors" and the processes are called "use cases." The Use case diagram shows which actors interact with each use case. - A use case diagram captures the functional aspects of a system. More specifically, it captures the business processes carried out in the system - Use case diagrams define the requirements of the system being modeled and hence are used to write test scripts for the modeled system.

14.2.2. Elements of Use Case diagram:


- Actor: An actor portrays any entity (or entities) that performs certain roles in a given system

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

168

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

or - Use Case: a visual representation of a distinct business functionality in a system

- System boundary: A system boundary defines the scope of what a system will be

14.2.3. Relationship in Use Case Diagram:


- Include: a use case includes the functionality described in the another use case as a part of its business process flow

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

169

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

- Extend: In an extend relationship between two use cases, the child use case adds to the existing functionality and characteristics of the parent use case

- Generalization: The child use case in the generalization relationship has the underlying business process meaning, but is an enhancement of the parent use case

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

170

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

171

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

14.2.4. UML Tools:


- Rational Rose (Commerce Software):

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

172

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

- ConceptDraw

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

173

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

-StarUML (Freeware):

14.2.5. Example:

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

174

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

14.3. Class Diagram:


14.3.1. Introduction:
-By definition, a class diagram is a diagram showing a collection of classes and interfaces, along with the collaborations and relationships among classes and interfaces. - A class diagram is a pictorial representation of the detailed system design

14.3.2. Elements of Class Diagram:


- Class: A class represents an entity of a given system that provides an encapsulated implementation of certain functionality of a given entity.

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

175

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

- Interface: An interface on the other hand provides only a definition of business functionality of a system.

- Package: A package provides the ability to group together classes and/or interfaces that are either similar in nature or related. Grouping these design elements in a package element provides for better readability of class diagrams, especially complex class diagrams

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

176

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

14.3.3. Relations between Classes:


- Association: When two classes are connected to each other in any way, an association relation is established

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

177

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

- Aggregation: When a class is formed as a collection of other classes, it is called an aggregation relationship between these classes

- Inheritance/Generalization: Generalization is the basic type of relationship used to define reusable elements in the class diagram

- Realization: In a realization relationship, one entity (normally an interface) defines a set of functionalities as a contract and the other entity (normally a class) "realizes" the contract by implementing the functionality defined in the contract.

Chapter Exercise: Draw the Use-case Diagram and Class diagram for an E-commerce website.

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

178

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

Chapter 15

XML & Web Service


Keywords: XML, web service, parsing, element, root, attribute, doctype, namespace, well-formed, valid, XPath, SimpleXML, SOAP, WSDL, JSON. Subjects: 15.1. XML Basics 15.2. SimpleXML Class 15.3. Web Service Basics 15.4. SOAP 15.5. JSON Overview

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

179

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

180

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

15.1. XML Basics:


15.1.1. Introduction:
XML stands for Extensible Markup Language XML is a markup language much like HTML XML was designed to carry data, not to display data XML tags are not predefined. You must define your own tags XML is designed to be self-descriptive XML is a W3C Recommendation

15.1.2. Well-formed XML:

15.1.3. Valid XML: Well-formed & follow Document Type Definition (DTD) or XML
Schema(XSD):

15.1.3.1. Internal DTD:


<?xml version="1.0"?> <!DOCTYPE note [ <!ELEMENT note (to,from,heading,body)> <!ELEMENT to (#PCDATA)> <!ELEMENT from (#PCDATA)> <!ELEMENT heading (#PCDATA)> <!ELEMENT body (#PCDATA)> ]> <note> <to>Tove</to> <from>Jani</from>
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

181

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


<heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>

15.1.3.2. External DTD:


<?xml version="1.0"?> <!DOCTYPE note SYSTEM "note.dtd"> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>

"note.dtd" file:
<?xml version="1.0"?> <!ELEMENT note (to,from,heading,body)> <!ELEMENT to (#PCDATA)> <!ELEMENT from (#PCDATA)> <!ELEMENT heading (#PCDATA)> <!ELEMENT body (#PCDATA)>

15.2. SimpleXML Class:


15.2.1. Load XML Data:
- Load an XML String:
$xmlstr = file_get_contents('book.xml'); $booklib = simplexml_load_string($xmlstr);

- Load an XML File:


$booklib = simplexml_load_file('book.xml');

- Load an XML String using OOP:


$xmlstr = file_get_contents('book.xml'); $booklib = new SimpleXMLElement($xmlstr);

- Load an XML File using OOP:


$booklib = new SimpleXMLElement('book.xml', NULL, true);

15.2.2. Simple Read XML Data:


VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

182

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


foreach($booklib->Book as $book) { echo $book['ISBN'] . "\n"; echo $book['title'] . "\n"; echo $book[author] . "\n\n"; }

15.2.3. Common SimpleXML Class Method:


Method addChild() Description Adds a child element to the XML node. Ex:
$magazine = $booklib->addChild('magazine'); $magazine->addChild('PCW', 'Mag for IT, Jun 09');

addAttribute()

Adds an attribute to the SimpleXML element. Ex:


$magazine->addAttribute('size', 'big');

attributes()

Returns element's attributes. Ex:


foreach($magazine->attributes() as $magAttr)

children()

Finds children of given node. Ex:


foreach($booklib->children() as $book)

getName()

Gets the name of the XML element. Ex:


$tagName = $magazine->getName();

xpath()

Runs XPath query on XML data. Ex:


$result =$booklib->xpath('/Books/Book/author');

15.2.4. Export XML Data:


- Output to XML string:
header('Content-type: text/xml'); echo $booklib->asXML();

- Save to XML file:


$booklib->asXML('mybook.xml');

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

183

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

15.3. Web Service Basics:


15.3.1. Introduction:

Web services are application components Web services communicate using open protocols Web services are self-contained and self-describing Web services can be discovered using UDDI Web services can be used by other applications XML is the basis for Web services

15.3.2. Types of Using Web Services:


15.3.2.1. Reusable application-components: - Reusable components. - Offer application-components. - Examples: Weather report, Map 15.3.2.2. Connect existing software: - Solve interoperability problem. - Link to exchange data between different applications and platforms.

15.4. SOAP:
15.4.1. Enable SOAP Extension in PHP5:
- Edit file PHP.INI, uncomment line extension for php_soap

15.4.2. Using non-WSDL Mode:


15.4.2.1. Soap Server:
class QuoteService { private $quotes = array("ibm" => 98.42); function getQuote($symbol) { if (isset($this->quotes[$symbol]))
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

184

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


{ return $this->quotes[$symbol]; } else { throw new SoapFault("Server","Unknown Symbol '$symbol'."); } } } $options = array('uri' => 'http://localhost/soap/server.php'); $server = new SoapServer(NULL, $options); $server->setClass("QuoteService"); $server->handle();

15.4.2.2. Soap Client:


$options = array( 'location' => http://localhost/soap/server.php', 'uri' => 'http://localhost/soap/'); $client = new SoapClient(NULL, $options); try { print($client->getQuote("ibm")); print($client->getQuote("microsoft")); } catch (SoapFault $exception) { echo 'Not Found'; }

15.4.3. Using WSDL Mode:


15.4.3.1. WSDL File:
<?xml version ='1.0' encoding ='UTF-8' ?> <definitions name='StockQuote' targetNamespace='http://example.org/StockQuote' xmlns:tns=' http://example.org/StockQuote ' xmlns:soap='http://schemas.xmlsoap.org/wsdl/soap/' xmlns:xsd='http://www.w3.org/2001/XMLSchema'

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

185

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


xmlns:soapenc='http://schemas.xmlsoap.org/soap/encoding/' xmlns:wsdl='http://schemas.xmlsoap.org/wsdl/' xmlns='http://schemas.xmlsoap.org/wsdl/'> <message name='getQuoteRequest'> <part name='symbol' type='xsd:string'/> </message> <message name='getQuoteResponse'> <part name='Result' type='xsd:float'/> </message>

<portType name='StockQuotePortType'> <operation name='getQuote'> <input message='tns:getQuoteRequest'/> <output message='tns:getQuoteResponse'/> </operation> </portType>
<binding name='StockQuoteBinding' type='tns:StockQuotePortType'> <soap:binding style='rpc' transport='http://schemas.xmlsoap.org/soap/http'/> <operation name='getQuote'> <soap:operation soapAction='urn:xmethods-delayed-quotes#getQuote'/> <input> <soap:body use='encoded' namespace='urn:xmethods-delayed-quotes' encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'/> </input> <output> <soap:body use='encoded' namespace='urn:xmethods-delayed-quotes' encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'/> </output> </operation> </binding>

<service name='StockQuoteService'> <port name='StockQuotePort' binding='StockQuoteBinding'> <soap:address location='http://localhost/soap/server.php'/> </port> </service>


</definitions>

15.4.3.2. Soap Server:


class QuoteService { private $quotes = array("ibm" => 98.42); function getQuote($symbol) { if (isset($this->quotes[$symbol])) { return $this->quotes[$symbol]; } else {
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

186

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


throw new SoapFault("Server","Unknown Symbol '$symbol'."); } } } $server = new SoapServer("stockquote.wsdl"); $server->setClass("QuoteService"); $server->handle();

15.4.3.3. Soap Client:


$client = new SoapClient("stockquote.wsdl"); try { print($client->getQuote("ibm")); print($client->getQuote("microsoft")); } catch (SoapFault $exception) { echo 'Not Found'; }

15.5. JSON Overview:


15.5.1. Introduction:
{"menu": { "id": "file", "value": "File", "popup": { "menuitem": [ {"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"} ] } }}

15.5.2. Using JSON in PHP:


VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

187

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

15.5.2.1. json_encode() : returns the JSON format of a variable.


Ex:
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5); echo json_encode($arr); // Displays '{"a":1,"b":2,"c":3,"d":4,"e":5}'

15.5.2.2. json_decode() : decodes a JSON string. Ex:


$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; var_dump(json_decode($json)); var_dump(json_decode($json, true)); // Displays object(stdClass)#1 (5) { ["a"] => int(1) ["b"] => int(2) ["c"] => int(3) ["d"] => int(4) ["e"] => int(5) } array(5) { ["a"] => ["b"] => ["c"] => ["d"] => ["e"] => }

int(1) int(2) int(3) int(4) int(5)

15.5.3. XML vs. JSON:


XML Format:
<menu id="file" value="File"> <popup> <menuitem value="New" onclick="CreateNewDoc()" /> <menuitem value="Open" onclick="OpenDoc()" /> <menuitem value="Close" onclick="CloseDoc()" /> </popup> </menu>

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

188

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

Chapter Exercise: A> Write a Webpage simple SOAP service to simulate a calulator with operator: +, -, *, / and write an client using that service. In client side, user input 2 number in HTML form and click submit, your script will use calculator service to calculate the result and response for user. Example: $sum = $client->plus($_GET['first'], $_GET['second']); B> Use SimpleXML to read RSS Feeds from a news website (ex:tuoitre, vnexpress) and displays into your website.

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

189

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

Chapter 16

Security
Keywords: security, hack, attacker, password, register globals, exploit, input, whitelist, blacklist, filtering, sanitize, escape, hashing, spoof, XSS, CSRF, SQL Injection, information leakage, command Injection, user agent, risk, vulnerable, validate, session fixation, hijacking, identifier, privilege, remote code injection, safe mode. Subjects: 16.1. Security Basics 16.2. Database Security 16.3. Website Security 16.4. Session Security 16.5. File System Security

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

190

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

16.1. Security Basics:


16.1.1. Why consider security? 16.1.2. Core PHP security theory:
- know the mechanism of HTTP model - Check PHP configuration - Hide important data - Filter User input data

16.2. Database Security:


16.2.1. SQL Injection:

Solution: - Prevent unauthorized access


VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

191

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

- Limit the permissions. - Filter user input - Using prepared statements - Hide database errors.

16.2.2. Information Leakage:


Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost' (using password: YES)' in D:\AppServ\www\phpa\index.php(492) : eval()'d code:1 Stack trace: #0 D:\AppServ\www\phpa\index.php(492) : eval()'d code(1): PDO>__construct('mysql:host=loca...', 'root', 'rooat') #1 D:\AppServ\www\phpa\index.php(492): eval() #2 {main} thrown in D:\AppServ\www\phpa\index.php(492) : eval()'d code on line 1

Solution: - Configure right setting for logging, display error - Catch exception when error

16.3. Website Security:


16.3.1. Weak Authentication:
- Weak Password - Guessing Files & Directories - People

Solution:
- Strong password - Set Access-Rule for files, directories - Publish files/directories when needed.
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

192

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

- Notice to file/directory name convention - Keep your secret

16.3.2. Using bad libraries, components, plug-ins:


- Open-source projects - Free-proviced scripts, libraries, components, plug-ins, widgets - Discussion Board (forum) - "Bad" books - "Bad" people.

Solution:
- Check bugs before using. - Check the source of scripts, libraries, plug-ins, widgets - Check the reviews of others scripts. - Write your own code when needed.

16.3.3. DoS DDoS - SPAM:

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

193

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

Solution:
- Using Session to limit the actions on the website - User Authentication - Redirect & Authentication - Track IP - Check User-Agent - Using CAPTCHA - Use lower level system security (Clustering & Load balance, IDS, IPS, Bandwidth management)

16.3.4. Cross Site Scripting - XSS :


VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

194

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

View Animation: http://www.virtualforge.de/vmovie.php

Solution:
- Filter All Input - Escape All Output - Only Allow Safe Content

16.3.5. Cross Site Request Forgery CSRF :

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

195

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

196

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

View Animation: http://www.virtualforge.de/vmovie.php

Solution:
- Use POST methods - Require Verification for important actions - Use an Anti-CSRF Token. - Limit the external link resource(images, scripts) submitted by users

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

197

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

16.4. Session Security:


16.4.1. Session Fixation:

Solution: - Correct Configuration (do not accept external SIDs, set time-out..) - Perform session id regeneration, support log-out, reject illegal referrers Ex:
if (strpos($_SERVER['HTTP_REFERER'], 'https://DiD/') !== 0 || isset($_GET['LOGOUT']) || $_SERVER['REMOTE_ADDR'] !== $_SESSION['PREV_REMOTEADDR'] || $_SERVER['HTTP_USER_AGENT'] !== $_SESSION['PREV_USERAGENT']) session_destroy(); session_regenerate_id(); // generate a new session identifier $_SESSION['PREV_USERAGENT'] = $_SERVER['HTTP_USER_AGENT']; $_SESSION['PREV_REMOTEADDR'] = $_SERVER['REMOTE_ADDR'];
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

198

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

16.4.2. Session Hijacking:

Solution: - Using HTTPS on sensitive areas - Check various request headers sent by the client (User-Agent, IP, referrer header) Ex:
// After a successful login, store the User-Agent into the session: $_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT']; // On subsequent page loads, check to ensure User-Agent // not change. If its has changed, then that is cause
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

199

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


// for concern, and the user should log in again if ($_SESSION['user_agent'] != $_SERVER['HTTP_USER_AGENT']) { // Force user to log in again exit; }

16.5. File System Security:


16.5.1. File Including Injection:
Solution: - Check the path of included file - Filter file name

16.5.2. Command Injection:


Solution: - Disable unuse functions using directives in PHP.INI file( directive disable_functions, disable_classes) - Using escape function: escapeshellcmd(), escapeshellarg(). - Avoid the use of shell commands. - Avoid the use of client input to construct dynamic shell commands.

16.5.3. Shared Hosting , Local Attack:


Solution: - Limit the access to your files/directories - Using open_basedir, disable_functions, disable_classes directives in PHP.INI Ex:
; Disable functions disable_functions = exec,passthru,shell_exec,system

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

200

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


; Disable classes disable_classes = DirectoryIterator,Directory

Chapter Exercise: A> Check security for all your projects. B> Using CAPTCHA function for register user page in your projects.

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

201

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

Chapter 17

Advanced PHP Topics


Keywords: config, section, directive, date, time, email, phpmailer, gd, image, color, curl, smarty, template engine. Subjects: 17.1. PHP.INI File Overview 17.2. Date & Time 17.3. Email Sending 17.4. Image Processing 17.5. cURL Library 17.6. Smarty 17.7. Different between PHP5 & PHP4
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

202

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

17.1. PHP.INI File Overview:


17.1.1.Introduction:
- is a PHP configuration file, controls some of the settings of the PHP interpreter. - Use this code to view the contents of php.ini
<?php phpinfo(); ?>

- On Linux, php.ini may be located in:


/etc/php.ini /etc/php/php.ini /etc/php5/php.ini /usr/bin/php5/bin/php.ini

- On Windows, php.ini may be located in:


C:\WINDOWS\php.ini

17.1.2.Directives:
- Directive is a setting for a function/system when running PHP script. - Each directive in php.ini usually has comment. Comment lines begin with comma (,) - You can disable some directives by inserting comma to begin of line, PHP will use the default value for disabled directives. - Format: directive_name = directive_value - Ex:
short_open_tag = On post_max_size = 80M

17.1.3. Sections:
- Group php.ini directives together. - Format: [SECTION_NAME]
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

203

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

- Ex:
[PHP] [MySQL] [Session]

17.1.4. Some important directives:


- error_reporting, display_errors, register_globals, post_max_size,
magic_quotes_gpc, upload_max_filesize, extension

17.2. Date & Time:


17.2.1. Get the current date & time:
- The simplest and most basic thing you'll want to do with PHP's date API is, obviously, get the current date and time. This is best accomplished via the getdate() function, which returns an associative array containing date and time information. - Ex:
$today = getdate(); print_r($today); // Displays Array ( [seconds] [minutes] [hours] [mday] [wday] [mon] [year] [yday] [weekday] [month] [0] )

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

40 58 21 17 2 6 2003 167 Tuesday June 1055901520

17.2.2. Timestamp Introduction:


VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

204

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

- Most of PHP's date functions work on the basis of timestamps. This timestamp is a unique numeric representation of a particular date, calculated as the number of seconds between January 1 1970 and the date and time specified, and makes it easier to perform arbitrary calculations on date and time values. - In PHP, UNIX timestamps are created via the mktime() function, which accepts a series of date and time parameters, and converts them into a timestamp - Ex:
echo mktime(14, 35, 20, 4, 1, 2002); //displays 1017651920

- You can obtain a timestamp for the current moment in time by calling mktime() with no arguments: - you can also use the time() function, which returns the current timestamp

17.2.3. Format date/time output:


- Once you've got yourself a timestamp, you can use the date() function to format it. - This date() function is easily one of the most useful functions in this collection Ex:
echo "It is now " . date("h:i d M Y", mktime());

- Common format characters of date() function (view full list at http://php.net/date):

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

205

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

17.3. Email Sending:


17.3.1. Using function mail() from PHP:
$to = 'nobody@example.com'; $subject = 'the subject'; $message = 'hello'; $headers = 'From: webmaster@example.com' . "\r\n" . 'Reply-To: webmaster@example.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); mail($to, $subject, $message, $headers);

17.3.2. PHPMailer Class: - Download class at: http://phpmailer.worxware.com/


require("phpmailer/class.phpmailer.php"); //change settings here
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

206

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


$your_email = "info@example.com"; $your_smtp = "mail.example.com"; $your_smtp_user = "info@example.com"; $your_smtp_pass = "example_password"; $your_website = "http://example.com"; //get contact form details $name = $_POST['name']; $email = $_POST['email']; $url = $_POST['url']; $comments = $_POST['comments']; $response="Name: $name\nContents:\n$comments\n"; $mail = new PHPmailer(); $mail = $mail->SetLanguage("en", "phpmailer/language"); $mail->From = $your_email; $mail->FromName = $your_website; $mail->Host = $your_smtp; $mail->Mailer = "smtp"; $mail->Password = $your_smtp_pass; $mail->Username = $your_smtp_user; $mail->Subject = "$your_website feedback"; $mail->SMTPAuth = "true"; $mail->Body = $response; $mail->AddAddress($your_email,"$your_website admin"); $mail->AddReplyTo($email,$name); echo "<p>Thanks for your feedback</p>"; if (!$mail->Send()) { echo "<p>Send Email Error. Try again later!</p>"; } $mail->ClearAddresses(); $mail->ClearAttachments();

17.4. Image Processing:


17.4.1. GD Library Introduction:
- The GD library is used for dynamic image creation. From PHP we use with the GD library to create GIF, PNG or JPG images instantly from our code. This allows us to do things such as create charts on the fly, created an an anti-robot security image, create thumbnail images, or even build images from other images.
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

207

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

17.4.2. Useful Image Functions:


Function
imagecreate() imagecreatefromgif() imagecreatefromjpeg() imagecreatefrompng() imagesx() imagesy() imagegif() imagejpeg() imagepng() imagedestroy() imagecopy() imagecopymerge() imagecopyresampled()

Description
Creates a blank image resource of the specified size. Creates an image resource from the specified GIF format file. Creates an image resource from the specified JPEG format file. Creates an image resource from the specified PNG format file. Returns the image's width Returns the image's height Output a GIF image to browser or file Output a JPEG image to browser or file Output a PNG image to browser or file Destroy an image resource, free up memory Copy part of an image Copy and merge part of an image Copy and resize part of an image with resampling

17.4.3. Example:
// File imagethumb.php // Capture GET parameters $source_file = $_GET['image']; $new_width = $_GET['width']; $new_height = $_GET['height']; // Open source image file and get image dimensions $old_image = imagecreatefromjpeg($source_file); $old_width = imagesx($old_image); $old_height = imagesy($old_image); // Create blank image $new_image = imagecreatetruecolor($new_width,$new_height); // Copy and resize old image into new image resource and then return to browser imagecopyresized($new_image,$old_image,0,0,0,0,$ne w_width,$new_height,$old_w idth,$old_height); header('Content-type: image/jpeg'); imagejpeg($new_image);

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

208

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

Called with:
<img src="imagethumb.php?image=test.jpg&width=100&height=75" />

17.5. cURL Library:


17.5.1. cURL Introduction:
- The cURL extension to PHP is designed to allow you to use a variety of web resources from within your PHP script - It lets you use several web protocols using one uniform interface, most notably FTP, FTPS, HTTP, HTTPS, GOPHER, TELNET, and LDAP. - The basic premise to using Curl is that there are four steps: initialize cURL, set your options, execute your query, and close Curl. - Curl is very configurable, and there are dozens of options you can set to make it do all sorts of things.

17.5.2. Using cURL:


$ch = curl_init(); curl_setopt($ch,CURLOPT_URL,"http://example.com/login.php"); curl_setopt($ch, CURLOPT_REFERER, "http://www.google.com/"); curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0"); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, "Username=johndoe&Password=1234&Submit=Go%21"); $result = curl_exec ($ch); curl_close($ch);

17.6. Smarty:
17.6.1. Smarty Introduction:
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

209

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

- Written in PHP - Is a Template Engine - Many features: . No parsing overhead . Extensible : functions, modifiers . Control statements . Can embed php code in template . Caching . Output filtering

17.6.2. Using Smarty:


- Installation: download at http://www.smarty.net/ - File structure:
/www.example.com/smarty/ Smarty.class.php
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

210

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


Smarty_Compiler.class.php Config_File.class.php debug.tpl internals/*.php plugins/*.php /www.example.com/ smarty/ templates/ templates_c/ configs/ cache/

17.6.3. Example:
require 'Smarty.class.php'; $smarty = new Smarty; $smarty->assign('Username', 'John Doe'); $smarty->display('index.tpl');

- index.tpl file
<html> <body> Welcome {$Username} </body> </html>

17.7. Different between PHP5 & PHP4:


17.7.1. Language Features:
- allows limited type hinting. - foreach support by-reference declaration - A number of new functions, particularly for string and array manipulation

17.7.2. OOP:
- all objects are passed by reference
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

211

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

- defines constant within the scope of a class - class methods and properties support visibility: public, private, protected - using clone mechanism to copy objects. - using __construct() and __destruct() - interfaces and abstract classes - lazy loading using __autoload()

17.7.3. New Extensions:


- SimpleXML, DomXML - PHP Data Object (PDO) - Standard PHP Library(SPL) - Reflection extension

17.7.4. Error Management:


- Classes support exceptions - E_STRICT error reporting level : emit notices when legacy or deprecated code is encountered.

Chapter Exercise: Using image functions to enhanced the photo editing page of current project. Ex: resize, crop, create thumbnail, add watermark

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

212

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

Chapter 18

Design Pattern
Keywords: design, singleton, factory, strategy, MVC, Model-ViewController, business logic, presentation, request, response. Subjects: 18.1. Fundamentals 18.2. Singleton Pattern 18.3. Factory Pattern 18.4. Strategy Pattern 18.5. Model-View-Controller (MVC) Pattern

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

213

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

18.1. Fundamentals:
18.1.1. Design Pattern Theory:
- In software engineering, a design pattern is a general repeatable solution to a commonly occurring problem in software design. - It is a description or template for how to solve a problem that can be used in many different situations.

18.1.2. Popular Design Patterns:


18.1.2. 1. Creational design patterns: is all about class instantiation. Ex: Abstract Factory, Builder, Factory, Object Pool, Prototype, Singleton 18.1.2.2. Structural design patterns: about Class and Object composition. Ex: Adapter, Bridge, Composite, Decorator, Faade, Flyweight, Private Class Data, Proxy 18.1.2.3. Behavioral design patterns: about Class's objects communication. Most specifically concerned with communication between objects. Ex: Chain of responsibility, Command, Interpreter, Iterator, Null Object, Observer, Strategy

18.2. Singleton Pattern:


18.2.1. Singleton Pattern Introduction:

- Ensure that only one instance of a class is created and provide a global access point to the object. - Singleton pattern should be used when we must ensure that only one instance of a class is created and when the instance must be available through all the code. A special care
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

214

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

should be taken in multithreading environments when multiple threads must access the same resources through the same singleton object. - There are many common situations when singleton pattern is used: - Logger Classes - Configuration Classes - Accessing resources in shared mode

18.2.2. Implement Singleton Pattern in PHP:


class Singleton { protected static $_instance; // don't permit an explicit call of constructor! protected function __construct(){ } public static function getInstance() { if( self::$_instance === NULL ) self::$_instance = new self(); return self::$_instance; } }

18.3. Factory Pattern:


18.3.1. Factory Pattern Introduction:

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

215

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

- Creates objects without exposing the instantiation logic to the client and refers to the newly created object through a common interface. - Factory pattern should be used when: - a framework delegate the creation of objects derived from a common superclass to the factory - we need flexibility in adding new types of objects that must be created by the class - Along with singleton pattern the factory is one of the most used patterns. Almost any application has some factories.

18.3.2. Implement Factory Pattern in PHP:


interface IProduct { function calWeight(); function say(); } class ProductLaptop implements IProduct { function calWeight(){} function say() { echo 'I am a laptop'; }
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

216

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


} class ProductDesktop implements IProduct { function calWeight(){} function say(){} } class ProductFactory { const PROD_DESK = 1; const PROD_LAP = 2; public static function getProduct($type = self::PROD_LAP) { switch($type) { case self::PROD_DESK : return new ProductDesktop(); break; case self::PROD_LAP : return new ProductLaptop(); break; default: throw new Exception('Not found.'); } } } $obj = ProductFactory::getProduct(ProductFactory::PROD_LAP); $obj->say();

18.4. Strategy Pattern:


18.4.1. Strategy Pattern Introduction:

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

217

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

- Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it. - Capture the abstraction in an interface, bury implementation details in derived classes.

18.4.2. Implement Strategy Pattern in PHP:


interface IStrategy { function getPoint($point = 0); } class StrategyHappy implements IStrategy { function getPoint($point = 0) { return ++$point; } } class StrategySad implements IStrategy { function getPoint($point = 0) { return --$point; } } class Student { private $point;
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

218

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477


function __construct($point = 0) { $this->point = $point; } function tellPoint($strategy) { $newPoint = $strategy->getPoint($this->point); echo 'My point is ' . $newPoint; } } $studentA = new Student(9); $studentA->tellPoint(new StrategyHappy()); $studentB = new Student(9); $studentB->tellPoint(new StrategySad());

18.5. Model-View-Controller (MVC) Pattern:


18.5.1. MVC Pattern Introduction:

- Modelviewcontroller (MVC) is an architectural pattern used in software engineering. Successful use of the pattern isolates business logic (or other program logic) from the user interface, permitting one to be freely modified without affecting the other.
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

219

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

- The Model is how your data is going to be represented. This is usually in the form of a relational database (MySQL). - We use a Controller to interact and query the data within the Model layer. The controller also sends data to the view. Some people refer to the Controller as the business logic within a software system. - The View is a way to represent or serve up the data manipulated by the controller from the model. The view is typically what the end user interacts with, often times in the form of a web page.

18.5.2. MVC Framework Overview:

- Some popular PHP MVC Framework: Framework PHP Multiple DB ORM Ver. CakePHP 4,5 x x CodeIgniter 4,5 x Prado 5 x x Symfony 5 x x Zend 5 x x

Template

Cache x x x x x

Validation x x x x x

Ajax x x x x

x x

- Multiple DB: Indicates whether the framework supports multiple databases without having to change anything.
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

220

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

- ORM: Indicates whether the framework supports an object-record mapper, usually an implementation of ActiveRecord. - Template: Indicates whether the framework has an inbuilt template engine. - Cache: Indicates whether the framework includes a caching object or some way other way of caching. - Validation: Indicates whether the framework has an inbuilt validation or filtering component. - Ajax: Indicates whether the framework comes with inbuilt support for Ajax.

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

221

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

Chapter 19

E-Commerce Website
Keywords: ecommerce, shopping cart, payment, order, optimization, search engine, SEO, backend, frontend, web analytic, google. Subjects: 19.1. E-Commerce Fundamentals 19.2. Website Optimization 19.3. SEO Basics 19.4. Website Analytic Google Analytic

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

222

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

19.1. E-Commerce Fundamentals:


- consists of the buying and selling of products or services over electronic systems such as the Internet and other computer networks. - Features of an ecommerce website: Online Shopping Cart Secure Credit Card Facility (SSL) Online Payment Option Offline Payment Options Payment Gateway Interface Member Accounts Subscription Options Customised Data Collection & Reporting Multiple Currencies Automated Electronic Invoice & Receipts System Freight Management Order Management Integration with Inventory Management & Accounting Systems Integration with Email Marketing Systems

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

223

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

19.2. Website Optimization:


19.2.1. Front-end Optimization:

19.2.2. Back-end Optimization: - Code Optimize


VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

224

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

- Query Optimize - Caching

19.3. SEO Basics:


19.3.1. Introduction:
- Short for search engine optimization, the process of increasing the amount of visitors to a Web site by ranking high in the search results of a search engine. The higher a Web site ranks in the results of a search, the greater the chance that that site will be visited by a user. It is common practice for Internet users to not click through pages and pages of search results, so where a site ranks in a search is essential for directing more traffic toward the site. - SEO helps to ensure that a site is accessible to a search engine and improves the chances that the site will be found by the search engine.

19.3.2. Some SEO Techniques:


1. The Meta Keywords, Description and Robots tag Google used description copy to market your site in its results, treat this as optimized sales copy. Make sure your sitemap.xml page is CONSTANTLY called up to the search engines 2. The Title Tag - The MOST important aspect of on-page SEO, just take our word for it. 3. The Body Text (focus on the body text in bold, for this denotes strong emphasis to the search engines) 4. The first sentence in the body text and the first words used per sentence are the most important ones for advanced on-page SEO necessities (Make it humanly readable and SE readable The words used in the first sentence are most important due to the implementation of Googles LSI algorithm) 5. The URL The subdirectory folder and page of content should be SEOd (i.e. http://domain.com/real-estate/real-estate-marketing-ideas.com would fetch a high ranking for a page dedicated to real estate marketing ideas - especially with many highly authoritative, relevant, deep in-bound links) 6. The H1 and H2 Texts are highly important - Why? They show the search engine the main subjects and Table of Contents for the content to be indexed. Make these keyword friendly and reflective of your pages title tag. 7. Same Site Link Texts The links connecting the pages of your site together must have your targeted keyword terms in them as well as all links throughout the site
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

225

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

even though it seems excessive, having variations to your targetted keywords would also help when linking out to other pages within your site. 8. Same-Site Link URLs Not only should you be using your keywords to describe pages within your site, those URLs you link to must have SEO URLs ( eg: http://domain.com/your-keyword.html) 9. Outbound Link Text Resources you link to must be SEOd - If you are an internet marketing site and are linking to an email marketing company (email marketing software in this instance), you would use Put your internet marketing on auto-pilot and use the best tool for internet marketers today - internet marketing email software. Then just use other variants to internet marketing. 10. IMG Alt Tags Your images should be described via ALT Tags with the keywords you are optimizing for - If your image is hosted on your web-host, the file name of the images should also be SEOd If you have an image about polar bears have it be polar-bear.jpg in your images folder. 11. Keyword Density 8% is excellent and doesnt seem spammy, if you have a 500 word article, then 40 of those words should have variances of the search term you are targeting, if this seems excessive, lower the keyword density down to 5% and you will only need to add 25 variances/instances of your keyword. And thats just a start (Keyword prominence is big, but not worth a discussion). 12. Lastly and surprisingly, Your HTML comments should have your SEO terms in them (!!) As a question to the relevancy this has to your ranking, I am unsure, but most of the large sites have html comments connected to their search terms. If you end up doing an analysis of your on-page content, you can find out if the high ranked sites for your keyword use HTML comments tagged to the keyword(s) being targeted.

19.4. Website Analytic Google Analytic:


- Google Analytics is one of the best tools out there for analyzing traffic on your website.

19.4.1. Setup Account:


1. Go to Google Analytics. 2. If you do not have a Google account, click Sign Up Now, to the left of the sign-in box. This will take you to a page where you can sign up for a Google account.

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

226

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

3. If you have a Google account, use your email address and password to sign in. 4. Click the Sign Up button to continue.

5. In the next window, provide Google with the URL of the site you wish to analyze.

6. Give the site an account name that is easy to remember. If you will be tracking multiple sites, this is especially important. 7. Select the country your site is based in, or the country it is serving. Then select the appropriate time zone.
o

If your site is based in India but all your users are in the U.S., you may want to select a U.S. time zone to figure out when in their day most choose to use your

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

227

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

site - or you may want to set it to your city's time zone to see when you need the most workers on staff. 8. Click Continue. 9. In the next window, provide your contact information. 10. Click Continue. 11. In the next window, read the Google Analytics terms of service. If you agree with them, click the Yes box. 12. Click Create New Account. 13. Google will provide you with a block of code. Copy this - you'll need to insert it into your web site.

19.4.2. Embed Google Analytics JavaScript Into Pages


1. Find the </body> tag at the very bottom, just above the </html> page. 2. Do you see the code urchinTracker(), utmLinker(), utmSetTrans(), or utmLinkPost() above the </body> tag? If so, you must paste the Google Analytics Javascript above that code. If not, paste it immediately above the </body> tag. 3. If you have templates, insert the code into them as well. 4. Once you have uploaded the pages back to your site, you can begin tracking information!

19.4.3. WebSite Analytic


VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

228

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

1. Log in to Google Analytics. 2. In the center of the page is a section titled Website Profiles. Click on the View Reports link to the right of the name of the site you're interested in. This will bring you to the Dashboard.

3. At the top of the page is a chart that gives a visual representation of your site traffic over the past month.
o

This chart will only give you data from the time you inserted the tracking code into your pages. If you want to change the span of time the chart displays, click on the dates in the upper right-hand corner. Click on dates in the calendar that is revealed or manually type in dates to view a different span of time. To compare traffic over two different time periods, select one date range you want to use, click Compare to Past, and select the range you wish to compare it against. Just below the dates is a menu that says Visits. Click on it to change the graph to pageviews (how many times the pages on your site have been viewed), pages per visit (how many pages on your site users visited on average), average time on site (how long each user spent on your site), bounce rate (what percentage of
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

229

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

users left after visiting only one page), or percentage of new visits (how many visitors had never been to your site before).

4. Immediately beneath that chart, you'll see a header that says Site Usage, with six small charts underneath. Under Site Usage, you'll find quick information on various site traffic statistics for the time period shown in the main chart. Each one has an individual chart.
o

Visits tells you how many visits there were to your page. A visit is defined as a page view when that user has viewed no other page on your site in the past half hour. Pageviews tells how many times the pages on your site have been viewed. Pages/visit tells how many pages, on average, users view when they come to your site. Bounce Rate tells what percentage of users left after viewing only one page on your site. Avg. Time on Site shows how long each user spent on your site. New Visits shows what percentage of your users have not visited your site before.

o o

o o

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

230

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

231

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

5. The Visitors Overview graph shows how many visitors have come to your site.
o

This number is usually lower than the Visits statistic, sometimes a lot lower, because some visitors may visit your site over and over again. Click on View Report to view more detailed information about your visitors.

6. "Map Overlay" displays what countries your visitors are coming from.
o o

The darker the green, the more visitors come from that country. Click View Report to get in-depth information on where your visitors come from.

7. Traffic Sources Overview shows which percentage of users are getting to your site by typing your URL directly into their browser, and via search engines, referring sites, and other avenues such as emailed links.
o

Click on View Report to get breakdowns of exactly what places your users are coming from, and what keywords they're looking for.

8. Content Overview specifies the top five most viewed pages over the time period you're looking at.
o

Click on the name of any page to get extremely detailed information about where the people viewing that page came from, how long they spent on the page, how many of them were new to the page, and a lot more. Click on View Report to get access to information about the performance of all pages on the site.

19.4.4. See How Website Site Is Performing Daily and Hourly


1. In the menu to the left, click on the word Visitors.

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

232

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

2. To the left beneath the main chart, you'll see a number of different statistical breakouts.

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

233

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

3. Click on any of the words to get a bar-chart breakout of the daily performance for that aspect of site traffic measurement. 4. If you want to learn hour-by-hour trends, click on the word Hourly above the bar chart to see an hour by hour graph for the time period at hand. 5. To compare two different time periods, click on the dates above the line graph. Select the first set of dates you want to work with, check the Compare to Past box, click on the second set of dates, and click the Apply Range button.

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

234

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

19.4.5. See Where Your Traffic Comes From


1. In the lower right-hand corner of the Dashboard you'll find your site's top 5 mostaccessed pages. Click on any of these.

2. Below the chart on the right hand side, you will see a heading labeled Landing Page Optimization. Click on the link beneath it labeled Entrance Sources.

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

235

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

3. Beneath the chart, you'll see a table. This table lists all the places your users came from to visit your site.

In the first column to the right of the source name is the number of pageviews your page received from that source. The next column tells how many of those were unique pageviews - someone coming to your page who had not been to that page before in the time frame you're reviewing. Time on Page tells you how much time, on average, users from that particular source spent on the page in question. Bounce Rate shows how many people from that specific source left your site after looking at that page, without viewing another page. % Exit shows how many people from that specific source went to another site from that page. (This number may be lower than the Bounce Rate number; if they close the window or shut down their browser, it is not considered exiting.) When you set up certain financial measurements in the Goals section, Google will crunch the numbers to show you how much return you're getting with the $ Index column.
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

236

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

4. If you want to get information on other pages, under the Content menu on the right, click on the Content by Title menu item. You can now go through all of your content to learn information on every page! 5. Return to the main dashboard by clicking on the word Dashboard in the upper-left corner. Course Project: Write a complete e-commerce website with: Function requirement: 1. Support Shopping cart 2. Email ordering 3. Have Administration Control Panel 4. Have User registration/login/forgot password function 5. User can manage orders if logins, purchases products and checks out. 6. Security website 7. SEO Coding requirement: 1. Using MVC Framework (OOP) 2. Using PDO 3. Using Smarty

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

237

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

Chapter 20

Zend PHP 5 Certification - ZCE


Keywords: zce, zend, test, vulcan, mock test, exam, engineer, certification, certified, Pearson Vue, Yellow page. Subjects: 20.1. Zend Certification Introduction 20.2. Zend PHP 5 Certification Exam

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

238

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

20.1. Zend Certification Introduction:


20.1.1. Zend Certification Type:
- Zend PHP 5 Certification - Zend Framework Certification

20.1.2. PHP Yellow Pages:

20.1.3. Zend Certificate

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

239

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

ZCE Logo

20.2. Zend PHP 5 Certification Exam:


20.2.1. PHP Exam Contents:

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

240

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

20.2.2. Exam Information :


- Tesing Center: Pearson VUE - Price: $125 - 70 questions with 3 types: A multiple-choice question with only one right answer.
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

241

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

A multiple-choice question with multiple correct answers. A free-form question for which the answer must be typed in. - Test duration: 90 minutes

20.2.3. Exam Practice Resources :


- PHP Manual - Books - Mock Test

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

242

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

Good luck!

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

243

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

Further Reading:
1. Core PHP programming, 3rd Edition (Prentice Hall 2003) Leon Atkinson, Zeev Suraski 2. PHP 5 for Dummies (For Dummies 2004) - Janet Valade. 3. Object-Oriented Programming with PHP5 (Packt Publishing 2007) - Hasin Hayder. 4. Beginning PHP 5 and MySQL E-Commerce : From Novice to Professional (Apress 2004) - Cristian Darie, Mihai Bucica. 5. Professional PHP 6 (Wrox 2009) - Ed Lecky Thompson, Steven D. Nowicky, Thomas Myer. 6. Advanced PHP Programming (Sams 2004) - George Schlossnagle. 7. Learning PHP Data Objects (Packt Publishing 2007) - Dennis Popel. 8. Smarty PHP Template Programming and Application (Packt Publishing 2006) - Joao Prado Maia, Hasin Hayder, Lucian Gheorghe. 9. Head First Design Patterns (O'Reilly 2009) - Elisabeth Freeman, Eric Freeman, Bert Bates, Kathy Sierra. 10. Php|architect's Guide to PHP Design Patterns (php|architech 2005) - Jason E. Sweat. 11. MySQL, 4th Edition (Addison Wesley 2008) - Paul Dubois. 12. Professional Web 2.0 Programming (Wiley Publishing 2007) - Eric van der Vlist, Alessandro Vernet, Erik Bruchez, Joe Fawcett, Danny Ayers. 13. The Essential Guide to CSS and HTML Web Design (friends of ED 2007) Craig Grannell 14. Pro CSS Techniques (Apress 2006) - Jeff Croft, Ian Lloyd, Dan Rubin. 15. Javascript Bible, 6th Edition (Wiley Publishing 2007) Danny Goodman, Michael Morrison 16. Learning jQuery (Packt Publishing 2007) - Jonathan Chaffer, Karl Swedberg. 17. Search Engine Optimization : An Hour a Day (Wiley Publishing 2006) - Jennifer Grappone, Gradiva Couzin. 18. Head First Software Development (O'Reilly 2008) - Dan Pilone, Russ Miles.
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

244

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

19. How to Break Web Software (Addison-Wesley Professional 2006) - Mike Andrews, James A. Whittaker. 20. HTTP Essential Protocols for Secure, Scaleable Web Sites (John Wiley & Sons 2001) Stephen A. Thomas.

Useful Websites:
1. http://php.net/ 2. http://talks.php.net/ 3. http://zend.com/ 4. http://www.smarty.net/ 5. http://www.phpdeveloper.org/ 6. http://www.phpclasses.org/ 7. http://phpbuilder.com/ 8. http://mysql.com/ 9. http://www.w3schools.com/ 10. http://developer.yahoo.com/ 11. http://www.google.com/webmasters/ 12. http://www.seomoz.org/ 13. http://www.smashingmagazine.com/ 14. http://templatemonster.com/ 15. http://jquery.com/ 16. http://www.alistapart.com/ 17. http://www.cssplay.co.uk/ 18. http://knowfree.net/ 19. http://ha.ckers.org/ 20. http://www.riapedia.com/
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

245

THNH VIN HI P H I AN TON THNG TIN VI T NAM- VNISA

WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

Textbook Author:
Full Name: Vo Duy Tuan Email: tuanmaster2002@yahoo.com Phone: 0938 916 902 Website: http://bloghoctap.com/

VO DUY TUAN

PHP Beginner & Intermediate ATHENA INFORMATION TRAINING

246