You are on page 1of 164

PHP (PHP: Hypertext Preprocessing)

Ngi lp: Nguyn Ph Qung


B mn: Tin hc Xy dng

Ni dung trnh by
. Lm quen vi PHP
. PHP Cn bn
. Cc tnh nng cho ng dung Web base

Lm vic vi Form

Cc hm lm vic vi MySQL

Lm vic vi File

Cc hm lm vic vi hnh nh

Cc hm trn ngy thng

Cc hm trn d liu

Cookies v QueryString

Session

G li

I. Lm quen vi PHP
.1. PHP l g?
.2. Ljch s pht trin ca PHP
.3. L do chn PHP
.4. Zend Engine
.5. Ci dt PHP
.6. Chong trnh PHP du tin
.7. Cc DE cho PHP

I.1. PHP I g?

PHP doc pht trin t ngn ng kjch bn (script) vi muc dch


xy dng trang Web c nhn (Personal Home Page). Sau d d
doc pht trin thnh mt ngn ng hon chinh v doc a
chung trn ton th gii trong vic pht trin cc ng dung Web
based

Theo NetCraft:

Thng 11 nm 1999, hon 1 triu my ch

Thng 9 nm 2000, hon 1.4 triu my

PHP (PHP: Hypertext Perprocessor) l ngn ng kjch bn lp trnh


pha my ch (server-side) ph bin nht th gii.

PHP thng hoat dng theo th t sau:

Ngi dng gi yu cu ln my ch

My ch x l yu cu (Thng djch m PHP v chay chong trnh, m


PHP c th truy xut CSDL, tao hnh nh, dc ghi file, tong tc vi
my ch khc...)

My ch gi d liu v cho ngi dng (thng l di dang HTML)



I.1. PHP I g? (2)

