6. PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
6
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
7
8. PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
8
9. 1.1. Web Design Toolbox:
1.1.1. Image Manipulating: Photoshop, GIMP, Illustrator…
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
9
10. PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
10
11. 1.1.2. Animation Creator: Photoshop, Flash, Flex, Maya, 3DS Max…
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
11
12. PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
12
13. 1.1.3. HTML Editor: Dreamweaver, Notepad++…
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
13
14. 1.1.4. CSS Editor: Dreamweaver, Rapid CSS, Notepad++…
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
14
15. 1.1.5. Javascript Editor: Dreamweaver, 1st Javascript Editor, Notepad++…
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
15
16. 1.2. HTML Editor – Dreamweaver CS3:
- Main Dreamweaver CS3 interface
- Auto-complete function
- Collapse selected script:
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
16
17. - Property Inspector Panel:
- Create a Local Site:
Or:
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
17
18. Or:
- After creating site, the FILES panel will become:
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
18
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
19
20. PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
20
21. - Create new file
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
21
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
22
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
23
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
27
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
28
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
29
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
30
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
31
32. PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
32
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
33
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
34
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
35
36. PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
36
37. 2.3. Using AppServ:
2.3.1. AppServ 2.10 Directory Structure:
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
37
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
38
39. - Some main features:
+ Autocomplete code:
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
39
40. + Full screen support
+ Database Client
+ Support HTML, CSS, JS language
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
40
41. PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
41
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
42
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
43
44. - Access php interactive using URL: http://localhost/phpa/
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
44
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
45
46. PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
46
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
47
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
48
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', 'myemail@example.com');
echo EMAIL; // Displays 'myemail@example.com'
define('5CLASS, 'some value); // Invalid name
PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
49
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
50
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
51
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
52
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
53
54. PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
54
56. PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
56
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
57
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
58
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
59
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
60
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
61
62. PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
62
64. PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
64
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
65
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
66
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
67
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 Order of sort Related functions
association
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 natsort()
insensitive
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 First array or array_walk()
yes, numeric sort options
no
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
68
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
70
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
71
72. PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
72
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
76
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
77
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
78
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-ed]/ 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
79
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
80
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("/[ds,]+/", "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
81
82. PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
82
84. PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
84
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
85
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: frog@jmarshall.com
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
86
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 Reason Description
Code Phrase
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 The resource requested has been moved to a new URL
Permanently 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
87
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 Generic error message indicating that the request could not be
Server Error 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 The server is temporarily unable to fulfill the request for internal
Unavailable reasons. This is often returned when a server is overloaded or
down for maintenance.
504 Gateway The server, while acting as a gateway or proxy, timed out while
Timeout 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
88
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
89
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
90
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
91
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: rasmus@myemail.com, 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
92
94. PHP Beginner & Intermediate
ATHENA TRAINING & EDUCATION CENTER
94
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
95
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
96
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
97