Professional Documents
Culture Documents
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
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
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
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
Chapter 1
VO DUY TUAN
VO DUY TUAN
VO DUY TUAN
VO DUY TUAN
VO DUY TUAN
10
VO DUY TUAN
11
VO DUY TUAN
12
VO DUY TUAN
13
VO DUY TUAN
14
VO DUY TUAN
15
VO DUY TUAN
16
- Auto-complete function
17
Or:
VO DUY TUAN
18
Or:
VO DUY TUAN
19
VO DUY TUAN
20
- Manage Site Files: In the Files Panel, right click the root (top level) and select your function (New File, New Folder)
VO DUY TUAN
21
VO DUY TUAN
22
23
</body> </html>
24
25
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>
VO DUY TUAN
26
27
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
- 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
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>
30
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
VO DUY TUAN
32
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
33
- 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
34
VO DUY TUAN
35
VO DUY TUAN
36
VO DUY TUAN
37
VO DUY TUAN
38
VO DUY TUAN
39
2.3.3. Restart/ Stop / Start Apache / MySQL Services using start menu:
VO DUY TUAN
40
VO DUY TUAN
41
VO DUY TUAN
42
VO DUY TUAN
43
VO DUY TUAN
44
VO DUY TUAN
45
VO DUY TUAN
46
2.5.2. Installation:
- Download at: http://www.hping.org/phpinteractive/ - Unzip and copy to www folder and rename to "phpa".
VO DUY TUAN
47
VO DUY TUAN
48
VO DUY TUAN
49
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
50
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
<?php
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
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
3.4. Operators:
3.4.1. Assignment Operator: assigning data to variables. Ex:
$a = 1; // Assign the integer 1 to $a
54
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:\"
is used to determine whether a PHP variable is an instantiated object of a certain class. Ex:
echo $a instanceof MyClass;
VO DUY TUAN
55
VO DUY TUAN
56
VO DUY TUAN
57
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
58
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
59
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
60
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
- 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; }
62
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"
63
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"
// Display "3"
- Using $GLOBALS $a = 1; $b = 2;
variable. Ex:
VO DUY TUAN
64
// 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)
VO DUY TUAN
65
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
66
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
67
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();
68
69
- 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
// 0: 1: 2:
Outputs: a b c
70
- 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
Order of sort
Related functions
Low to high High to low Low to high High to low Natural Natural, case insensitive Low to high High to low
VO DUY TUAN
71
User defined User defined User defined Random First array or sort options
sort($fruits); foreach ($fruits as $key => $val) { echo "fruits[" . $key . "] = " . $val . "\n"; } // Outputs: fruits[0] = fruits[1] = fruits[2] = fruits[3] =
VO DUY TUAN
72
remove an element from array using queue and stack operation. STACK OPERATION
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING
73
QUEUE OPERATION
VO DUY TUAN
74
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
75
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
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
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.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
78
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.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().
79
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"
80
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).
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.1. Introduction:
VO DUY TUAN
81
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
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.
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
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
84
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
85
86
Ex:
$firstName = $_POST['FirstName']; $salary = $_POST['Salary']; $contractor = $_POST['Contractor'];
87
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
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
88
302 304
400
Bad request
401
Unauthorized
404
Not Found
500 502
503
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
- PHP script:
$nameA = $_FILES[myfile]['name'][0]; $tmpnameA = $_FILES[myfile][tmp_name][0];
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING
90
7.3. Cookie:
7.3.1. How cookies work:
91
7.4. Session:
7.4.1. How sessions work:
VO DUY TUAN
92
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.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 />";
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
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
94
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
95
- 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.
96
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
97
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
99
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
101
VO DUY TUAN
102
+ 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
103
+ 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
- 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
106
- 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()
107
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
108
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
109
a a+ x
x+
110
- 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.
Function file_exists()
Handle
is_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
rewind()
Yes
file_get_contents()
VO DUY TUAN
111
Ex:
$contents = file_get_contents('config/text.txt');
chmod()
copy()
rename()
filesize()
unlink()
filemtime()
pathinfo()
112
9.3. Directory:
9.3.1. Open directory handle:
$dh = opendir('uploads/photos/');
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.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
closedir($handle); }
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
114
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
115
VO DUY TUAN
116
VO DUY TUAN
117
VO DUY TUAN
118
- SQLyog:
VO DUY TUAN
119
10.2.2.2. Shell:
120
10.2.2.4. phpMyAdmin:
VO DUY TUAN
121
- Ex:
CREATE DATABASE employee
- 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
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" :
123
- Ex:
SELECT * FROM countries ORDER by iso_code IN ('UK', 'US') DESC SELECT *, COUNT(field) FROM table GROUP BY field HAVING COUNT(count)>=1;
- Ex:
UPDATE items, month SET items.price = month.price WHERE items.id = month.id;
- Syntax:
DELETE FROM table_name WHERE LIMIT
- Ex:
DELETE FROM users
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING
124
- Ex:
DROP DATABASE mydbtest
VO DUY TUAN
125
VO DUY TUAN
126
VO DUY TUAN
127
VO DUY TUAN
128
129
- Select the table you want to insert value - Click the INSERT tab to begin insert data
VO DUY TUAN
130
131
- In the Editing page, update your value, and click Go button to save.
VO DUY TUAN
132
VO DUY TUAN
133
- Delete multiple rows by click the checkbox before each row, after that, click the Delete icon ( ) followed the data tables.
VO DUY TUAN
134
VO DUY TUAN
135
VO DUY TUAN
136
VO DUY TUAN
137
VO DUY TUAN
138
139
- 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()); }
mysql_fetch_row()
mysql_fetch_array()
mysql_num_rows()
VO DUY TUAN
140
mysql_affected_rows()
mysql_real_escape_string()
mysql_insert_id()
mysql_free_result()
Chapter Exercise: Edit the website at Chapter 9, using MySQL Database instead of Files to store user information.
VO DUY TUAN
141
Chapter 11
VO DUY TUAN
142
VO DUY TUAN
143
VO DUY TUAN
144
- 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.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.
VO DUY TUAN
145
VO DUY TUAN
146
147
- 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
148
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
149
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
- 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
VO DUY TUAN
152
- 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';} }
153
154
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
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
VO DUY TUAN
157
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
158
13.1.1. Introduction
- Combines records from two or more tables in a database.
Or:
SELECT * FROM employee, department WHERE employee.DepartmentID = department.DepartmentID
VO DUY TUAN
159
VO DUY TUAN
160
VO DUY TUAN
161
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';
162
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");
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
VO DUY TUAN
164
Chapter 14
VO DUY TUAN
165
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
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
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?
VO DUY TUAN
168
- System boundary: A system boundary defines the scope of what a system will be
VO DUY TUAN
169
- 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
170
VO DUY TUAN
171
VO DUY TUAN
172
- ConceptDraw
VO DUY TUAN
173
-StarUML (Freeware):
14.2.5. Example:
VO DUY TUAN
174
VO DUY TUAN
175
- 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
176
VO DUY TUAN
177
- 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
178
Chapter 15
VO DUY TUAN
179
VO DUY TUAN
180
15.1.3. Valid XML: Well-formed & follow Document Type Definition (DTD) or XML
Schema(XSD):
181
"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)>
182
addAttribute()
attributes()
children()
getName()
xpath()
VO DUY TUAN
183
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.4. SOAP:
15.4.1. Enable SOAP Extension in PHP5:
- Edit file PHP.INI, uncomment line extension for php_soap
184
VO DUY TUAN
185
<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>
186
187
VO DUY TUAN
188
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
189
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
190
191
- Limit the permissions. - Filter user input - Using prepared statements - Hide database errors.
Solution: - Configure right setting for logging, display error - Catch exception when error
Solution:
- Strong password - Set Access-Rule for files, directories - Publish files/directories when needed.
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING
192
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.
VO DUY TUAN
193
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)
194
Solution:
- Filter All Input - Escape All Output - Only Allow Safe Content
VO DUY TUAN
195
VO DUY TUAN
196
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
197
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
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
VO DUY TUAN
200
Chapter Exercise: A> Check security for all your projects. B> Using CAPTCHA function for register user page in your projects.
VO DUY TUAN
201
Chapter 17
202
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
- Ex:
[PHP] [MySQL] [Session]
=> => => => => => => => => => =>
204
- 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
VO DUY TUAN
205
206
207
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
208
Called with:
<img src="imagethumb.php?image=test.jpg&width=100&height=75" />
17.6. Smarty:
17.6.1. Smarty Introduction:
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING
209
- 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
210
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.2. OOP:
- all objects are passed by reference
VO DUY TUAN PHP Beginner & Intermediate ATHENA INFORMATION TRAINING
211
- 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()
Chapter Exercise: Using image functions to enhanced the photo editing page of current project. Ex: resize, crop, create thumbnail, add watermark
VO DUY TUAN
212
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
213
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.
- 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
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
VO DUY TUAN
215
- 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.
216
VO DUY TUAN
217
- 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.
218
- 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
- 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.
- 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
- 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
221
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
222
VO DUY TUAN
223
224
225
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.
VO DUY TUAN
226
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
227
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.
228
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
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
230
VO DUY TUAN
231
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.
VO DUY TUAN
232
2. To the left beneath the main chart, you'll see a number of different statistical breakouts.
VO DUY TUAN
233
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
234
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
235
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
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
237
Chapter 20
VO DUY TUAN
238
VO DUY TUAN
239
ZCE Logo
VO DUY TUAN
240
241
A multiple-choice question with multiple correct answers. A free-form question for which the answer must be typed in. - Test duration: 90 minutes
VO DUY TUAN
242
Good luck!
VO DUY TUAN
243
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
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
Textbook Author:
Full Name: Vo Duy Tuan Email: tuanmaster2002@yahoo.com Phone: 0938 916 902 Website: http://bloghoctap.com/
VO DUY TUAN
246