I.2. L[ch s pht trin ca PHP

Phin bn du tin ca PHP doc pht trin nm 1994,


bao gm cc macro cho trang Web c nhn (Personal
Home Page)

Sau d, PHP doc pht trin thm mt s chc nng mi


gi l Form nterpreter (PHP/F) v c doc s quan tm
ln t pha cng dng

Phin bn tip theo, PHP3, doc vit lai bi mt nhm cc


lp trnh vin (Zeev Suraski, Andi Gutmans). PHP3 doc
b sung thm mt s tnh nng v cc c php ngn ng
khc, d tr thnh ngn ng kjch bn pha my ch doc
a chung nht

I.3. L do chn PHP

Khi s dung PHP, ngi dng s c doc


tc d nhanh hon nhiu so vi cc ngn ng
kjch bn khc, bi PHP l phn mm m
ngun m, doc h tro bi nhiu lp trnh
vin gii, c s long ngi dng dng do.
Ngoi ra PHP chay doc trn nhiu h diu
hnh khc nhau

I.3. L do chn PHP (2)

Rt ngn thi gian pht trin

PHP cho php ban tch phn HTML code v phn script,
do d c th dc lp gia cng vic pht trin m v thit
k. iu ny va gip lp trnh vin d dng hon va c
th lm cho chong trnh mm do hon trong vic thay di
giao din

PHP l phn mm m ngun m

PHP khng chi l phn mm m ngun m m cn thc s


min ph (k c khi ban s dung cho muc dch thong mai)

Do l phn mm m ngun m, cc li (bug) ca PHP


doc cng khai v nhanh chng doc sa cha bi nhiu
chuyn gia

I.3. L do chn PHP (3)

Tc d

Nh vo sc manh ca Zend Engine, khi so snh


PHP vi ASP, c th thy PHP vot hon mt
s test, vot tri tc d bin djch.

Tnh kh chuyn

PHP doc thit k d chay trn nhiu nn tng


khc nhau, c th lm vic vi nhiu phn mm
my ch, co s d liu (v du: ban c th pht
trin d n trn UNX, sau d chuyn sang NT
m khng gp phi bt c vn d g)

I.4. Zend Engine

Zend l scripting engine nm bn trong PHP

Zend Engine thc s l s ci tin dng k.


Hu ht cc doan m vit trn PHP3 du c
th chay trn PHP4 vi tc d tng gp 200
ln

I.5. Ci dt PHP

Ban c th tm phin bn mi nht ca PHP


tai dja chi http://www.php.net

PHP l phn mm m ngun m, ban c th


download c m ngun ca PHP

Ban c th tm ti liu tham kho ca PHP tai


dja chi http://www.php.net/manuaI

I.5. Ci dt PHP (2)
Ci dt PHP vi S

Control Panel/Add Remove Programs/Add Remove


Window Components

Bt nternet nformation Services

Download PHP nstaller (Windows Binaries) t


http://www.php.net/downloads.php

Ci dt PHP (chn server S)


Ci dt Apache

Download Apache tai http://httpd.apache.org/

Ci dt Apache

I.5. Ci dt PHP (3)

Download bn PHP zip package (Window Binaries)

Gii nn vo th muc C:\PHP

Sa file conf/httpd.conf, thm vo ni dung sau


ScriptAlias /php/ "c:/php/"
AddType application/x-httpd-php .php
Action application/x-httpd-php "/php/php.exe"

Hoc (Copy php5ts.dll vo th muc c:/windows/system32)


LoadModule php5_module "c:/php/sapi/php5apache2.dll"
AddType application/x-httpd-php .php

I.5. Ci dt PHP (4)

Thm alias (vo trong httpd.conf)


Alias fake realname
Alias /pm/ "C:/PMNM/47PM1/47PM1/

Ch : fake phi bt du bng /

nu fake kt thc bng / th realname cng


phi kt thc bng /

I.6. Chuong trnh PHP du tin

Chong trnh du tin (ban c th soan bng bt


ky trnh soan tho vn bn no)
<?php
echo("Hello world");
?>
Lu file di tn hello.php tai c:\inetpub\wwwroot\php
(S) hoc trong th muc ng vi Alias va tao ra
Tai trnh duyt, nhp vo dja chi
http://localhost/php/hello.php

I.6. Chuong trnh PHP du tin (2)

Khi chong trnh PHP


</script> <script
language=ph
p>
Script tags
> < ASP
?> <? Dang rt gn
?> <?php Chun
End Tag Start Tag Tag style

I.6. Chuong trnh PHP du tin (3)
<html>
<head>
<title>Chuong trinh PHP dau tien</title>
</head>
<body>
<b>
<?php
// Day la chuong trinh PHP dau tien
echo("Hello world");
/* Comment the nay cung duoc */
# Ma the nay cung chang sao
?>
</b>
</body>
</html>

I.7. Cc IDE cho PHP
Nh d bit, ban c th vit chong trnh PHP
bng bt c h soan tho vn bn no. Tuy
nhin, d c doc cc chc nng h tro nh
AutoComplete, Debug... cn phi s dung cc
DE dnh ring cho PHP

Macromedia DreamWaver

Nusphere PHPED

Zend Studio

II. PHP Cn bn
.1. Bin, kiu v hng
.2. Ton t v biu thc
.3. Cc cu lnh diu khin
.4. Hm
.5. Lp di tong
.6. Tham chiu (reference)

II.1. Bin, kiu v hng
.1.1. Bin
.1.1.1. Tn bin
.1.1.2. Tham chiu
.1.1.3. Bin dng
.1.1.4. Pham vi (scope) ca bin
.1.2. Kiu
.1.3. Hng

II.1.1.1. Tn bin
<?php
$var = "Bob";
$Var = "Joe";
echo "$var, $Var"; // outputs "Bob, Joe"
$4site = 'not yet'; // invalid; starts with a number
$_4site = 'not yet'; // valid; starts with an underscore
$tyte = 'mansikka'; // valid; '' is (Extended) ASCII 228.
?>
Bin doc k hiu bi k t $
Tn bin phi doc bt du bi 1 ch ci hoc k t gach
chn
Tn bin khng cha cc du v k t cch

II.1.1.2. Tham chiu
Ging ngn ng C, trong PHP ban c th s dung tham chiu
<?php
$quang = "adfsdfasdfa";
echo("<p>$quang</p>");
$q = &$quang;
$q = "quangnp";
echo("<p>$quang</p>");
?>
<?php
$foo = 25;
$bar = &$foo; // This is a valid assignment.
$bar = &(24 * 7);// Invalid references an unnamed exression.
function test() {
return 25;
}
$bar = &test(); // Invalid.
?>

II.1.1.3. Bin dng (Dynamic VariabIe)
PHP l ngn ng thng djch nn ban c th s dung cc bin
c tn cha bit trc (tn bin thay di)
<?php
$a = "quang"; // gia tri cua !ien a la "#uang"
$$a = "np"; // !ien dong $#uang co gia tri la "n"
echo("$a<br>"); // In ra gia tri cua !ien a
echo("$quang<br>"); // In ra gia tri cua !ien #uang
${"quang"} = 13432; // %ian truc tie !ien dong
echo("$quang<br>");
$c = "quang";
${$c} = 1000;
// Mot cach &hac de truy ca den !ien dong #uang
echo("${$c}<br>");
?>

II.1.1.4. Pham vi ca bin
<?php
$a = 1;
include "b.inc";
?>
Pham vi ca bin a c tc dung trong c b.inc
<?php
$a = 1; // glo!al scoe
function Test() {
echo $a; // reference to local scoe varia!le
}
Test();
?>
Bin a ngoi v trong hm Test khc nhau

II.1.1.4. Pham vi ca bin (2)
T kha global
<?php
$a = 1;
$b = 2;
function Sum() {
//a' ! trong ( ngoai ham )um
global $a, $b;
// la giong nhau
$b = $a + $b;
}
Sum();
echo $b;
?>
Hoc s dung c php
<?php
$a = 1;
$b = 2;
function Sum() {
$GLOBALS["b"] =
$GLOBALS["a"] +
$GLOBALS["b"];
}
Sum();
echo $b;
?>

II.1.1.4. Pham vi ca bin (3)
<?php
function Test ()
{
$a = 0;
echo $a;
$a++;
}
Test();
Test();
?>
<?php
function Test ()
{
static $a = 0;
echo $a;
$a++;
}
Test();
Test();
?>

II.1.1.4. Pham vi ca bin (4)
<?php
$foo = 25;
$bar = &$foo; // This is a valid assignment.
function test()
{
global $foo;
return $foo;
}
$bar = &test(); // Invalid.
echo($bar);
?>

II.1.2. Kiu

Cc kiu don
.1.2.1. boolean
.1.2.2. integer
.1.2.3. float
.1.2.4. string

Cc kiu phc
.1.2.5. array
.1.2.6. obect

Cc kiu dc bit
.1.2.7. resource
.1.2.. NULL

II.1.2. Kiu (2)
<?php
$bool = TRUE; // a !oolean
$str = "foo"; // a string
$int = 12; // an integer
echo gettype($bool); // rints out *!oolean*
echo gettype($str); // rints out *string+
// If this is an integer' increment it !y four
if (is_int($int)) {
$int += 4;
}
// If $!ool is a string' rint it out
// ,does not rint out anything-
if (is_string($bool)) {
echo "String: $bool";
}
?>
Ban c th p kiu bng hm settype()

II.1.2.1. Kiu booIean
<?php
// .. is an oerator /hich test
// e#uality and returns a !oolean
$q = (1==1);
echo("$q<br>");
$q = (1=="1");
echo("$q<br>");
// this is not necessary...
if ($show_separators == TRUE) {
echo "<hr>\n";
}
// ...!ecause you can simly tye
if ($show_separators) {
echo "<hr>\n";
}
?>

II.1.2.2. Kiu integer
<?php
$a = 1234; # decimal num!er
$a = -123; # a negative num!er
$a = 0123; # octal num!er ,e#uivalent to 01 decimal-
$a = 0x1A; # hexadecimal num!er ,e#uivalent to 23
decimal-
?>
<?php
$a=10000000;
var_dump($a); echo("<br>");
$a=100000000;
var_dump($a); echo("<br>");
$a=1000000000;
var_dump($a); echo("<br>");
$a=10000000000;
var_dump($a); echo("<br>");
?>

II.1.2.3. Kiu fIoat
<?php
$a = 1.234;
$b = 1.2e3;
$c = 7E-10;
?>
<?php
$foo = 1 + "10.5"; // $foo is float ,44.5-
$foo = 1 + "-1.3e3"; // $foo is float ,64277-
$foo = 1 + "bob-1.3e3"; // $foo is integer ,4-
$foo = 1 + "bob3"; // $foo is integer ,4-
$foo = 1 + "10 Small Pigs"; // $foo is integer ,44-
$foo = 4 + "10.2 Little Piggies"; // $foo is float ,48.2-
$foo = "10.0 pigs " + 1; // $foo is float ,44-
$foo = "10.0 pigs " + 1.0; // $foo is float ,44-
?>

II.1.2.4. Kiu string

String trong PHP l mt chui cc k t 1 byte. PHP khng h


tro Unicode, d lm vic vi Unicode ban phi s dung UTF
vi cc hm utfencode() utfdecode()

String ca PHP h tro chiu di rt ln (?)

Trong PHP, string doc xc djnh theo 3 cch

Du nhy don (single quote)

Du nhy kp (double quote)

Heredoc

Truyn bin trong string

Truyn kiu don gin

Truyn kiu phc

Truy cp dn tng k t trong string

Cc ton t trn string



II.1.2.4. Kiu String (2)
Kiu du nhy don
<?php
echo 'this is a simple string';
echo 'You can also have embedded newlines in
strings this way as it is
okay to do';
// Outputs: Arnold once said: "I'll be back"
echo 'Arnold once said: "I\'ll be back"';
// Outputs: You deleted C:\*.*?
echo 'You deleted C:\\*.*?';
// Outputs: You deleted C:\*.*?
echo 'You deleted C:\*.*?';
// Outputs: This will not expand: \n a newline
echo 'This will not expand: \n a newline';
// Outputs: Variables do not $expand $either
echo 'Variables do not $expand $either';
?>

II.1.2.4. Kiu String (3)

Kiu du nhy kp: kiu ny ging vi kiu


du nhy don nhng c nhiu h tro cho cc
k t dc bit hon

II.1.2.4. Kiu String (4)
Kiu Heredoc
<?php
$str = <<<EOA
Example of string <br>
spanning multiple lines<br>
using heredoc syntax.<br>
EOA;
echo($str);
$name = "quang";
$d = date("d/m/y");
$str = <<<EOQ
This is a lecture of $name.<br>
Ngay $d<br>
EOQ;
echo($str);
?>

II.1.2.4. Kiu String (5)
Truyn bin kiu don gin
<?php
$beer = 'Heineken';
echo "$beer's taste is great";
// /or&s' *"* is an invalid character for varnames
echo "He drank some $beers";
// /on"t /or&' "s" is a valid character for varnames
echo "He drank some ${beer}s"; // /or&s
echo "He drank some {$beer}s"; // /or&s
?>
Truyn bin kiu phc (truyn bin kiu mng vo
string) s d cp dn phn mng

II.1.2.4. Kiu String (6)
Truy cp dn tng k t ca String
<?php
$str = "This is a test";
echo $str[0]; // 9y tu dau tien
echo $str{1}; // 9y tu thu 2
echo $str{strlen($str)-1}; // 9y tu cuoi cung
echo "<br>$str";
$str{strlen($str)-1} = "s"; // )ua &y tu cuoi cung
echo "<br>$str";
?>
Cc ton t trn string
<?php
$str1 = "quang";
$str2 = "np";
echo $str1 . $str2, "<br>";
echo $str1 + $str2, "<br>";
?>

II.1.2.5. Kiu Array

Kiu Array ca PHP thc s l kiu nh xa


(map) c th t. Tc l kiu d liu gm cc
cp kha (key) v gi trj (value).

i kiu mng ny, ban c th s dung nh


mt mng thun ty (vector), hay dng cho
cc kiu d liu collection, stack, queue,
tree...

II.1.2.5. Kiu Array (2)

Khai bo
<?php
$ar = array(3,4,5,6,3,2);
echo var_dump($ar), "<br>";
$ar = array(5=>10, 20, 30, "q"=>40);
echo var_dump($ar), "<br>";
$ar = array(5=>10, 6=>20, 7=>30, "q"=>40);
echo var_dump($ar), "<br>";
$ar = array("a"=>10, 20, 30, 40);
echo var_dump($ar), "<br>";
$ar = array("a"=>array(1,2,3,4,5), 20, 30, 40);
echo var_dump($ar);
?>

II.1.2.5. Kiu Array (3)
S dung array
<?php
$arr = array(5 => 1, 12 => 2);
$arr[] = 56; // This is the same as $arr:41; . 53<
// at this oint of the scrit
$arr["x"] = 42; // This adds a ne/ element to
// the array /ith &ey *x*
unset($arr[5]); // This removes the element from the array
unset($arr); // This deletes the /hole array
?>
<?php
$handle = opendir(".");
var_dump($handle);
while($file=readdir($handle)) {
$files[] = $file;
}
var_dump($files);
?>

II.1.2.6. Kiu Object
<?php
class Xeco {
var $sobanh;
function BaoNhieuBanh() {
echo($this->sobanh);
}
};
$xe = new Xeco();
$xe->sobanh = 4;
$xe->BaoNhieuBanh();
?>

II.1.3. Hng
jnh ngha hng bng cch s dung hm define()
Pham vi ca hng l ton cuc (global)
Chi c cc dang d liu don gin (boolean, interger, float, string)
Nu tn hng cha doc djnh ngha, PHP gi thit rng ban dang s dung
1 hng cha gi trj l 1 string (chnh l tn ca hng d)
xc djnh mt hng d doc djnh ngha hay cha, ban c th s dung
hm defined
<?php
define("CONSTANT", "Hello world.");
echo CONSTANT; // oututs *Hello /orld.*
echo Constant; // oututs *Constant* and issues a notice.
echo defined("Constant");
echo defined("CONSTANT");
?>

II.1.3. Hng (2)

Cc hng doc djnh ngha trc (cc hng ny


thng doc s dung d phuc vu qu trnh debug
Tn phong thc hin tai ca lp METHD
Tn lp hin tai CLASS
Tn hm hin tai FUNCTN
ng dn dy d ca file hin tai FLE
Th t dng hin tai trong file LNE
M t Tn hng

II.2. Ton t v biu thc
.2.1. Mc d u tin cc ton t
.2.2. Ton t s hc
.2.3. Ton t gn
.2.4. Cc ton t trn bit
.2.5. Ton t so snh
.2.6. Ton t diu khin li
.2.7. Ton t thc thi
.2.. Ton t tng, gim
.2.9. Cc ton t logic
.2.10. Ton t trn string
.2.11. Ton t trn mng

II.2.1. Mc d uu tin cc ton t
new non-associative
[ right
! ~ ++ -- (int) (float) (string) (array) (object) @ right
* / % left
+ - . left
<< >> left
< <= > >= non-associative
== != === !== non-associative
& left
^ left
| left
&& left
|| left
? : left
= += -= *= /= .= %= &= |= ^= <<= >>= right
print right
and left
xor left
or left
, left
Operators Associativity

II.2.2. Ton t s hc
Remainder of $a divided by $b. Modulus $a % $b
Quotient of $a and $b. Division $a / $b
Product of $a and $b. Multiplication $a * $b
Difference of $a and $b. Subtraction $a - $b
Sum of $a and $b. Addition $a + $b
Result Name Example

II.2.3. Ton t gn

Ton t gn (=) cho php ban gn mt biu thc (v


phi) cho 1 bin (v tri)

Ton t gn tr v gi tr[ ca biu thc v phi, do d


c th dng nhiu php gn Iin tip nhau

Ngoi ra, cn c cc php ton gi I php ton kt


hp cho hu ht cc ton t s hc d thay di gi tr[ 1
bin theo php ton s hc d (+=, -=, *=, /=, .= ...)
<?php
$a = 4; echo "$a\n";
$a = $b = $c = 10; echo "$a,$b,$c\n";
$a = ($b=4) + 5; echo "$a,$b\n";
$a .= "quang"; echo "$a\n";
$a = ($b+=10) + 2; echo "$a";
?>

II.2.4. Cc ton t trn bit
Shift the bits of $a $b steps to the left
(each step means "multiply by two")
Shift
left
$a << $b
Bits that are set in $a are not set, and vice
versa.
Not ~ $a
Bits that are set in $a or $b but not both are
set.
Xor $a ^ $b
Bits that are set in either $a or $b are set. Or $a | $b
Bits that are set in both $a and $b are set. And $a & $b
Result Name Example
<?php
echo 12 ^ 9; // =ututs "5"
echo "12"^"9"; // =ututs the >ac&sace character ,ascii 0-
// ,"4" ,ascii 87-- ? ,"7" ,ascii 5@-- . #0
echo "hallo"^"hello"; // =ututs the ascii values #A #8 #A #A #A
// "a" ? "e" . #8
?>

II.2.5. Ton t so snh
TRUE if $a is greater than or equaI to $b.
Greater than or
equaI to
$a >= $b
TRUE if $a is Iess than or equaI to $b.
Less than or equaI
to
$a <= $b
TRUE if $a is strictIy greater than $b. Greater than $a > $b
TRUE if $a is strictIy Iess than $b. Less than $a < $b
TRUE if $a is not equaI to $b, or they are not of the
same type. (PHP 4 onIy)
Not identicaI $a !== $b
TRUE if $a is not equaI to $b. Not equaI $a <> $b
TRUE if $a is not equaI to $b. Not equaI $a != $b
TRUE if $a is equaI to $b, and they are of the same type.
(PHP 4 onIy)
IdenticaI $a === $b
TRUE if $a is equaI to $b. EquaI $a == $b
ResuIt Name ExampIe

II.2.6. Ton t diu khin Ii

Ton t diu khin li () dng d dt trc cc


hm, biu thc. Khi d tt c cc thng bo li trong
hm, biu thc d bj b qua
<?php
$b = @file("a adf a") or
die("Khong the mo file");
?>

II.2.7. Ton t thc thi

Ton t thc thi () cho php ban gi cc lnh


trn console, (cc thng tin tin ny c th vit
ra output hoc gn vo cc bin)
<?php
$output = `dir c:\\`;
echo "$output";
?>

II.2.8. Ton t tng, gim
<?php
$a = 5;
echo "Should be 5: " . $a++ . "<br />\n";
echo "Should be 6: " . $a . "<br />\n";
$a = 5;
echo "Should be 6: " . ++$a . "<br />\n";
echo "Should be 6: " . $a . "<br />\n";
$a = 5;
echo "Should be 5: " . $a-- . "<br />\n";
echo "Should be 4: " . $a . "<br />\n";
$a = 5;
echo "Should be 4: " . --$a . "<br />\n";
echo "Should be 4: " . $a . "<br />\n";
?>

II.2.9. Cc ton t Iogic
TRUE if either $a or $b is TRUE. Or $a || $b
TRUE if both $a and $b are TRUE. And $a && $b
TRUE if $a is not TRUE. Not ! $a
TRUE if either $a or $b is TRUE, but not both. Xor $a xor $b
TRUE if either $a or $b is TRUE. Or $a or $b
TRUE if both $a and $b are TRUE. And $a and $b
Result Name Example

II.2.10. Ton t trn string

C 2 ton t trn string ( . v .=)


<?php
$a = "Hello ";
$b = $a . "World!"; // no/ $! contains *Hello BorldC*
$a = "Hello ";
$a .= "World!"; // no/ $a contains *Hello BorldC+
?>

II.2.11. Ton t trn mng
i vi mng, chi c ton t , ton t ny ni 2
mng vi nhau (cc phn trng kha doc ly
ton hang tri)
<?php
$a = array("a" => "apple", "b" => "banana");
$b = array("a" =>"pear",
"b" => "strawberry",
"c" => "cherry");
$c = $a + $b;
var_dump($c);
?>

II.3. Cc cu trc diu khin
.3.1. Cu trc if, else, elseif, endif
.3.2. Cu trc while / do...while
.3.3. Cu trc for / for...each
.3.4. S dung break, continue trong cc vng
lp
.3.5. Cu trc switch

II.3.1. Cu trc if, eIse, eIseif, endif
<?php
if ($a > $b) {
echo "a is bigger than b";
$b = $a;
}
if ($a > $b) {
echo "a is bigger than b";
} else {
echo "a is NOT bigger than b";
}
if ($a > $b) {
echo "a is bigger than b";
} elseif ($a == $b) {
echo "a is equal to b";
} else {
echo "a is smaller than b";
}
?>
<?php if ($a == 5): ?>
A is equal to 5
<?php endif; ?>

II.3.2. Cu trc whiIe / do...whiIe
<?php
$i = 1;
while ($i <= 10) {
print $i++;
}
$i = 1;
while ($i <= 10):
print $i;
$i++;
endwhile;
$i = 0;
do {
print $i;
} while ($i > 0);
?>

II.3.3. Cu trc for / for...each
<?php
echo "--------------------\n";
for ($i = 1; $i <= 10; $i++) {
print "$i\n";
}
echo "--------------------\n";
for ($i = 1; ; $i++) {
if ($i > 10) break;
print "$i\n";
}
echo "--------------------\n";
$i = 1;
for (;;) {
if ($i > 10)break;
print "$i\n";
$i++;
}
echo "--------------------\n";
for ($i = 1; $i <= 10;
print "$i\n", $i++);
echo "--------------------\n";
for ($i = 1; $i<=20; $i++):
print "$i\n";
endfor
?>

II.3.3. Cu trc for / for...each (2)
foreach (array_expression as $vaIue) statement
foreach (array_expression as $key => $vaIue) statement
<?php
$arr = array("one", "two", "three");
reset ($arr);
while (list(, $value) = each ($arr)) {
echo "Value: $value<br>\n";
}
foreach ($arr as $value) {
echo "Value: $value<br>\n";
}
foreach ($arr as $key => $value) {
echo "Key: $key; Value: $value<br>\n";
}
foreach (array(1, 2, 3, 4, 5) as $v) {
print "$v\n";
}
?>

II.3.4. S dng break, continue trong
cc vng Ip
<?php
$arr = array ('one','two','three','four','stop','five');
while (list (, $val) = each ($arr)) {
if ($val == 'stop')
break; // DiEt +!rea& 4<F cGng HIJc
echo "$val<br>\n";
}
while (list ($key, $value) = each ($arr)) {
if (!($key % 2)) // >K #ua sL lM
continue;
do_something_odd ($value);
}
?>

II.3.4. S dng break, continue trong
cc vng Ip (2)
$i = 0;
while ($i++ < 5) {
echo "Outer<br>\n";
while (1) {
echo "&nbsp;&nbsp;Middle<br>\n";
while (1) {
echo "&nbsp;&nbsp;Inner<br>\n";
continue 3;
}
echo "This never gets output.<br>\n";
}
echo "Neither does this.<br>\n";
}
?>

II.3.5. Cu trc switch
<?php
if ($i == 0) {
print "i equals 0";
} elseif ($i == 1) {
print "i equals 1";
} elseif ($i == 2) {
print "i equals 2";
}
switch ($i) {
case 0:
print "i equals 0";
break;
case 1:
print "i equals 1";
break;
case 2:
print "i equals 2";
break;
}
?>

II.4. Hm
.4.1. Hm t djnh ngha (user-defined)
.4.2. Truyn tham s
.4.3. Gi trj tr v
.4.4. Bin hm

II.4.1. Hm t d[nh ngha (user-defined)
<?php
function foo ($arg_1, $arg_2, ..., $arg_n) {
echo "Example function.\n";
return $retval;
}
?>
<?php
function foo() {
function bar() {
echo "I don't exist until foo() is called.\n";
}
}
// 9hNng thO gPi !ar,- vQ nR chIa HIJc HQnh nghSa
foo();
// >Ty giU thQ cR thO gPi !ar,-
bar();
?>

II.4.2. Truyn tham s
PHP h tro truyn tham s vo hm, truyn tham s di dang
tham chiu (reference), truyn tham s vi gi trj mc djnh
<?php
function takes_array($input) {
echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
function add_some_extra(&$string) {
$string .= 'and something extra.';
}
$str = 'This is a string, ';
add_some_extra($str);
echo $str;// oututs "This is a string' and something extra.
?>

II.4.2. Truyn tham s (2)
function makecoffee ($type = "cappuccino") {
return "Making a cup of $type.\n";
}
echo makecoffee ();
echo makecoffee ("espresso");
function makeyogurt ($type = "acidophilus", $flavour) {
return "Making a bowl of $type $flavour.\n";
}
// /on"t /or& as exected
echo makeyogurt ("raspberry");
function makeyogurt ($flavour, $type = "acidophilus") {
return "Making a bowl of $type $flavour.\n";
}
// /or&s as exected
echo makeyogurt ("raspberry");

II.4.2. Truyn tham s (3)
Ban c th truyn tham s vi s long khng xc djnh. Khi d s s
dung cc hm sau
func_num_args(): S luong tham s
func_get_args(): Ly danh sch cc tham s
<?php
function mwrite() {
$arg = func_get_args();
foreach($arg as $value) echo "$value\n";
}
mwrite("Khoa CNTT", "Truong DHXD", "Lop 46PM1");
?>

II.4.3. Gi tr[ tr v
tr v gi tr[ ca hm, s dng Inh return. C th s dng bt
c kiu no trong gi tr[ tr v ca hm (k c mng v di tung)
<?php
function square ($num) {
return $num * $num;
}
echo square (4); // oututs "43".
function small_numbers() {
return array (0, 1, 2);
}
list ($zero, $one, $two) = small_numbers();
function &returns_reference() {
return $someref;
}
$newref =& returns_reference();
?>

II.4.4. Bin hm
Ban c th s dng cc bin hm (tc I ban c th gi hm dui dang
ten_bien() ).
Bin hm thung duc s dng cho cc hm caIIback
<?php
function foo() {
echo "In foo()<br>\n";
}
function bar($arg = '') {
echo "In bar(); argument was '$arg'.<br>\n";
}
// This is a /raer function around echo
function echoit($string) {
echo $string;
}
$func = 'foo';
$func(); // This calls foo,-
$func = 'bar';
$func('test'); // This calls !ar,-
$func = 'echoit';
$func('test'); // This calls echoit,-
?>

II.4.4. Bin hm (2)
<?php
class Foo {
function Var() {
$name = 'Bar';
$this->$name(); // This calls the >ar,- method
}
function Bar() {
echo "This is Bar";
}
}
$foo = new Foo();
$funcname = "Var";
$foo->$funcname(); // This calls $foo6VDar,-
?>

II.5. Lp & di tung
.5.1. Serialiing di tong di tong trong session
.5.2. Tham chiu bn trong constructor
.5.3. So snh di tong trong PHP4
.5.4. So snh di tong trong PHP5

II.5.1. SeriaIizing di tung - di
tung trong session
Hm serialie() dng d lu tr di tong, hm tr v mt chui cc byte d lu
thng tin ca di tong
Hm unserialie() dng d khi phuc di tong doc lu gi bi hm serialie()
<?php
class AClass {
var $a;
function AClass() {
}
};
$ob1 = new AClass();
$ob1->a = 10;
$ob1->b = 100;
$ob1->c = "Nguyen Phu Quang";
$luu = serialize($ob1);
echo "$luu\n";
$ob2 = unserialize($luu);
var_dump($ob2);
?>

II.5.2. Tham chiu bn trong constructor
<?php
class AClass {
var $m_name;
function AClass($name) {
global $global_ref;
$global_ref[] = &$this;
$this->setName($name);
}
function setName($name) {
$this->m_name = $name;
}
function echoName() {
echo "$this->m_name\n";
}
};
$a = new AClass("a");
$b =& new AClass("b");
$a->setName("quang1");
$global_ref[0]->echoName();
$b->setName("quang2");
$global_ref[1]->echoName();
?>

II.5.3. So snh di tung trong PHP4
<?php
class AClass {
var $m_flag;
};
class BClass extends AClass {
function turnOn() {
$this->m_flag = true;
}
};
$a = new AClass();
$b = new BClass();
$a->m_flag = true;
$b->turnOn();
$c = new BClass();
$c->turnOn();
var_dump($b==$c);
var_dump($a==$b);
?>
Trong PHP4, php so snh cc di tong thc hin theo quy tc don gin
sau: Hai di tong l bng nhau nu chng c cc thuc tnh bng nhau
v cng thuc 1 lp. Quy tc so snh ny cng doc p dung vi php
===

II.5.3. So snh di tung trong PHP4
<?php
class AClass {
var $set;
function addFlag($key, $value) {
$this->set[$key] = $value;
}
function removeFlag($key) {
unset($this->set[$key]);
}
};
$a = $b = new AClass();
$a->addFlag("quang", 1);
$a->addFlag("quang2", 2);
$b->addFlag("quang", 1);
$b->addFlag("quang2", 2);
var_dump($a==$b);
$b->removeFlag("quang");
var_dump($a==$b);
?>

II.5.4. So snh di tung trong PHP5

So snh di tong trong PHP5 c mt s


thay di so vi PHP4

i vi php so snh ==, hai di tong bng


nhau nu c chung cc thuc tnh v cng
thuc 1 lp

i vi php so snh ===, hai di tong


doc gi l bng nhau nu chng cng tham
chiu dn 1 phin bn ca 1 lp

II.6. Tham chiu (reference)
.6.1. Cc trng hop s dung tham chiu
.6.2. Cc trng hop ko s dung tham chiu
.6.3. Truyn tham chiu
.6.4. Tr v tham chiu
.6.5. Unset tham chiu

II.6.1. Cc trung hp s dng tham
chiu

Tham chiu cho php ban s dung 1 bin vi nhiu tn khc nhau

i vi di tong, nn s dung php gn tham chiu khi dng ton t new d trnh php
gn tao ra thm 1 phin bn ca di tong

thay di gi trj ca tham s truyn vo trong hm, ban c th s dung tham chiu

<?php
$a = &$b;
$b = 100;
var_dump($a);
class AClass {};
$c = new AClass();
$d =& new AClass();
function increment(&$num) {
$num++;
}
$a = 10;
increment($a);
var_dump($a);
?>

II.6.2. Cc trung hp ko s dng
tham chiu

Tham chiu gn ging con tr nhng bn cht khng phi l


con tr

Trong trng hop tai v du di dy, var trong hm foo du


tin doc tham chiu dn bin var (global). Tuy nhin sau d
var lai doc tham chiu din bin quang (global)

<?php
function foo(&$var)
{
$var =& $GLOBALS["quang"];
var_dump($var);
}
$quang = "Nguyen Phu Quang";
$var = 100;
foo($var);
var_dump($var);
?>

II.6.3. Truyn tham chiu

Ban c th truyn cc dang tham chiu sau:

Bin foo(a)

Lnh new foo(new AClass())

Tham chiu tr v t hm
<?php
function foo(&$num) {
$num++;
}
function &bar() {
global $a;
return $a;
}
$a=10;
foo($a); var_dump($a);
foo(bar()); var_dump($a);
foo($a = 5); var_dump($a);
foo(5);
?>

II.6.4. Tr v tham chiu

Hm c th tr v tham chiu, khi d ban dt ton t tham chiu


dng trc tn hm

Nu hm tr v tham chiu, d nhn doc tham chiu ban phi


dng ton t gn vi tham chiu dn hm (xem v du)

<?php
function &bar() {
global $a;
return $a;
}
$a = 10;
$c = bar();
$c++;
var_dump($a);
var_dump($c);
$b =& bar();
$b++;
var_dump($a);
var_dump($b);
?>

II.6.5. Unset tham chiu

Ban c th s dung lnh unset() d loai b mt bin khi b


nh

Nu unset doc s dung vi 1 bin tham chiu, PHP s kim


tra xem cn bin no cng tham chiu dn vng nh hay
khng ri mi loai b bin khi b nh

<?php
$a = &$b;
$b = 100;
unset($a);
var_dump($a);
var_dump($b);
unset($b);
var_dump($a);
var_dump($b);
?>

III. Lm vic vi Form
.1. Cc bin SuperGlobal
.2. Bin SERER
.3. Ly thng tin t form
.4. Kt hop m HTML v PHP trong 1 trang
.5. S dung Hidden field d lu trang thi
.6. Redirect
.7. Form Upload file

III.1. Cc bin SuperGIobaI

Cc bin global l cc bin doc khai bo mc ngoi cng ca PHP doc s


dung chung cho mi module

Cc bin SuperGlobal l cc bin (mng) doc PHP tao ra d lu cc thng tin cn


thit
Contains aII gIobaI variabIes associated with the current script
$GLOBALS
VariabIes made avaiIabIe by the server
$_SERVER
A combined array containing vaIues from the $_GET, $_POST, and $_COOKIES
supergIobaI arrays
$_REQUEST
Contains keys and vaIues submitted to the script using the HTTP post
method
$_POST
Contains keys and vaIues submitted to the script using the HTTP get method
$_GET
Contains information about upIoaded fiIes
$_FILES
Contains keys and vaIues set by the script's sheII context
$_ENV
Contains keys and vaIues set as browser cookies
$_COOKIE
Description Array

III.2. Bin $_SERVER
http://p24.corrosive The address of the
page from which the
request was made.
$_SERVER['HTTP_REFERER']
/phpbook/source/Iisting10.1.php?
name=matt
The fuII address of the
request, incIuding
query string.
$_SERVER['REQUEST_URL']
name=matt&address=unknown For GET requests, the
encoded data sent
appended to the URL.
$_SERVER['QUERY_STRING']
POST Whether the request
was GET or POST.
$_SERVER['REQUEST_METHOD']
158.152.55.35 The IP address of the
cIient.
$_SERVER['REMOTE_ADDR']
MoziIIa/4.6 -(X11; I;Linux2.2. 6-
15apmac ppc)
The name and version
of the cIient.
$_SERVER['HTTP_USER_AGENT']
/phpbook/source/Iisting10.1.php The current script.
SuitabIe for use in
Iinks and form eIement
action arguments.
$_SERVER['PHP_SELF']
ExampIe Contains VariabIe

III.2. Bin $_SERVER (2)
oan lnh sau lit k tt c cc thng tin ca bin
SERER
<?php
foreach ($_SERVER as $key=>$value) {
echo "[$key]=$value\n";
}
?>

III.3. Ly thng tin t form
.3.1. Ly thng tin t form bng cc mng
superglobal
.3.2. mport thng tin ca form vo cc bin
global
.3.3. Ly thng tin ca form bng mng do
ngi dng djnh ngha

III.3.1. Ly thng tin t form bng cc
mng supergIobaI
D Iiu t form duc submit In server thng qua cc phuong thc: get,
post
Iy duc thng tin t form, ban c th s dng cc mng supergIobaI
tuong ng $_POST[tn_controI], $_GET[tn_controI],
$_REQUEST[tn_controI] (REQUEST c th s dng cho c POST v GET)
<?php
var_dump($_POST["Submit"]);
var_dump($_GET["Submit"]);
var_dump($_REQUEST["Submit"]);
if ($_POST["Submit"]=="Submit") {
echo $_POST["UserInput1"];
}
?>
<FORM method="POST" name="myForm">
<INPUT TYPE="TEXT" name="UserInput1">
<INPUT TYPE="SUBMIT" value="Submit" name="Submit"></FORM>

III.3.2. Import thng tin ca form vo
cc bin gIobaI
thun tin cho ngui Ip trnh, PHP cung cp hm
import_request_variabIes() cho php dua cc tham s GET, POST v
COOKIE vo thnh cc bin gIobaI
C php
bool import_request_variables(string types, [string prefix])
types: Ch ra Ioai thng tin no duc import, c th kt hp gia cc gi tr[
g, p, c (get, post, cookie)
prefix: tin t cho tn bin
<?php
import_request_variables("gpc", "ui_");
echo "$ui_Submit\n";
if ($ui_Submit=="Submit") {
echo "$ui_UserInput1\n";
}
?>
<FORM method="POST" name="myForm"><INPUT TYPE="TEXT"
name="UserInput1">
<INPUT TYPE="SUBMIT" value="Submit" name="Submit"></FORM>

III.3.3. Ly thng tin ca form bng
mng do ngui dng d[nh ngha

Nhng cch ly thng tin t form d nu trn cho


php chng ta lm vic tt vi cc control don
(c 1 gi trj)

i vi cc control c nhiu gi trj nh select hay


checkbox, ny sinh vn d l lm sao nhn doc
tt c cc control doc la chn

gii quyt vn d ny, dt tn cc control vi


kt thc l du ngoc vung , khi d d liu
truyn t form dn server s l mng

III.3.3. Ly thng tin ca form bng
mng do ngui dng d[nh ngha
<?php
var_dump($_REQUEST["product"]);
?>
<FORM method="POST" name="AForm">
<INPUT TYPE="CHECKBOX" name="product[]
value="Sony Ericson">Sony Ericson<br>
<INPUT TYPE="CHECKBOX" name="product[]
value="Motorola">Motorola<br>
<INPUT TYPE="CHECKBOX" name="product[]
value="Samsung">Samsung<br>
<INPUT TYPE="CHECKBOX" name="product[]
value="Hang tau">Hang tau<br>
<INPUT TYPE="SUBMIT" name="Submit
value="Submit"><br>
</FORM>

III.4. Kt hp m HTML v PHP trong 1
trang

i vi cc trang PHP nh, ban thng mun kt


hop form gi thng tin vi cc doan script PHP
x l thng tin. iu ny c th d dng thc
hin bng cch d cc kt hop cc cu trc diu
khin r nhnh vi cc doan m HTML.

dt doan m HTML vo trong cu trc r


nhnh, s dung kt hop cc khi lnh PHP (xem
v du)

III.4. Kt hp m HTML v PHP trong 1
trang (2)
<?php
if ( is_array($_REQUEST["product"]) &&
!array_search("Motorola", $_REQUEST["product"] )) {
?>
<h1>Cam on ban da su dung san pham Motorola</h1>
<?php
} else {
?>
<FORM method="POST" name="AForm">
<INPUT TYPE="CHECKBOX" name="product[]
value="Sony Ericson">Sony Ericson<br>
<INPUT TYPE="CHECKBOX" name="product[]
value="Motorola">Motorola<br>
<INPUT TYPE="CHECKBOX" name="product[]
value="Samsung">Samsung<br>
<INPUT TYPE="CHECKBOX" name="product[]
value="Hang tau">Hang tau<br>
<INPUT TYPE="SUBMIT" name="Submit" value="Submit"><br>
</FORM>
<?php
}
?>

III.5. S dng Hidden fieId d Iuu trang
thi
lu thng tin chung ca cc form gia cc ln submit (v du: S ln
submit), cch don gin nht l s dung trng n (hidden field) trong form
<?php
$g_nSubmit = $_REQUEST["nSubmit"];
if ($g_nSubmit==null) $g_nSubmit=0; else $g_nSubmit++;
if ($g_nSubmit>3) echo "Submit gi ma nhieu the?<br>";
echo "$g_nSubmit<br>";
?>
<FORM method="POST" name="AForm">
<input type="hidden" name="nSubmit" value="<?echo
$g_nSubmit;?>">
<INPUT TYPE="SUBMIT" name="Submit" value="Submit"><br>
</FORM>

III.6. Redirect

R rng l vic hardcode HTML cng vi s dung nhiu khi


PHP xen ln HTML l khng tt. Mt cch don gin v hiu
qu hon l s dung Redirect d dn hng ngi dng dn
cc trang thch hop (v du: Trang dng nhp nu ngi dng
cha dng nhp, trang chc mng nu ngi dng dng nhp
thnh cng)

lm doc vic ny, trc ht ta tm hiu co ch lm vic


gia PHP script v client. u tin, d giao tip vi client, PHP
t dng gi cc thng tin header cho client. Tuy nhin, ban vn
c th t gi header.

dn hng client dn trang khc, ban chi cn don gin di


header bng hm header(). s dung hm header() ban phi
dm bo rng cho c d liu no d doc gi cho client (s
dung hm headersent() d kim tra)

III.6. Redirect (2)
<?php
$g_nSubmit = $_REQUEST["nSubmit"];
if ($g_nSubmit==null) $g_nSubmit=0; else $g_nSubmit++;
if ($g_nSubmit>5) {
header("Location:ham.html");
exit;
} else
if ($g_nSubmit>3) echo "Submit gi ma nhieu the?<br>";
echo "$g_nSubmit<br>";
?>
<FORM method="POST" name="AForm">
<input type="hidden" name="nSubmit"
value="<?=$g_nSubmit;?>">
<input type=submit" name="Submit" value="Submit"><br>
</FORM>

III.7. Form UpIoad fiIe
Ngi dng c th gi cc file (upload) ln server l mt chc nng khng th
thiu di vi cc ng dung Web-based
form c th upload file, ban phi xc djnh form enctype:
ENCTPE=multipart/form-data
i PHP, ban c th xc djnh kch thc ln nht ca file upload bng cch
dt thm 1 hidden field c tn MAXFLESZE trc control file
<form enctype="multipart/form-data"
action="<?=$_SERVER['PHP_SELF']?>" method="post">
<p>
<input type="hidden" name="MAX_FILE_SIZE" value="102400"/>
<input type="file" name="fupload" /><br/>
<input type="submit" value="upload!" />
</p>
</form>

III.7. Form UpIoad fiIe (2)

Mng FLE
image/gif
MIME type of uploaded file
(where given by client)
$_FILES['fupload']['type']
UPLOAD_ERR_FOR
M_SIE
An error code
corresponding to a PHP
constant
$_FILES['fupload']['e!!o!']
68! "i#e (in bytes) of uploaded
file
$_FILES['fupload']['"i#e']
/tmp/p$p!Df%&
Path to te$porary file
$_FILES['fupload']['tmp_'a
me']
te"t(gif
%a$e of uploaded file
$ FILES['fupload'][''ame']
E&a$ple 'ontains Ele$ent

(ile was not uploaded
* UPLOAD_ERR_&O_FILE
(ile only partially uploaded
+ UPLOAD_ERR_PAR,IAL
(ile si#e e&ceeds li$it set in hidden
ele$ent na$ed MA-_FILE_SIE
. UPLOAD_ERR_FORM_SI
E
(ile si#e e&ceeds p$p(i'i li$it set in
upload_ma/_file"i#e
0 UPLOAD_ERR_I&I_SIE
%o proble$
1 UPLOAD_ERR_O2
E&planation
)alu
e 'onstant %a$e

III.7. Form UpIoad fiIe (3)

<?php
if ($_REQUEST["submit"]=="upload!") {
echo $_!"ES["#upload"]["$%%o%"]& "\n"'
echo $_!"ES["#upload"]["si($"]& "\n"'
echo $_!"ES["#upload"][")am$"]& "\n"'
echo $_!"ES["#upload"]["tmp_)am$"]& "\n"'
if ($_!"ES["#upload"]["$%%o%"]==0) {
$sou%*$ = $_!"ES["#upload"]["tmp_)am$"]'
$d$st = $_!"ES["#upload"][")am$"]'
mo+$_upload$d_#il$($sou%*$& $d$st)'
,
,
?-
<#o%m $)*t.p$="multipa%t/#o%m0data" m$thod="post"-
<p-
<i)put t.p$="hidd$)" )am$="123_!"E_S!4E" +alu$="567866" /-
<i)put t.p$="#il$" )am$="#upload" /-<b%/-
<i)put t.p$="submit" +alu$="upload!" )am$="submit" /-
</p-
</#o%m-

IV. Lm vic vi fiIe
.1. S dung include()
.2. S dung includeonce() v includepath
cho cc d n ln
.3. Kim tra file
.4. c, ghi file
.5. Lm vic vi th muc

IV.1. S dng incIude()

Lnh include() cho php ban phi hop gia cc file trong mt
PHP proect, ko ging nh c php include ca ngn ng C,
lnh ny khng chn m lnh vo file m thc thi file php ging
nh c php gi hm

include() s dung d chia s cc hm dng chung, cc doan


m chung trong mt proect c nhiu file

Nu khng tm thy file, include() thng bo warning nhng


khng dng chong trnh

PHP cung cp 1 lnh tong t include() l require(), lnh ny


c s khc bit l s dng ngay chong trnh khi khng tm
thy file

IV.1. S dng incIude() (2)

<!00il$59php0-
<?php
echo "This is #%om #il$ 5\n"'
?-

<!00il$79php 0-
<?php
echo "This is #%om #il$ 7\n"'
include("#il$59php")'
include("#il$:9php")'
echo "This is #%om #il$ 7\n"'
?-

IV.1. S dng incIude() (3)

include() thc hin li gi dn file php, do d ban c th tr


v gi trj t file PHP doc include

<!00il$559php00-
<?php
return 4 ; 4'
?-

<!00il$579php00-
<?php
echo "This is #%om #il$ 57\n"'
$%$t<al = include("#il$559php")'
echo "R$tu%) +alu$ #%om #il$ 55= \$%$t<al=
$retVal\n"'
echo "This is #%om #il$ 57\n"'
?-

IV.1. S dng incIude() (4)

Ban c th dt lnh include bn trong 1 cu trc diu kin hoc


cu trc lp, khi d ty theo diu kin ca cu trc m include()
c doc thc hin hay khng, 1 hay nhiu ln

<!--File22.php-->
<?php
if ($j==null) $j=10; else $j++;
return $i+$j;
?>

<!--File21.php-->
<?php
for ($i=0; $i<10; $i++) {
echo include("File22.php"), "\n";
}
?>

IV.2. S dng incIude_once() v
incIude_path cho cc d n In

includeonce() ging nh include(), tuy nhin c dim khc bit l


chi include 1 ln, ln sau nu gp lai file ny th ko include na

includeonce() s dung cho cc hm th vin dng chung d


trnh trng hop khi nhiu file cng include dn 1 file, sau d cc
file ny lai include ln nhau (so snh vi ifdefine trong file header
ca ngn ng C)

includeonce() phn bit ch hoa, ch thng

<?php
include_once("a.php"); // this /ill include a.h
include_once("A.php"); // this /ill include a.h
again on Bindo/sC
?>

IV.2. S dng incIude_once() v
incIude_path cho cc d n In (2)

Trong qu trnh lm vic, ban hn c nhiu hm doc


dng chung gia nhiu file trong 1 proect, gia nhiu
proect. s dung cc hm ny, ban c th p dung
cc cch sau:

include file theo dng dn tuyt di: Cch ny d v khi ci


dt trn my khc s khng tm thy file doc include

include file theo dng dn tong di: Cch ny tt hon,


nhng mi khi di vj tr ca file doc include th phi sa lai
tai tt c cc file thc hin li gi include

Cch tt nht l s dung includepath (thit lp trong file


PHP.N) di vi nhng file th vin dng chung doc s
dung nhiu (ging nh di vi ngn ng C)

IV.2. S dng incIude_once() v
incIude_path cho cc d n In (3)

thit lp includepath, ban c nhng cch sau:

thay di includepath trong PHP.N

dng lnh setincludepath()

<?php
var_dump(get_include_path());
set_include_path('/inc'); // Bor&s as of PHP 8.1.A
var_dump(get_include_path());
restore_include_path();
var_dump(get_include_path());
?>

dng lnh iniset()

<?php
var_dump(ini_get("include_path"));
ini_set("include_path", "/inc"); // Bor&s in all PHP versions
var_dump(ini_get("include_path"));
ini_restore("include_path");
var_dump(ini_get("include_path"));
?>

IV.3. Kim tra fiIe

fileexist(), isfile(), isdir(), isreadable(), iswriteable(), isexecutable(), filesie(), fileatime()

<?php
function outputFileTestInfo( $file ) {
if ( ! file_exists( $file ) ) {
print "$file does not exist<br/>";
return;
}
print "$file is ".(is_file( $file )?"":"not ")."a file<br/>\n";
print "$file is ".(is_dir( $file )?"":"not ")."a directory<br/>\n";
print "$file is ".(is_readable( $file )?"":"not ")."readable<br/>\n";
print "$file is ".(is_writable( $file )?"":"not ")."writable<br/>\n";
print "$file is ".( filesize($file))." bytes<br/>\n";
print "$file was accessed on "
.date( "D d M Y g:i A", fileatime( $file ) )."<br/>\n";
print "$file was modified on "
.date( "D d M Y g:i A", filemtime( $file ) )."<br/>\n";
print "$file was changed on"
.date( "D d M Y g:i A", filectime( $file ) )."<br/>\n";
}
outputFileTestInfo("c:\\windows\\system32\\cmd.exe");
?>

IV.4. c, ghi fiIe

fopen($filename, $mode);
fwrite($handle, $string);
fread($handle, $length);
fgets($handle);
sprintf($format);
fscanf($handle, $format);
fseek($handle, $offset);
fclose($handle);
file_get_contents($filename);

IV.4. c, ghi fiIe (2)
<?php
$var1 = 10;
$var2 = "This is a String";
$var3 = true;
$f = fopen("test.txt", "wt");
fwrite($f, "$var1 $var2 $var3\n");
fwrite($f, "$var1\n$var2\n$var3\n");
fclose($f);
echo "Read line by line......\n";
$f = fopen("test.txt", "rt");
while (!feof($f)) {
$line = fgets($f);
echo "$line";
}
fclose($f);
echo "Read all file by fread......\n";
$f = fopen("test.txt", "rb");
$myfile = fread($f, filesize("test.txt"));
echo $myfile;
fclose($f);
echo "Read all file......\n";
$myfile = file_get_contents("test.txt");
echo($myfile);
?>

IV.4. c, ghi fiIe (3)

<?php
$+a%5=10'
$+a%7=100'
$+a%:=5669:8:8'
$+a%8="T$st st%i)>"'
$#=#op$)("t$st9t?t"& "@t")'
#@%it$($#& sp%i)t#("Ad A569:# A569:l#\n\r"& $+a%5& $+a%7& $+a%:))'
#@%it$($#& sp%i)t#("As"& $+a%8))'
#*los$($#)'
$#=#op$)("t$st9t?t"& "%t")'
if (list($+5& $+7& $+:& $+8) = #s*a)#($#& "Ad A# Al#\n\rAs")) {
+a%_dump($+5)'
+a%_dump($+7)'
+a%_dump($+:)'
+a%_dump($+8)'
,
$+8 = #>$ts($#)'
+a%_dump($+8)'
#*los$($#)'
?-

IV.4. c, ghi fiIe (4)

<?php
class 2Blass {
,'
$ob5 =C new 2Blass()'
$ob50-a = 10'
$ob50-b = 566967:'
$ob50-* = "T$st St%i)>"'
+a%_dump($ob5)'
$# = #op$)("t$st9t?t"& "@b")'
#@%it$($#& s$%iali($($ob5))'
#*los$($#)'
$# = #op$)("t$st9t?t"& "%b")'
$ob7 = u)s$%iali($(#>$ts($#))'
#*los$($#)'
+a%_dump($ob7)'
?-

IV.5. Lm vic vi thu mc

mkdir(), rmdir(), opendir(), readdir(), closedir()

<?php
$di%=op$)di%("*=\\@i)do@s")'
while ($#il$=%$addi%($di%)) {
echo "$file\n"'
,
*los$di%($di%)'
?-

V. PHP & CSDL
.1. S dung PHP d kt ni vi CSDL
.2. PEAR DB
.3. Cc chc nng nng cao vi PEAR DB

V.1. S dng PHP d kt ni vi
CSDL

C 2 cch kt ni PHP vi CSDL

S dung cc hm ring cho tng loai CSDL

u dim: Tc d cao do doc thit k cho tng CSDL cu


th. Tn dung doc u dim ca tng loai CSDL

Nhoc dim: Khng c tnh kh chuyn gia cc CSDL

S dung cc hm dc lp CSDL (th vin PEAR


DB)

u dim: C th s dung trn nhiu CSDL khc nhau

Nhoc dim: Chm hon phong php trn, khng tn


dung doc u dim ca tng CSDL.

V.1. S dng PHP d kt ni vi CSDL
(2)

Ci dt th vin PEAR

u cu: PHP phin bn 5.0

Ci dt PHP

Chay go-pear.bat

Theo cc hng dn trong chong trnh (cc tham s chi cn dt mc


djnh)

Nu khng cai dt PEAR, ma copy t may khac, phai thm vao


C:/Windows/PHP.N 2 dong nh o doi

Cu hnh Zend Studio d lm vic vi PEAR DB

Thm vo file Zenddir/bin/php5/php.ini 2 dng

includepath=.C:/php/pear

extensiondir=c:/php/ext

Copy file libMySQL.dll vo Windows/System (nu ban s dung S)



Cac buoc cai dt kiu mi n Iin

Cai S, cai Mysql 5.0, cai PHP

Copy \Mysql\bin\libMysql.dll dn
c:\windows\system32

Copy PHP.rar de ln th muc c:/PHP

Sa ni dung c:\windows\system32\PHP.N, thm


vao cac dong sau (d o cui file)
includepath=.C:/php/pear
extensiondir= c:/php/ext
extension=phpmysql.dll

Sau do, co th chay doc trn local host (trn Zend


thi phai config thm, tt nht la dng config)

V.2. PEAR DB
<?php
require("DB.php");
$dsn = "mysql://root:root@localhost/dhxd";
$db = DB::connect($dsn);
if (DB::isError($db)) die($db->getMessage());
$table = $db->query("SELECT * FROM SV");
if (DB::isError($table)) die($table->getMessage());
echo "<table border='1'>";
while ($row = $table->fetchRow()) {
echo "<tr>
<td>$row[0]</td>
<td>$row[1]</td>
<td>$row[2]</td>
<td>$row[3]</td>
</tr>";
}
echo "</table>";
?>

V.2. PEAR DB (2)
.2.1. Data source name
.2.2. Kt ni vi co s d liu
.2.3. Kim tra li
.2.4. Thc thi query
.2.5. Ly kt qu t query
.2.6. Gii phng b nh

V.2.1. Data source name

dsn=Data Source Name

type://username:passwordprotocolhost
spec/database

du:

mysql:///webdb mysql://localhost/webdb
mysql://bondviewlocalhost/webdb
mysql://bondviewtcplocalhost/webdb
mysql://bondview:007localhost/webdb
FrontBase Fbsql
Informix Ifx
SyBase Sybase
ODBC Odbc
Oracle 7/8/8i oci8
Microsoft SQL Server Mssql
Mini SQL Msql
InterBase Ibase
PostgreSQL Pgsql
MySQL Mysql
*atabase +ype

V.2.2. Kt ni vi co s d Iiu

Khi d c DSN, ban c th kt ni bng hm


DB::connect vi c php sau:
D
$db = EF==*o))$*t(DSN [& options ])'

options c th l 1 gi trj Boolean hoc 1 mng

$db = EF==*o))$*t($ds)& array(Gd$bu>G =- 1&


Goptimi($G =- Gpo%tabilit.G))'

V.2.3. Kim tra Ii

Cc phong thc ca DB tr v DBERRR nu c li trong


qu trnh thc hin

Ban c th kim tra 1 kt qu tr v c phi l li khng bng


hm DB::isError()

Nu DB::isError() tr v true, kt qu tr v ca ban l li, c


th xem thng bo li bng phong thc tenbien-
>getMessage()

$db = EF==*o))$*t($datasou%*$)'
if (EF==isE%%o%($db)) {
die($db0->$t1$ssa>$( ))'
,

V.2.4. Thc thi query

thc thi query, s dung phong thc query() ca Database


bect (di tong tr v khi ban kt ni thnh cng vi CSDL
bng hm DB::connect() )

$db = EF==*o))$*t($datasou%*$)'
$%$sult = $db0-Hu$%.(sHl)'

Cng tong t nh DB::connect(), ban c th kim tra li bng


DB::isError()

if (EF==is$%%o%($%$sult)) {
die($%$sult0->$t1$ssa>$())'
,

V.2.5. Ly kt qu t query

$row = $result->fetchRow([ mode ]);

Hm fetchRow() tr v mng cc gi trj trn dng hoc


DBERRR (nu c li)

<?php
$db = DB::connect($datasource);
$result = $db->query(sql);
while ($row = $result->fetchRow( )) {
if (DB::isError($row)) {
die($row->getMessage( ));
}
// do something /ith the ro/
}
?>

V.2.5. Ly kt qu t query (2)

row = result->fetchRow( mode )

mode:

DBFETCHMDERDERED: Cc ct doc lit


k trn row theo th t 0,1,2...

DBFETCHMDEASSC : Cc ct doc lit k


vi kha l tn ca cc ct

DBFETCHMDEBECT: Cc ct doc lit


k thnh cc trng ca di tong

V.2.5. Ly kt qu t query (3)
<?php
require("DB.php");
$db = DB::connect("mysql://root:root@localhost/dhxd");
$table = $db->query("select * from sv");
$row = $table->fetchRow();
var_dump($row);
$row = $table->fetchRow(DB_FETCHMODE_ASSOC);
var_dump($row);
$row = $table->fetchRow(DB_FETCHMODE_OBJECT);
var_dump($row);
echo "Hoten: {$row->hodem} {$row->ten}, Ngay sinh:
{$row->ngaysinh}";
?>

V.2.6. Gii phng b nh

<?php
require("DB.php");
$db =
DB::connect("mysql://root:root@localhost/d
hxd");
$table = $db->query("select * from sv");
$row = $table->fetchRow();
unset($row);
$table->free();
$db->disconnect();
?>

V.3. Cc chc nng nng cao vi
PEAR DB
.3.1. Query template
.3.2. Prepare/Execute
.3.3. Cc hm tin ch
.3.4. Cc thng tin tr v t query()
.3.5. Metadata

V.3.1. Query tempIate

xy dng cc query, nu dng php ni xu k t rt d gy


nhm ln do khng nhn thy tng th ca cu lnh SQL (nht l vi
cc trng hop c s dung du nhy)

Trong trng hop ny, PHP cung cp 1 cng cu hoat dng cho
php truyn tham s trong cu lnh SQL ging nh lnh printf,
trong d s dung cc k hiu

?: Cho s hoc string (du nhy s doc b sung khi cn thit)

: Cho s hoc string (khng s dung du nhy)

: Tn file (dng cho cc trng BLB)

<?php
require("EF9php")'
$db = EF==*o))$*t("m.sHl=//%oot=%ootIlo*alhost/dh?d")'
$%o@ = array("J>u.$) <a)"& "2")'
$db0-Hu$%.("!JSERT !JTK s+ (hod$m& t$)) <2"UES(?&?)"& $%o@)'
?-

V.3.2. Prepare/Execute

Khi ban thc hin nhiu cu lnh ging nhau, cch tt nht l djch cu lnh SQL trc khi
thc hin bng phong thc prepare()

Sau khi djch SQL, ban c th thc hin cu lnh SQL bng cch dng 2 lnh sau:

response = db->execute(compiled, values) (values: mng 1 chiu cc gi trj)

responses = db->executeMultiple(compiled, values) (values: mng 2 chiu cc dng, mi dng l


1 mng 1 chiu cc gi trj)

<?php
require("EF9php")'
$db = EF==*o))$*t("m.sHl=//%oot=%ootIlo*alhost/dh?d")'
$*ompli$d = $db0-p%$pa%$("!JSERT !JTK s+ (hod$m& t$))
<2"UES(?&?)")'
$%o@s=array( array("J>u.$) <a)"& "2")&
array("J>u.$) <a)"& "F")&
array("J>u.$) <a)"& "B")&
array("J>u.$) <a)"& "E") )'
foreach ($%o@s as $%o@) {
$db0-$?$*ut$($*ompli$d& $%o@)'
,
$db0-$?$*ut$1ultipl$($*ompli$d& $%o@s)'
?-

V.3.3. Cc hm tin ch

Ngoi cc hm chung, PEAR DB cn cung cp cc hm cho php thc hin


nhanh 1 s chc nng hay doc s dung: getne(), getRow(), getCol(),
getAssoc(), getAll()
<?php
require("DB.php");
$db = DB::connect("mysql://root:root@localhost/dhxd");
$result = $db->getRow("SELECT * FROM sv");
var_dump($result);
$result = $db->getOne("SELECT count(*) FROM sv");
var_dump($result);
$result = $db->getCol("SELECT * FROM sv", "ten");
var_dump($result);
$result = $db->getAssoc("SELECT * FROM sv");
var_dump($result);
$result = $db->getAll("SELECT * FROM sv");
var_dump($result);
?>

V.3.4. Cc thng tin tr v t query()
Ban c th ly thng tin v cc dng, ct kt qu tr v t cu lnh SQL qua
cc hm numRows(), numCols(), tablenfo(), affectedRows()
<?php
require("DB.php");
$db = DB::connect("mysql://root:root@localhost/dhxd");
$table = $db->query("SELECT * FROM sv");
var_dump($table->numRows());
var_dump($table->numCols());
var_dump($table->tableInfo());
$result = $db->query(
"INSERT INTO sv (hodem, ten) VALUES (?,?)",
array("Nguyen Phu", "Quang"));
var_dump($result);
var_dump($db->affectedRows());
?>

V.3.5. Metadata
Hm getListf() s dung d ly thng tin v users, databases, tables, views,
functions (phu thuc vo s h tro ca CSDL m ban dang s dung)
<?php
require_once("DB.php");
$db = DB::connect("mysql://root:root@localhost/dhxd");
$result = $db->getListOf("users");
var_dump($result);
$result = $db->getListOf("databases");
var_dump($result);
$result = $db->getListOf("tables");
var_dump($result);
?>

V.3.6. Transaction
Nhiu co s d liu h tro Transaction safe, d s dung
transaction safe trong PHP, ban s dung cc lnh commit(),
rollback()
c th rollback(), ban phi thit lp autocommit l false
<?php
require_once("DB.php");
$db = DB::connect("mysql://root:root@localhost/dhxd");
$db->autocommit = false;
$result = $db->query("DELETE FROM sv;");
$db->rollback();
$db->autocommit = true;
?>

VI. T chc ng dng PHP
.2. H thng template
.3. Qun l output
.4. Qun l li
.5. Ti u ha

VI.2. H thng tempIate

Trang Web c giao din d thay di l 1 tiu ch rt


quan trng

Nu kt hop m HTML v PHP khng tt th rt kh cho


ngi thit k giao din v ngi lp trnh lm vic vi
nhau kh nng thay di giao din kh khn

Mt phong php hiu qu l s dung cc file template


(.HTML doc thit k t cc chong trnh: DW,
FrontPage...). Cc file template ny thng khng cha
m PHP m chi c cc thng tin di dang quy c
(thng l cc tn gi, gi trj doc dt theo 1 quy c
nht djnh, cc gi trj ny s doc thay th khi chay
chong trnh bng PHP)

VI.2. H thng tempIate (2)
<?php
$templatePath = "./templates/";
function MakeWebPageFromTemplate($templateName, $params)
{
global $templatePath;
$templateName = $templatePath . $templateName;
if ($f = fopen($templateName, "rt")) {
$templateContent = fread($f, filesize($templateName));
fclose($f);
}
$templateContent = str_replace(
"\"./", "\"" . $templatePath, $templateContent);
foreach ($params as $paramName=>$paramVal) {
$templateContent = str_replace(
$paramName, $paramVal, $templateContent);
}
return $templateContent;
}
?>

VI.3. Qun I output

Thng th cc hm ghi thng tin ra browser. Tuy nhin c nhiu trng hop chng
ta khng mun nh vy.

Ban c th s dung vng dm ra (output buffer) d cc lnh ghi thng tin ghi d liu
ln d

Cc hm vi output buffer: obstart(), obgetlength(), obgetcontents(),


obflush(), obendflush() obendclean()

<?php
ob_sta%t()'
phpi)#o()'
$phpi)#o = ob_>$t_*o)t$)ts()'
ob_$)d_*l$a)()'
if (st%pos($phpi)#o& "modul$_pd#") === FALSE) {
echo "Lou do )ot ha+$ ME suppo%t i) .ou% MNM& so%%.9"'
, else {
echo "Bo)>%atulatio)s& .ou ha+$ ME suppo%t!"'
,
?-

VI.4. Qun I Ii
.4.1. Thng bo li
.4.2. Giu li
.4.3. Pht sinh li
.4.4. Hm x l li
.4.5. Log li

VI.4.1. Thng bo Ii

Thng thng, khi c li, thng bo li doc in ra


output

C 3 mc d thng bo: notices, warnings, errors

Mc djnh ca PHP l cc thng bo warning, error


s doc in ra browser, ban c th thay di trong
PHP.N hoc trong thi gian chay bng hm
errorreporting() (cc tham s EERRR
EPARSE ECREERRR
ECMPLEERRR EUSERERRR)

VI.4.1. Thng bo Ii (2)
ll of t!e a"ove o#tions E_ALL
$%ntime &arnings generate' "y a call to trigger_error( ) E_USE_!O"I#E
$%ntime &arnings generate' "y a call to trigger_error( ) E_USE_$A!I!%
$%ntime errors generate' "y a call to trigger_error( ) E_USE_EO
(arnings generate' internally "y t!e )en' scri#ting engine E_#OMPILE_$A!I!%
*rrors generate' internally "y t!e )en' scri#ting engine E_#OMPILE_EO
(arnings generate' internally "y P+P E_#OE_$A!I!%
*rrors generate' internally "y P+P E_#OE_EO
$%ntime notices E_!O"I#E
Com#ile,time #arse errors E_PASE
$%ntime &arnings E_$A!I!%
$%ntime errors E_EO
Meaning )alue

VI.4.2. Giu Ii

S dung ton t d ngn khng cho output li ra browser

Thit lp trackerrors trong php.ini d bt doc cc thng bo li qua bin


phperrormsg

ngn khng cho tt c cc thng bo li trn browser, s dung hm


errorreporting(0)

<?php
i)i_s$t("t%a*O_$%%o%s"& "5")'
$+alu$ = 2/0'
$+alu$ = I(2/0)'
echo "$php_errormsg"'
i)i_%$sto%$("t%a*O_$%%o%s")'
?-

<?php
$%%o%_%$po%ti)>(0)'
i)i_s$t("t%a*O_$%%o%s"& "5")'
$+alu$ = 2/0'
echo "$php_errormsg"'
i)i_%$sto%$("t%a*O_$%%o%s")'
?-

VI.4.3. Pht sinh Ii

Ban c th lm pht sinh li ngi dng bng hm


triggererror

triggererror(message , type)

type: EUSERERRR, EUSERWARNNG,


EUSERNTCE (default)

<?php
function di+id$%($a& $b) {
if($b == 0) {
t%i>>$%_$%%o%(G$b *a))ot b$ 6G& _USER_ERRKR)'
,
return($a / $b)'
,
?-

VI.4.4. Hm x I Ii

Giu tt c cc li khng phi l mt phong n hay, d qun


l li tt hon, ban nn dng hm x l li (error handler)

Error handler doc thit lp bng hm seterrorhandler(),


khi phuc lai bng hm restoreerrorhandler()

<?php
function m._ha)dl$%($$%%o%& $$%%o%st%i)>&
$#il$)am$& $li)$& $s.mbol)
{
echo "$errorP$errorstringP$filenameP$line\n"'
,
s$t_$%%o%_ha)dl$%(Gm._ha)dl$%G)'
echo 4/0'
$# = #il$("li)hti)h")'
?-

VI.4.5. Log Ii

VI.5. Ti uu ha

VII. Hnh nh
.1. u cu phn mm
.2. Tao v v nh
.3. Text
.4. Co dn nh

VII.1. Yu cu phn mm

i PHP ban c th s dung cc hm graphic d v


ra cc hnh nh v lu tr di dang file (GF, PNG,
PG)

thc hin doc chc nng ny, ban cn phi ci


dt b th vin GD (http://www.boutell.com/gd/ )

bit th vin GD d doc ci dt hay cha, c


th s dung hm phpinfo() hoc hm gdinfo()

i vi b PHP full (v5.0) c dy d th vin PEAR


di km, d chay GD ban chi vic thit lp trong file
php.ini: extension=phpgd2.dll

VII.2. Tao v v nh

<!00 #il$= *a%o9php 00-


<?php
$im = ima>$*%$at$(30& 30)'
$%$d = ima>$*olo%allo*at$($im& 0xff& 0x00& 0x00)'
$blu$ = ima>$*olo%allo*at$($im& 0x00&0x00&0xff)'
$bla*O = ima>$*olo%allo*at$($im& 0x00& 0x00& 0x00)'
ima>$#ill$d%$*ta)>l$($im& 0& 0& 29& 29& $bla*O)'
ima>$#ill$d%$*ta)>l$($im& 0&0&15&15&$%$d)'
ima>$#ill$d%$*ta)>l$($im& 15&15&29&29&$blu$)'
ima>$Qp$>($im)'
?-
<!00 #il$= 59html 00-
<html-
Ea. la *a%o <im> s%*="*a%o9php"/-
</html-

<?php
$im = ima>$*%$at$(30& 30)'
$%$d = ima>$*olo%allo*at$($im& 0xff& 0x00& 0x00)'
$blu$ = ima>$*olo%allo*at$($im& 0x00&0x00&0xff)'
$bla*O = ima>$*olo%allo*at$($im& 0x00& 0x00& 0x00)'
ima>$#ill$d%$*ta)>l$($im& 0& 0& 29& 29& $bla*O)'
ima>$#ill$d%$*ta)>l$($im& 0&0&15&15&$%$d)'
ima>$#ill$d%$*ta)>l$($im& 15&15&29&29&$blu$)'
ima>$Qp$>($im& "*=/t$st9Qp>"& 100)'
?-
<html-
Ea. *u)> la *a%o= <im> s%* = "*=/t$st9Qp>"/-
</html-

VII.2. Tao v v nh (2)

Cc hm thng s dung

resource imagecreate ( int xsie, int ysie ): Tao nh vi


kch thc xsie * ysie, nh ko phi truecolor

imagecoIoraIIocate ( resource image, int red, int green, int


blue ): S dung d djnh ngha 1 mu s xut hin trong
nh. i vi nh s dung palette, ln gi du tin s cho
mu l mu nn ca nh

resource imagecreatetruecoIor ( int xsie, int ysie ):


Tao nh truecolor

bool imagejpeg ( resource image , string filename , int


quality )

bool imagepng ( resource image , string filename )

bool imagegif ( resource image , string filename )



VII.2. Tao v v nh (3)

mageSetPixel(image, x, y, color)

mageLine(image, start_x, start_ y, end_x, end_ y, color)

mageDashedLine(image, start_x, start_ y, end_x, end_ y,


color)

mageRectangle(image, tlx, tly, brx, bry, color)

mageFilledRectangle(image, tlx, tly, brx, bry, color)

magePolygon(image, points, number, color)

mageFilledPolygon(image, points, number, color)

mageArc(image, center_x, center_ y, width, height, start, end,


color)

mageFill(image, x, y, color)

mageFillToBorder(image, x, y, border_color, color)



VII.3. V Text

<?php
$im = ima>$*%$at$(100&100)'
$@hit$ = ima>$*olo%allo*at$($im& 0xff& 0xff& 0xff)'
$%$d = ima>$*olo%allo*at$($im& 0xff& 0x00& 0x00)'
ima>$st%i)>($im& 1& 0& 0& "NUBE"& $%$d)'
ima>$st%i)>($im& 2& 0& 10& "NUBE"& $%$d)'
ima>$st%i)>($im& 3& 0& 20& "NUBE"& $%$d)'
ima>$st%i)>($im& 4& 0& 30& "NUBE"& $%$d)'
ima>$st%i)>($im& 5& 0& 45& "NUBE"& $%$d)'
ima>$st%i)>up($im& 5& 50& 99& "U)i+$%sit."& $%$d)'
ima>$>i#($im)'
?-

