giaotrinhphp2009 voduytuan final 111201213145 phpapp02
TRANSCRIPT
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 3
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
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
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 4
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
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
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 5
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
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
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 7
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
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 9
1.1. Web Design Toolbox:
1.1.1. Image Manipulating: Photoshop, GIMP, Illustrator…
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 11
1.1.2. Animation Creator: Photoshop, Flash, Flex, Maya, 3DS Max…
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 13
1.1.3. HTML Editor: Dreamweaver, Notepad++…
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 14
1.1.4. CSS Editor: Dreamweaver, Rapid CSS, Notepad++…
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 15
1.1.5. Javascript Editor: Dreamweaver, 1st Javascript Editor, Notepad++…
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 16
1.2. HTML Editor – Dreamweaver CS3:
- Main Dreamweaver CS3 interface
- Auto-complete function
- Collapse selected script:
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 17
- Property Inspector Panel:
- Create a Local Site:
Or:
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 18
Or:
- After creating site, the FILES panel will become:
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 19
- Open an Local Site:
- Manage Site Files: In the Files Panel, right click the root (top level) and select your function
(New File, New Folder…)
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 22
1.3. HTML Basics:
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>
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 23
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
- 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:
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 24
1.4.2. Form Elements:
1.4.2.1. Text Field:
<form method="post" action="mailto:[email protected]">
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:[email protected]">
Name: <input type="text" size="10" maxlength="40" name="name">
<br />
Password: <input type="password" size="10"
maxlength="10" name="password"><br />
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 25
<input type="submit" value="Send">
</form>
1.4.2.3. Radio button:
<form method="post" action="mailto:[email protected]">
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 type="radio" name="size" value="small">Small
<input type="radio" name="size" value="medium">Medium
<input type="radio" name="size" value="large">Large <br />
<input type="submit" value="Email Myself">
</form>
1.4.2.4. Check box:
<form method="post" action="mailto:[email protected]">
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:[email protected]">
College Degree?
<select name="degree">
<option>Choose One</option>
<option>Some High School</option>
<option>High School Degree</option>
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 26
<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:[email protected]">
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>
<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:[email protected]">
<textarea rows="5" cols="20" name="comments">
Enter Comments Here
</textarea>
<input type="submit" value="Email Yourself">
</form>
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 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…
- 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>
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 28
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');" />
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>
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 29
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;
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++;
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 30
// 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>
<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>
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 31
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
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 33
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"
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 34
interacting via browser
Working via CLI (command-line interface)
Working via GUI(Graphical User Interface) – Desktop Application
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 35
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.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 37
2.3. Using AppServ:
2.3.1. AppServ 2.10 Directory Structure:
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 38
2.3.2. Edit Server config using start menu:
2.3.3. Restart/ Stop / Start Apache / MySQL Services using start menu:
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)
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 39
- Some main features:
+ Autocomplete code:
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 40
+ Full screen support
+ Database Client
+ Support HTML, CSS, JS language
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 42
+ Debuging & Profiling tool
+ 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.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 43
2.5.2. Installation:
- Download at: http://www.hping.org/phpinteractive/
- Unzip and copy to www folder and rename to "phpa".
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 44
- Access php interactive using URL: http://localhost/phpa/
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 45
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
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 47
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
output…Most 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
*/
Function foo($bar){}
<?php //this is the end tag "?>" of PHP ?>
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 48
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
3.2.7.Type casting: can be done automatically or manually.
Ex: $a = 1.5; $b = (int)$a; // $b will be assigned 1
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 49
3.3. Variable & Constant:
3.3.1. Variables:
- Can contain any type of data, such as strings, integers, objects, arrays…PHP 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 $
- It's usually defined constants using only upper-case names.
- Examples:
define('EMAIL', '[email protected]');
echo EMAIL; // Displays '[email protected]'
define('5CLASS, 'some value); // Invalid name
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 50
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:
$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++; // Outputs 1, $a is now equal to 2
echo ++$a; //Outputs 3, $a is now equal to 3
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 51
3.4.10. Type Operators: instanceof operator 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:
3.5. Control Structure:
3.5.1. Conditional Structures:
3.5.1.1. If…Else Statement:
if (condition_1) {
statement_1
}
[elseif (condition_2) {
statement_2
}]
...
[elseif (condition_n_1) {
statement_n_1
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 52
}]
[else {
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. Do…While Loop:
do
{
code to be exected;
}
while (condition);
3.5.2.3. For Loop:
for (initialization; condition; increment)
{
code to be executed;
}
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 53
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 />";
}
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?
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 55
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
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 57
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 • Don’t require calling external libraries • Don’t 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()
{
echo 'Hello World';
}
hello(); // Displays "Hello World";
HeLLo(); // Displays "Hello World";
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 58
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)
{
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:
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 59
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?
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()
{
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 60
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 variable. Ex:
$a = 1;
$b = 2;
function Sum()
{
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}
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()
{
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 61
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.
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
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 63
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
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 65
5.1. Declaration:
5.1.1. Declare an array variable:
$a = array(10, 20, 30);
$a = array('a' => 10, 'b' => 20, 'key' => 30);
$a = array(5 => 1, 3=> 2, 1=>3, );
$a = 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
)
)
- Using var_dump() can print more than one array.
$a = array ('a' => 'apple',
'b' => 'banana',
'c' => array ('x', 'y', 'z'));
$b = array('x', 'y');
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 66
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.
- 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
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 67
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(), current(), next(), prev(), reset(), end()
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);
}
// Outputs:
0: a
1: b
2: c
� It's not a common way for iteration array.
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, "
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 68
- 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 Sorts by Maintains key
association
Order of sort Related functions
sort() Value No Low to high rsort()
rsort() Value No High to low sort() asort() Value Yes Low to high arsort() arsort() Value Yes High to low asort()
natsort() Value Yes Natural natcasesort() natcasesort() Value Yes Natural, case
insensitive
natsort()
ksort() Key Yes Low to high asort()
krsort() Key Yes High to low ksort()
usort() Value No User defined uasort() uasort() Value Yes User defined uksort() uksort() Key Yes User defined uasort()
shuffle() Value No Random array_rand() array_multisort() Value Associative
yes, numeric
no
First array or
sort options
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";
}
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 69
// Outputs:
fruits[0] = apple
fruits[1] = banana
fruits[2] = lemon
fruits[3] = 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] = apple
fruits[d] = banana
fruits[a] = lemon
fruits[c] = orange
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] = lemon
fruits[b] = apple
fruits[c] = orange
fruits[d] = banana
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 70
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
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 71
QUEUE OPERATION
Chapter Exercise:
A> Can we use arithmetic operator (+, -, *, /) between 2 arrays. If yes, what is the result?
B> Simulate the game "Đánh bài Tiến lên" 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 thông" in 13 cards of each
person.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 73
Chapter 6
String
Manipulation Keywords: string, haystack, needle, text, character, case-sensitive, case-
insensitive, 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
6.7. Regular Expression – RegEx
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 75
6.1. Declaration:
6.1.1. Normal Assignment:
1. $a = "Using double quote";
2. $b = 'Using single quote';
3. $c = "control characters in \n double quote only";
4. $c2 = "\052";
5. $c3 = "\x2a";
6. $num = 1;
7. $d = "$num is parsed"; // $d equals "1 is parsed"
8. $e = "$numx is not parsed"; // $e equals " is not parsed"
9. $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';
$test1 = strcmp($str, 'hello world'); // $test1 equals -1
$test2 = strcasecmp($str, 'hello world'); // $test2 equals 0
$test3 = strcmp('a', 'A'); // $test3 equals 1;
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 76
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:
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' ); //Displays "zdef"
echo str_replace('ABC', 'z', 'abcdef'); // Displays "abcdef"
echo str_ireplace('ABC', 'z', '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"
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 77
6.5. Splitting:
6.5.1. Retun part of string: using substr().
Ex:
echo substr('abcdef', 1); // bcdef
echo substr('abcdef', 1, 3); // bcd
echo substr('abcdef', 0, 4); // abcd
echo substr('abcdef', 0, 8); // abcdef
echo substr('abcdef', -1, 1); // f
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
(
[0] => a
[1] => b
[2] => c
[3] => 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"
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 78
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.
Specifier Format b The argument is treated as an integer and is presented as an integer in binary
form. c The argument is treated as an integer and is presented as the ASCII character
for that value. d The argument is treated as an integer and presented as a signed integer. u The argument is treated as an integer and presented as an unsigned integer. f The argument is treated as a floating-point number and presented as a
floating-point number. o The argument is treated as an integer and presented as its octal
representation. x The argument is treated as an integer and presented as a hexadecimal
number (using lowercase letters). X The argument is treated as an integer and presented as a hexadecimal
number (using uppercase letters).
- Formatting functions:
Function Arguments Result printf Format, args Writes output
sprintf Format, args Return result vprintf Format, array of args Writes output vsprintf Format, array of args Returns result
fprintf Stream resource, format, args Writes output to stream
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 79
6.7. Regular Expression – RegEx:
- The most powerful tools in the string manipulation toolbox are regular expressions
6.7.1. Introduction:
6.7.2. Character Class: allow a pattern to match multiple characters simultaneously
Metacharacter Characters Matched \d Digits 0-9
\D Anything not a digit \w Any alphanumeric character or an underscore (_) \W Anything not an alphanumeric character or an underscore
\s Any whitespace (spaces, tabs, newlines) \S 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:
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 80
* The character can appear zero or more times + The character can appear one or more times
? The character can appear zero or one times {n,m} 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
(
[0] => 2008
[1] => 2009
)
)
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 81
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.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 83
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
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 85
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.
Ex:
$firstName = $_POST['FirstName'];
$salary = $_POST['Salary'];
$contractor = $_POST['Contractor'];
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 86
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:en-
US:official&um=1&q=http%20request&ndsp=21&ie=UTF-8&sa=N&tab=iw
POST Header Request:
POST /path/script.cgi HTTP/1.0
From: [email protected]
User-Agent: HTTPTool/1.0
Content-Type: application/x-www-form-urlencoded
Content-Length: 32
home=Mosby&favorite+flavor=flies
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 87
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
Code
Reason
Phrase
Description
200 OK Generic successful request message response. This is the code
sent most often when a request is filled normally.
201 Created The request was successful and resulted in a resource being
created. This would be a typical response to a PUT method.
301 Moved
Permanently
The resource requested has been moved to a new URL
permanently. Any future requests for this resource should use
the new URL.
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.
302 Found The resource requested is temporarily using a different URL.
The client should continue to use the original URL.
304 Not Modified 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.
400 Bad request Server says, “huh?” Generic response when the request cannot be understood or carried out due to a problem on the client's end.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 88
401 Unauthorized 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.
404 Not Found 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.)
500 Internal
Server Error
Generic error message indicating that the request could not be
fulfilled due to a server problem.
502 Bad Gateway 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.
503 Service
Unavailable
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.
504 Gateway
Timeout
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:
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>
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 89
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];
$uploadPathA = 'uploads/photos/'.$nameA;
$nameB = $_FILES[myfile]['name'][1];
$tmpnameA = $_FILES[myfile][tmp_name][1];
$uploadPathB = 'uploads/photos/'.$nameB;
// Begin to upload files
…
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 90
7.3. Cookie:
7.3.1. How cookies work:
7.3.2. Create cookies: using setcookie() function. Ex:
$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);
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 91
7.4. Session:
7.4.1. How sessions work:
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();
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 92
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: [email protected], password: abc3456ad5, website will display:
Hello rasmus !
You refreshed 3 times.
B> Write photo album function for the user (after login) from question A.
a. Upload images (png,gif,jpeg) – 5 images in a submit form
b. Store images in directory "uploads/images/".
c. Max file size: 300KB
d. File name: USERNAME_imagename
e. If image existed, append the letter "i" after name part. Ex: rasmus_image1.gif exists, will be
renamed to rasmus_image1i.gif
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 93
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
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 95
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.
Ex: $myClassInstance = new MyClass();
$copyInstance = $myClassInstance;
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 96
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;
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 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, it’s 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()
{
echo $this->color;
}
public function say()
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 98
{
$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
{
public $color;
function __construct($myColor)
{
$this->color = $myColor;
}
private function getColor()
{
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 99
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;
function __construct($myColor)
{
$this->color = $myColor;
}
function __destruct()
{
echo $this->color . ' is dead';
}
private function getColor()
{
echo $this->color;
}
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 100
public function say()
{
$this->getColor();
}
}
$redShirt = new Shirt('Red');
$blueShirt = new Shirt('Blue');
$redShirt->say(); // Displays 'Red'
$blueShirt->say(); // Displays 'Blue'
$redShirt = null; // Displays 'Red is dead';
unset($blueShirt); // 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
{
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"
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 101
8.4. Inheritance & Overriding:
8.4.1. Inheritance:
- Inheritance is the mechanism of deriving a new class from an existing class. It allows a sub-
class / 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;
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;
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 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
+ 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:
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 103
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
{
public function fly()
{
echo "Fly method of the Chicken Class called";
}
}
$e = new Eagle();
$c = new Chicken();
$e->fly(); // Displays "Fly method of the Eagle Class called"
echo "\n";
$c->fly(); // Displays "Fly method of the Chicken Class called"
- Examples:
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 104
class Car
{
protected $color;
protected $hoursepower;
protected $seatCount;
protected $type;
public $size = 'Small';
function __construct()
{
$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, it’s 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.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 105
- Syntax:
parent::method_name();
- 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 Person’s showData()
This is Customer’s 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()
{
parent::__construct();
echo "This is Customer's __construct()\n";
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 106
}
public function __destruct()
{
parent::__destruct();
echo "This is Customer's __destruct()\n";
}
}
$c = new Customer();
// Displays
This is Person’s __construct()
This is Customer’s __construct()
This is Person’s __destruct()
This is Customer’s __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: [email protected], password: abc3456ad5, website will display:
Hello rasmus !
You refreshed 3 times.
A> Write photo album function for the user (after login)
a. Upload images (png,gif,jpeg) – 5 images in a submit form
b. Store images in directory "uploads/images/".
c. Max file size: 300KB
d. File name: USERNAME_imagename
e. 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.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 107
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
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 109
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 Description
r Open for reading only; place the file pointer at the beginning of the file.
r+ Open for reading and writing; place the file pointer at the beginning of the file.
w 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.
w+ 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.
a Open for writing only; place the file pointer at the end of the file. If the file
does not exist, attempt to create it.
a+ 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.
x 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.
x+ 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.
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
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.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 110
9.2. File Manipulation:
Function Handle Description
file_exists() 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() Tells whether the filename is writable.
fread() Yes 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() Reads entire file into a string.
Ex: $contents = file_get_contents('config/text.txt');
chmod() Changes file mode.
Ex: chmod("/somedir/somefile", 0666);
copy() Copies file.
Ex:
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 111
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 $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n";
// Displays
/www/htdocs
index.html
html
index
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 112
9.3. Directory:
9.3.1. Open directory handle:
$dh = opendir('uploads/photos/');
9.3.2. Useful directory functions:
Function Handle Description
readdir() Yes Reads entry from directory handle
is_dir() Tells whether the filename is a directory
mkdir() Makes directory.
Ex: mkdir("/path/to/my/dir", 0700, true);
rmdir() Removes directory. Note: directory must be empty
dirname() 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";
}
}
closedir($handle);
}
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 113
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,[email protected],AVATAR_URL
bob, lakljliuaklnkajsdoif928379skjad,[email protected],AVATAR_URL
…
"
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 115
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
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 117
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.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 118
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:
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 119
10.2.2.1. Graphical User Interface - GUI:
- Navicat MySQL:
- SQLyog:
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 120
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'];
$web=$_POST['web'];
mysql_connect("localhost",$username,$password);
mysql_select_db($database) or die( "Unable to select database");
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 121
$query = "INSERT INTO contacts VALUES
('','$first','$last','$phone','$mobile','$fax','$email','$web')";
mysql_query($query);
mysql_close();
?>
10.2.2.4. phpMyAdmin:
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 122
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:
+ "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.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 123
• 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.
+ "name VARCHAR(30)" : 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.
+ "age INT" : Our third and final column is age, which stores an integer. Notice that there are no parentheses following "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]]
[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;
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 124
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
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
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 125
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/
10.4.2. Create Database:
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 127
10.4.4. Select Database:
- Select the dropdown box on the left panel, click the database you want to working.
10.4.5. Select Table:
- Click a table on the left panel to select
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 128
10.4.6. Change Table Structure:
- Select the columns you want to change structure, click Edit button
10.4.7. Insert Value to Table:
- Select the table you want to insert value
- Click the INSERT tab to begin insert data
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 129
10.4.8. View All Data of Table:
- Select the table you want to view data
- Click the BROWSE tab to view table data
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 130
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.
- In the Editing page, update your value, and click Go button to save.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 132
10.4.10. Delete Rows in Table:
- Delete 1 Row by click on the Delete icon ( ) on selected row.
- Delete multiple rows by click the checkbox before each row, after that, click the Delete icon
( ) followed the data tables.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 134
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.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 135
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.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 136
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.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 137
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.
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.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 138
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:
- 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);
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 139
10.5.4. Some Useful Functions:
Function Description
mysql_query() 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() Get number of rows in result.
Ex: $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.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 141
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
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 143
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.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 144
11.2.2. php.ini debugger configuration:
- 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.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 145
[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:
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 146
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.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 147
11.3.4. Using Breakpoint:
- 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.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 149
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
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 151
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(); // Display "I am a dog"
$cat->say(); // Display "I am a cat"
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 152
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
{
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';}
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 153
}
$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 don’t 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
- 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';}
}
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 154
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:
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)
{
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 155
$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))
{
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"
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 156
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)"
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)
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 157
{
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)
{
echo "Calling Static method test::$name(".implode(', ',
$arguments).")\n";
}
}
test::unknowfunction(1,2);
// Displays "Calling Static method test::unknowfunction(1, 2)"
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 159
Chapter 13
MySQL
Advanced Keywords: MyISAM, InnoDB, join, statement, prepared statement,
transaction, PDO.
Subjects:
13.1. Table Joining
13.2. PHP Data Object (PDO)
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 161
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
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 162
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).
SELECT *
FROM employee
RIGHT JOIN department
ON employee.DepartmentID = department.DepartmentID
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 163
13.1.5. Self Join:
- Table is joined to itself and is made possible by aliasing the original table.
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';
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 164
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;
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)
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 165
{
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',
':departmentid' => 35));
13.2.4.2. Using '?' character: $sql = 'INSERT INTO employee(LastName, DepartmentID)
VALUES(?, ?)';
$stmt = $dbh->prepare($sql);
$stmt->execute(array('Test1', 35));
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 167
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
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 169
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.?
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 170
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.
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?
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 171
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
or
- Use Case: a visual representation of a distinct business functionality in a system
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 172
- 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
- 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
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 173
- Generalization: The child use case in the generalization relationship has the underlying
business process meaning, but is an enhancement of the parent use case
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 174
14.2.4. UML Tools:
- Rational Rose (Commerce Software):
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 176
-StarUML (Freeware):
14.2.5. Example:
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 177
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.
- Interface: An interface on the other hand provides only a definition of business functionality
of a system.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 178
- 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
14.3.3. Relations between Classes:
- Association: When two classes are connected to each other in any way, an association
relation is established
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 179
- 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.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 181
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
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 183
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>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 184
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:
foreach($booklib->Book as $book)
{
echo $book['ISBN'] . "\n";
echo $book['title'] . "\n";
echo $book[author] . "\n\n";
}
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 185
15.2.3. Common SimpleXML Class Method:
Method Description
addChild() 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: oreach($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');
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
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 186
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]))
{
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();
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 187
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'
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>
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 188
<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
{
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';
}
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 189
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:
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"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 190
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>
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.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 191
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
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 193
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
- Limit the permissions.
- Filter user input
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 194
- 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.
- Notice to file/directory name convention
- Keep your secret
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 195
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:
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 196
���� 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 :
View Animation: http://www.virtualforge.de/vmovie.php
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 197
���� Solution:
- Filter All Input
- Escape All Output
- Only Allow Safe Content
16.3.5. Cross Site Request Forgery – CSRF :
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 198
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
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 199
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'];
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 200
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
// for concern, and the user should log in again
if ($_SESSION['user_agent'] != $_SERVER['HTTP_USER_AGENT'])
{
// Force user to log in again
exit;
}
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 201
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
; 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.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 203
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
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 205
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]
- Ex:
[PHP]
[MySQL]
[Session]
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 206
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] => 40
[minutes] => 58
[hours] => 21
[mday] => 17
[wday] => 2
[mon] => 6
[year] => 2003
[yday] => 167
[weekday] => Tuesday
[month] => June
[0] => 1055901520
)
17.2.2. Timestamp Introduction:
- 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:
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 207
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):
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 208
17.3. Email Sending:
17.3.1. Using function mail() from PHP:
$to = '[email protected]';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: [email protected]' . "\r\n" .
'Reply-To: [email protected]' . "\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
$your_email = "[email protected]";
$your_smtp = "mail.example.com";
$your_smtp_user = "[email protected]";
$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>";
}
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 209
$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.
17.4.2. Useful Image Functions:
Function Description imagecreate() Creates a blank image resource of the specified size.
imagecreatefromgif() Creates an image resource from the specified GIF format file.
imagecreatefromjpeg() Creates an image resource from the specified JPEG format file.
imagecreatefrompng() Creates an image resource from the specified PNG format file. imagesx() Returns the image's width
imagesy() Returns the image's height
imagegif() Output a GIF image to browser or file
imagejpeg() Output a JPEG image to browser or file
imagepng() Output a PNG image to browser or file
imagedestroy() Destroy an image resource, free up memory
imagecopy() Copy part of an image
imagecopymerge() Copy and merge part of an image
imagecopyresampled() 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);
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 210
// 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);
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);
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 211
17.6. Smarty:
17.6.1. Smarty Introduction:
- 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
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 212
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
- defines constant within the scope of a class
- class methods and properties support visibility: public, private, protected
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 213
- 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…
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 215
Chapter 18
Design Pattern Keywords: design, singleton, factory, strategy, MVC, Model-View-
Controller, 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
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 217
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, Façade, 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
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
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 218
- 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:
- Creates objects without exposing the instantiation logic to the client and refers to the newly
created object through a common interface.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 219
- 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';
}
}
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.');
}
}
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 220
}
$obj = ProductFactory::getProduct(ProductFactory::PROD_LAP);
$obj->say();
18.4. Strategy Pattern:
18.4.1. Strategy Pattern Introduction:
- 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;
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 221
}
}
class Student
{
private $point;
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:
- Model–view–controller (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.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 222
- 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
Ver.
Multiple DB ORM Template Cache Validation Ajax
CakePHP 4 , 5 x x x x x
CodeIgniter 4 , 5 x x x x
Prado 5 x x x x x x
Symfony 5 x x x x x
Zend 5 x x x x x
- Multiple DB: Indicates whether the framework supports multiple databases without having
to change anything.
- 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.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 223
- 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.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 225
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
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 227
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
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 228
19.2. Website Optimization:
19.2.1. Front-end Optimization:
19.2.2. Back-end Optimization:
- Code Optimize
- 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.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 229
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 Google’s LSI algorithm)
5. The URL — The subdirectory folder and page of content should be SEO’d (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 page’s 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 — 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 SEO’d - 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 SEO’d — 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 doesn’t 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 that’s 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
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 230
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.
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.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 231
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 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.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 232
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
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.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 233
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.
o 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.
o 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.
o 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 users left after visiting only one page), or percentage of new visits (how many visitors had never been to your site before).
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 234
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.
o Pageviews tells how many times the pages on your site have been viewed.
o Pages/visit tells how many pages, on average, users view when they come to your site.
o Bounce Rate tells what percentage of users left after viewing only one page on your site.
o Avg. Time on Site shows how long each user spent on your site.
o New Visits shows what percentage of your users have not visited your site before.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 236
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.
o Click on View Report to view more detailed information about your visitors.
6. "Map Overlay" displays what countries your visitors are coming from.
o The darker the green, the more visitors come from that country.
o 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.
o 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.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 237
2. To the left beneath the main chart, you'll see a number of different statistical breakouts.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 238
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.
19.4.5. See Where Your Traffic Comes From
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 239
1. In the lower right-hand corner of the Dashboard you'll find your site's top 5 most-accessed 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.
3. Beneath the chart, you'll see a table. This table lists all the places your users came from to visit your site.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 240
o In the first column to the right of the source name is the number of pageviews your page received from that source.
o 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.
o Time on Page tells you how much time, on average, users from that particular source spent on the page in question.
o Bounce Rate shows how many people from that specific source left your site after looking at that page, without viewing another page.
o % 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.)
o 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.
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.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 241
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
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 243
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
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 245
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
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 246
ZCE Logo
20.2. Zend PHP 5 Certification Exam:
20.2.1. PHP Exam Contents:
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 247
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.
− 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
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 249
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.
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.
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER 250
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/
Textbook Author: Full Name: Vo Duy Tuan
Certification : Zend Certified Engineer
Email: [email protected]
Phone: 0938 916 902
Website: http://bloghoctap.com/