VII.3. V Text (2)
<?php
$im = imagecreate(100,100);
$white = imagecolorallocate($im, 0xff, 0xff, 0xff);
$red = imagecolorallocate($im, 0xff, 0x00, 0x00);
$blue = imagecolorallocate($im, 0x00, 0x00, 0xff);
imagettftext($im, 8, 30, 10, 100, $red,
"Times", "HUCE - 46pm1");
imagettftext($im, 10, -30, 10, 10,$blue,
"Arialni","HUCE- 46pm1");
imagegif($im);
?>

VII.4. Co dn nh
<?php
$im = imagecreate(100,100);
$white = imagecolorallocate($im, 0xff, 0xff, 0xff);
$red = imagecolorallocate($im, 0xff, 0x00, 0x00);
$blue = imagecolorallocate($im, 0x00, 0x00, 0xff);
imagettftext($im, 8, 30, 10, 100, $red, "Times", "HUCE - 46pm1");
imagettftext($im, 10, -30, 10, 10, $blue, "Arialni", "HUCE - 46pm1");
$im2 = imagecreate(200, 200);
//imagecoyresiWed,$im2' $im' A' A' A' A' 2AA' 2AA' 4AA' 4AA-<
imagecopyresampled($im2, $im, 0, 0, 0, 0, 200, 200, 100, 100);
imagegif($im2);
?>

VII.5. Mu sc
.5.1. True color color index
.5.3. Knh alpha

VII.5.1. True coIor & coIor index

nh ca ban doc tao bi cc hm imagecreate() tao nh s


dung colorindex trn palette v imagecreatetruecolor () tao
nh truecolor (24bit/pixel)

T GD2.0 tr ln, ta c th lm vic vi knh alpha (xem phn


sau)

ly mu ca dim nh
D
$*olo% = !ma>$Bolo%2t(ima>$& ?& .)'
D
$+alu$s = !ma>$Bolo%so%!)d$?(ima>$& i)d$?)'

i nh truecolor, cu trc mu gm: 7bit alpha, bit Red, bit


Green, bit Blue (t tri qua phi). C th s dung cng thc
sau
D
$a = ($*ol C 0x7F000000) -- 24'
$% = ($*ol C 0x00FF0000) -- 16'
$> = ($*ol C 0x0000FF00) -- 8'
$b = ($*ol C 0x000000FF)'

VII.5.2. Knh aIpha

Knh alpha trong GD chi gm 7bit (gi trj t 0 dn 127)

s dung knh alpha s dung cc hm

mageColorResolveAlpha()

mageAlphaBlending()

<?php
$im = ImageCreateTrueColor(150,150);
$white = ImageColorAllocate($im,255,255,255);
ImageAlphaBlending($im, true);
ImageFilledRectangle($im,0,0,150,150,$white);
$red = ImageColorResolveAlpha($im,255,50,0,63);
ImageFilledEllipse($im,75,75,80,50,$red);
$gray = ImageColorResolveAlpha($im,70,70,70,63);
ImageAlphaBlending($im, true);
ImageFilledRectangle($im,60,60,120,120,$gray);
header('Content-Type: image/png');
ImagePNG($im);
?>

IX. XML
X.1. Tao vn bn XML
X.2. c XML

IX.1. Tao vn bn XML

Cch don gin nht d tao vn bn XML l


dt lai header ca trang PHP

header('Content-Type: text/xml')

Sau d da thng tin ra browser bng cc


hm echo, print... nh bnh thng

IX.2. c XML

<?php
function sta%t_$l$m$)t($i)Ma%s$%& $i)Jam$& C$i)2tt%ibut$s)
{
+a%_dump($i)Jam$)'
+a%_dump($i)2tt%ibut$s)'
,
function $)d_$l$m$)t($i)Ma%s$%& $i)Jam$) {
+a%_dump($i)Jam$)'
,
$?ml = ?ml_pa%s$%_*%$at$()'
?ml_s$t_$l$m$)t_ha)dl$%($?ml& "sta%t_$l$m$)t"&
"$)d_$l$m$)t")'
?ml_pa%s$($?ml& "<?ml-<%o@ )am$=G%o@5G
at%=Gatt%ibut$5G/-</?ml-")'
?-

VIII. PDF
.1. Document Page
.2. Text
.3. mages Graphics
.4. Nagivations
.5. Cc chc nng khc

You might also like