Está en la página 1de 164

PHP (PHP: Hypertext Preprocessing)

Ngi lp: Nguyn Ph Qung B mn: Tin hc Xy dng

Ni dung trnh by
I. II. III.
I.
II. III. IV.

Lm quen vi PHP PHP Cn bn Cc tnh nng cho ng dng 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

V.
VI. VII. VIII. IX.

I. Lm quen vi PHP
I.1. PHP l g? I.2. Lch s pht trin ca PHP I.3. L do chn PHP I.4. Zend Engine I.5. Ci t PHP I.6. Chng trnh PHP u tin I.7. Cc IDE cho PHP

I.1. PHP l g?

PHP c pht trin t ngn ng kch bn (script) vi mc ch xy dng trang Web c nhn (Personal Home Page). Sau c pht trin thnh mt ngn ng hon chnh v c a chung trn ton th gii trong vic pht trin cc ng dng Web based Theo NetCraft:

Thng 11 nm 1999, hn 1 triu my ch Thng 9 nm 2000, hn 1.4 triu my

PHP (PHP: Hypertext Perprocessor) l ngn ng kch bn lp trnh pha my ch (server-side) ph bin nht th gii. PHP thng hot ng theo th t sau:

Ngi dng gi yu cu ln my ch My ch x l yu cu (Thng dch m PHP v chy chng trnh, m PHP c th truy xut CSDL, to hnh nh, c ghi file, tng tc vi my ch khc...) My ch gi d liu v cho ngi dng (thng l di dng HTML)

I.1. PHP l g? (2)

I.2. Lch s pht trin ca PHP

Phin bn u tin ca PHP c pht trin nm 1994, bao gm cc macro cho trang Web c nhn (Personal Home Page) Sau , PHP c pht trin thm mt s chc nng mi gi l Form Interpreter (PHP/FI) v c c s quan tm ln t pha cng ng Phin bn tip theo, PHP3, c vit li bi mt nhm cc lp trnh vin (Zeev Suraski, Andi Gutmans). PHP3 c b sung thm mt s tnh nng v cc c php ngn ng khc, tr thnh ngn ng kch bn pha my ch c a chung nht

I.3. L do chn PHP

Khi s dng PHP, ngi dng s c c tc nhanh hn nhiu so vi cc ngn ng kch bn khc, bi PHP l phn mm m ngun m, c h tr bi nhiu lp trnh vin gii, c s lng ngi dng ng o. Ngoi ra PHP chy c trn nhiu h iu hnh khc nhau

I.3. L do chn PHP (2)

Rt ngn thi gian pht trin

PHP cho php bn tch phn HTML code v phn script, do c th c lp gia cng vic pht trin m v thit k. iu ny va gip lp trnh vin d dng hn va c th lm cho chng trnh mm do hn trong vic thay i giao din PHP khng ch l phn mm m ngun m m cn thc s min ph (k c khi bn s dng cho mc ch thng mi) Do l phn mm m ngun m, cc li (bug) ca PHP c cng khai v nhanh chng c sa cha bi nhiu chuyn gia

PHP l phn mm m ngun m

I.3. L do chn PHP (3)

Tc

Nh vo sc mnh ca Zend Engine, khi so snh PHP vi ASP, c th thy PHP vt hn mt s test, vt tri tc bin dch. PHP c thit k chy trn nhiu nn tng khc nhau, c th lm vic vi nhiu phn mm my ch, c s d liu (v d: bn c th pht trin d n trn UNIX, sau chuyn sang NT m khng gp phi bt c vn g)

Tnh kh chuyn

I.4. Zend Engine


Zend l scripting engine nm bn trong PHP Zend Engine thc s l s ci tin ng k. Hu ht cc on m vit trn PHP3 u c th chy trn PHP4 vi tc tng gp 200 ln

I.5. Ci t PHP

Bn c th tm phin bn mi nht ca PHP ti a ch http://www.php.net PHP l phn mm m ngun m, bn c th download c m ngun ca PHP Bn c th tm ti liu tham kho ca PHP ti a ch http://www.php.net/manual

I.5. Ci t PHP (2)


Ci t PHP vi IIS

Control Panel/Add Remove Programs/Add Remove Window Components Bt Internet Information Services Download PHP Installer (Windows Binaries) t http://www.php.net/downloads.php Ci t PHP (chn server IIS) Download Apache ti http://httpd.apache.org/ Ci t Apache

Ci t Apache

I.5. Ci t PHP (3)


Download bn PHP zip package (Window Binaries) Gii nn vo th mc 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 mc c:/windows/system32)


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

I.5. Ci t PHP (4)

Thm alias (vo trong httpd.conf)


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

Ch : fake phi bt u bng / nu fake kt thc bng / th realname cng phi kt thc bng /

I.6. Chng trnh PHP u tin

Chng trnh u tin (bn c th son bng bt k trnh son tho vn bn no)
<?php echo("Hello world"); ?> Lu file di tn hello.php ti c:\inetpub\wwwroot\php (IIS) hoc trong th mc ng vi Alias va to ra Ti trnh duyt, nhp vo a ch http://localhost/php/hello.php

I.6. Chng trnh PHP u tin (2)

Khi chng trnh PHP Tag style Chun Dng rt gn ASP Script tags Start Tag <?php <? <% End Tag ?> ?> %>

<script </script> language=ph p>

I.6. Chng trnh PHP u 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 bit, bn c th vit chng trnh PHP bng bt c h son tho vn bn no. Tuy nhin, c c cc chc nng h tr nh AutoComplete, Debug... cn phi s dng cc IDE dnh ring cho PHP

Macromedia DreamWaver Nusphere PHPED Zend Studio

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

II.1. Bin, kiu v hng


II.1.1. Bin II.1.1.1. Tn bin II.1.1.2. Tham chiu II.1.1.3. Bin ng II.1.1.4. Phm vi (scope) ca bin II.1.2. Kiu II.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 c k hiu bi k t $ Tn bin phi c bt u bi 1 ch ci hoc k t gch chn Tn bin khng cha cc du v k t cch

II.1.1.2. Tham chiu


Ging ngn ng C, trong PHP bn c th s dng 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 expression. function test() { return 25; } $bar = &test(); // Invalid. ?>

II.1.1.3. Bin ng (Dynamic Variable)


V PHP l ngn ng thng dch nn bn c th s dng cc bin c tn cha bit trc (tn bin thay i)
<?php $a = "quang"; // gia tri cua bien a la 'quang' $$a = "np"; // bien dong $quang co gia tri la 'np' echo("$a<br>"); // In ra gia tri cua bien a echo("$quang<br>"); // In ra gia tri cua bien quang ${"quang"} = 13432; // Gian truc tiep bien dong echo("$quang<br>"); $c = "quang"; ${$c} = 1000; // Mot cach khac de truy cap den bien dong quang echo("${$c}<br>"); ?>

II.1.1.4. Phm vi ca bin


<?php $a = 1; include "b.inc"; ?>

Phm vi ca bin [a] c tc dng trong c b.inc


<?php $a = 1; // global scope function Test() { echo $a; // reference to local scope variable } Test(); ?>

Bin [a] ngoi v trong hm Test khc nhau

II.1.1.4. Phm vi ca bin (2)


T kha global
<?php $a = 1; $b = 2; function Sum() { //a, b trong & ngoai ham Sum global $a, $b; // la giong nhau $b = $a + $b; } Sum(); echo $b; ?>

Hoc s dng c php


<?php $a = 1; $b = 2; function Sum() { $GLOBALS["b"] = $GLOBALS["a"] + $GLOBALS["b"]; } Sum(); echo $b; ?>

II.1.1.4. Phm 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. Phm vi ca bin (4)


<?php $foo = 25; $bar = &$foo;

// This is a valid assignment.

function test() { global $foo; return $foo; } $bar = &test(); echo($bar); ?>

// Invalid.

II.1.2. Kiu

Cc kiu n
II.1.2.1. boolean II.1.2.2. integer II.1.2.3. float II.1.2.4. string

Cc kiu phc
II.1.2.5. array II.1.2.6. object

Cc kiu c bit
II.1.2.7. resource II.1.2.8. NULL

II.1.2. Kiu (2)


<?php $bool = TRUE; // a boolean $str = "foo"; // a string $int = 12; // an integer echo gettype($bool); // prints out "boolean" echo gettype($str); // prints out "string // If this is an integer, increment it by four if (is_int($int)) { $int += 4; } // If $bool is a string, print it out // (does not print out anything) if (is_string($bool)) { echo "String: $bool"; } ?>

Bn c th p kiu bng hm settype()

II.1.2.1. Kiu boolean


<?php // == is an operator which test // equality and returns a boolean $q = (1==1); echo("$q<br>"); $q = (1=="1"); echo("$q<br>"); // this is not necessary... if ($show_separators == TRUE) { echo "<hr>\n"; } // ...because you can simply type if ($show_separators) { echo "<hr>\n"; } ?>

II.1.2.2. Kiu integer


<?php $a = 1234; $a = -123; $a = 0123; $a = 0x1A; decimal) ?> # # # # decimal number a negative number octal number (equivalent to 83 decimal) hexadecimal number (equivalent to 26

<?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 float


<?php $a = 1.234; $b = 1.2e3; $c = 7E-10; ?> <?php $foo = $foo = $foo = $foo = $foo = $foo = $foo = $foo = ?> 1 + "10.5"; 1 + "-1.3e3"; 1 + "bob-1.3e3"; 1 + "bob3"; 1 + "10 Small Pigs"; 4 + "10.2 Little Piggies"; "10.0 pigs " + 1; "10.0 pigs " + 1.0; // // // // // // // // $foo $foo $foo $foo $foo $foo $foo $foo is is is is is is is is float (11.5) float (-1299) integer (1) integer (1) integer (11) float (14.2) float (11) float (11)

II.1.2.4. Kiu string

String trong PHP l mt chui cc k t 1 byte. PHP khng h tr Unicode, lm vic vi Unicode bn phi s dng UTF8 vi cc hm utf8_encode() utf8_decode() String ca PHP h tr chiu di rt ln (?) Trong PHP, string c xc nh theo 3 cch

Du nhy n (single quote) Du nhy kp (double quote) Heredoc Truyn kiu n gin Truyn kiu phc

Truyn bin trong string


Truy cp n tng k t trong string Cc ton t trn string

II.1.2.4. Kiu String (2)


Kiu du nhy n
<?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 n nhng c nhiu h tr cho cc k t c bit hn

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 n gin
<?php $beer = 'Heineken'; echo "$beer's taste is great"; // works, "'" is an invalid character for varnames echo "He drank some $beers"; // won't work, 's' is a valid character for varnames echo "He drank some ${beer}s"; // works echo "He drank some {$beer}s"; // works ?>

Truyn bin kiu phc (truyn bin kiu mng vo string) s cp n phn mng

II.1.2.4. Kiu String (6)


Truy cp n tng k t ca String
<?php $str = "This is a test"; echo $str[0]; // Ky tu dau tien echo $str{1}; // Ky tu thu 2 echo $str{strlen($str)-1}; // Ky tu cuoi cung echo "<br>$str"; $str{strlen($str)-1} = "s"; // Sua ky 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 x (map) c th t. Tc l kiu d liu gm cc cp kha (key) v gi tr (value). Vi kiu mng ny, bn c th s dng 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 dng array
<?php $arr = array(5 => 1, 12 => 2); $arr[] = 56; // This is the same as $arr[13] = 56; // at this point of the script $arr["x"] = 42; // This adds a new element to // the array with key "x" unset($arr[5]); // This removes the element from the array unset($arr); // This deletes the whole 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
nh ngha hng bng cch s dng hm define() Phm vi ca hng l ton cc (global) Ch c cc dng d liu n gin (boolean, interger, float, string)

Nu tn hng cha c nh ngha, PHP gi thit rng bn ang s dng 1 hng cha gi tr l 1 string (chnh l tn ca hng )
xc nh mt hng c nh ngha hay cha, bn c th s dng hm defined
<?php define("CONSTANT", "Hello world."); echo CONSTANT; // outputs "Hello world." echo Constant; // outputs "Constant" and issues a notice. echo defined("Constant"); echo defined("CONSTANT"); ?>

II.1.3. Hng (2)

Cc hng c nh ngha trc (cc hng ny thng c s dng phc v qu trnh debug
Tn hng __LINE__ __FILE__ M t Th t dng hin ti trong file ng dn y ca file hin ti

__FUNCTION__
__CLASS__ __METHOD__

Tn hm hin ti
Tn lp hin ti Tn phng thc hin ti ca lp

II.2. Ton t v biu thc


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

II.2.1. Mc u tin cc ton t


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

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

II.2.3. Ton t gn
Ton t gn (=) cho php bn gn mt biu thc (v phi) cho 1 bin (v tri) Ton t gn tr v gi tr ca biu thc v phi, do c th dng nhiu php gn lin tip nhau Ngoi ra, cn c cc php ton gi l php ton kt hp cho hu ht cc ton t s hc thay i gi tr 1 bin theo php ton s hc (+=, -=, *=, /=, .= ...) <?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


Example $a & $b $a | $b $a ^ $b ~ $a $a << $b Name And Or Xor Not Shift left Result Bits that are set in both $a and $b are set. Bits that are set in either $a or $b are set. Bits that are set in $a or $b but not both are set. Bits that are set in $a are not set, and vice versa. Shift the bits of $a $b steps to the left (each step means "multiply by two")

<?php echo 12 ^ 9; echo "12"^"9";

// Outputs '5' // Outputs the Backspace character (ascii 8) // ('1' (ascii 49)) ^ ('9' (ascii 57)) = #8 echo "hallo"^"hello"; // Outputs the ascii values #0 #4 #0 #0 #0 // 'a' ^ 'e' = #4 ?>

II.2.5. Ton t so snh


Example $a == $b $a === $b $a != $b $a <> $b $a !== $b Name Equal Identical Not equal Not equal Not identical Result
TRUE if $a is equal to $b. TRUE if $a is equal to $b, and they are of the same

type. (PHP 4 only)


TRUE if $a is not equal to $b. TRUE if $a is not equal to $b. TRUE if $a is not equal to $b, or they are not of the

same type. (PHP 4 only)


TRUE if $a is strictly less than $b.
TRUE if $a is strictly greater than $b. TRUE if $a is less than or equal to $b. TRUE if $a is greater than or equal to $b.

$a < $b
$a > $b $a <= $b

Less than
Greater than Less than or equal to Greater than or equal to

$a >= $b

II.2.6. Ton t iu khin li

Ton t iu khin li (@) dng t trc cc hm, biu thc. Khi tt c cc thng bo li trong hm, biu thc b 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 bn 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 logic


Example
$a and $b $a or $b $a xor $b ! $a $a && $b

Name
And Or Xor Not And

Result
TRUE if both $a and $b are TRUE. TRUE if either $a or $b is TRUE. TRUE if either $a or $b is TRUE, but not both. TRUE if $a is not TRUE. TRUE if both $a and $b are TRUE.

$a || $b

Or

TRUE if either $a or $b is TRUE.

II.2.10. Ton t trn string

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

<?php $a = "Hello "; $b = $a . "World!"; // now $b contains "Hello World!" $a = "Hello "; $a .= "World!"; ?> // now $a contains "Hello World!

II.2.11. Ton t trn mng


i vi mng, ch c ton t +, ton t ny ni 2 mng vi nhau (cc phn trng kha c ly ton hng tri)
<?php $a = array("a" $b = array("a" "b" "c" $c = $a + $b; var_dump($c); ?> => "apple", "b" => "banana"); =>"pear", => "strawberry", => "cherry");

II.3. Cc cu trc iu khin


II.3.1. Cu trc if, else, elseif, endif II.3.2. Cu trc while / do...while II.3.3. Cu trc for / for...each II.3.4. S dng break, continue trong cc vng lp II.3.5. Cu trc switch

II.3.1. Cu trc if, else, elseif, endif


<?php if ($a > $b) { echo "a is bigger than b"; $b = $a; } if ($a echo } else echo } > $b) { "a is bigger than b"; { "a is NOT bigger than b"; { bigger than b"; == $b) { equal to b"; smaller than b";

<?php if ($a == 5): ?> A is equal to 5 <?php endif; ?>

if ($a > $b) echo "a is } elseif ($a echo "a is } else { echo "a is } ?>

II.3.2. Cu trc while / do...while


<?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 $value) statement foreach (array_expression as $key => $value) 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 lp


<?php $arr = array ('one','two','three','four','stop','five'); while (list (, $val) = each ($arr)) { if ($val == 'stop') break; // Vit break 1; cng c echo "$val<br>\n"; } while (list ($key, $value) = each ($arr)) { if (!($key % 2)) // B qua s l continue; do_something_odd ($value); } ?>

II.3.4. S dng break, continue trong cc vng lp (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
II.4.1. Hm t nh ngha (user-defined) II.4.2. Truyn tham s II.4.3. Gi tr tr v II.4.4. Bin hm

II.4.1. Hm t 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"; } } // Khng th gi bar() v n cha c nh ngha foo(); // By gi th c th gi bar() bar(); ?>

II.4.2. Truyn tham s


PHP h tr truyn tham s vo hm, truyn tham s di dng tham chiu (reference), truyn tham s vi gi tr mc nh
<?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;// outputs '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"; } // won't work as expected echo makeyogurt ("raspberry"); function makeyogurt ($flavour, $type = "acidophilus") { return "Making a bowl of $type $flavour.\n"; } // works as expected echo makeyogurt ("raspberry");

II.4.2. Truyn tham s (3)


Bn c th truyn tham s vi s lng khng xc nh. Khi s s dng cc hm sau func_num_args(): S lng 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 lnh return. C th s dng bt c kiu no trong gi tr tr v ca hm (k c mng v i tng)
<?php function square ($num) { return $num * $num; } echo square (4); // outputs '16'. 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
Bn c th s dng cc bin hm (tc l bn c th gi hm di dng ten_bien() ). Bin hm thng c s dng cho cc hm callback
<?php function foo() { echo "In foo()<br>\n"; } function bar($arg = '') { echo "In bar(); argument was '$arg'.<br>\n"; } // This is a wrapper function around echo function echoit($string) { echo $string; } $func = 'foo'; $func(); // This calls foo() $func = 'bar'; $func('test'); // This calls bar()

?>

$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 Bar() method } function Bar() { echo "This is Bar"; } } $foo = new Foo(); $funcname = "Var"; $foo->$funcname(); ?>

// This calls $foo->Var()

II.5. Lp & i tng


II.5.1. Serializing i tng i tng trong session II.5.2. Tham chiu bn trong constructor II.5.3. So snh i tng trong PHP4 II.5.4. So snh i tng trong PHP5

II.5.1. Serializing i tng i tng trong session


Hm serialize() dng lu tr i tng, hm tr v mt chui cc byte lu thng tin ca i tng Hm unserialize() dng khi phc i tng c lu gi bi hm serialize() <?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 i tng trong PHP4


Trong PHP4, php so snh cc i tng thc hin theo quy tc n gin sau: Hai i tng l bng nhau nu chng c cc thuc tnh bng nhau v cng thuc 1 lp. Quy tc so snh ny cng c p dng vi php ===

<?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); ?>

II.5.3. So snh i tng 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 i tng trong PHP5


So snh i tng trong PHP5 c mt s thay i so vi PHP4 i vi php so snh ==, hai i tng bng nhau nu c chung cc thuc tnh v cng thuc 1 lp i vi php so snh ===, hai i tng c gi l bng nhau nu chng cng tham chiu n 1 phin bn ca 1 lp

II.6. Tham chiu (reference)


II.6.1. Cc trng hp s dng tham chiu II.6.2. Cc trng hp ko s dng tham chiu II.6.3. Truyn tham chiu II.6.4. Tr v tham chiu II.6.5. Unset tham chiu

II.6.1. Cc trng hp s dng tham chiu


Tham chiu cho php bn s dng 1 bin vi nhiu tn khc nhau i vi i tng, nn s dng php gn tham chiu khi dng ton t new trnh php gn to ra thm 1 phin bn ca i tng thay i gi tr ca tham s truyn vo trong hm, bn c th s dng 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 trng hp ko s dng tham chiu


Tham chiu gn ging con tr nhng bn cht khng phi l con tr Trong trng hp ti v d di y, $var trong hm foo u tin c tham chiu n bin $var (global). Tuy nhin sau $var li c tham chiu in 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

Bn c th truyn cc dng 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 bn t ton t tham chiu ng trc tn hm Nu hm tr v tham chiu, nhn c tham chiu bn phi dng ton t gn vi tham chiu n hm (xem v d)
<?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


Bn c th s dng lnh unset() loi b mt bin khi b nh Nu unset c s dng vi 1 bin tham chiu, PHP s kim tra xem cn bin no cng tham chiu n vng nh hay khng ri mi loi 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


III.1. Cc bin SuperGlobal III.2. Bin $_SERVER III.3. Ly thng tin t form III.4. Kt hp m HTML v PHP trong 1 trang III.5. S dng Hidden field lu trng thi III.6. Redirect III.7. Form Upload file

III.1. Cc bin SuperGlobal


Cc bin global l cc bin c khai bo mc ngoi cng ca PHP c s dng chung cho mi module Cc bin SuperGlobal l cc bin (mng) c PHP to ra lu cc thng tin cn thit
Array Description Contains keys and values set as browser cookies Contains keys and values set by the script's shell context Contains information about uploaded files Contains keys and values submitted to the script using the HTTP get method Contains keys and values submitted to the script using the HTTP post method A combined array containing values from the $_GET, $_POST, and $_COOKIES superglobal arrays Variables made available by the server Contains all global variables associated with the current script

$_COOKIE $_ENV $_FILES $_GET $_POST $_REQUEST $_SERVER $GLOBALS

III.2. Bin $_SERVER


Variable $_SERVER['PHP_SELF'] Contains Example

$_SERVER['HTTP_USER_AGENT'] $_SERVER['REMOTE_ADDR'] $_SERVER['REQUEST_METHOD'] $_SERVER['QUERY_STRING']

$_SERVER['REQUEST_URL']

$_SERVER['HTTP_REFERER']

The current script. Suitable for use in links and form element action arguments. The name and version of the client. The IP address of the client. Whether the request was GET or POST. For GET requests, the encoded data sent appended to the URL. The full address of the request, including query string. The address of the page from which the request was made.

/phpbook/source/listing10.1.php

Mozilla/4.6 (X11; I;Linux2.2. 615apmac ppc) 158.152.55.35

POST
name=matt&address=unknown /phpbook/source/listing10.1.php? name=matt http://p24.corrosive

III.2. Bin $_SERVER (2)


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

III.3. Ly thng tin t form


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

III.3.1. Ly thng tin t form bng cc mng superglobal


D liu t form c submit ln server thng qua cc phng thc: get, post ly c thng tin t form, bn c th s dng cc mng superglobal tng ng $_POST[tn_control], $_GET[tn_control], $_REQUEST[tn_control] (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 global


thun tin cho ngi lp trnh, PHP cung cp hm import_request_variables() cho php a cc tham s GET, POST v COOKIE vo thnh cc bin global C php
bool import_request_variables(string types, [string prefix]) types: Ch ra loi thng tin no c 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 ngi dng nh ngha

Nhng cch ly thng tin t form nu trn cho php chng ta lm vic tt vi cc control n (c 1 gi tr) i vi cc control c nhiu gi tr nh select hay checkbox, ny sinh vn l lm sao nhn c tt c cc control c la chn gii quyt vn ny, t tn cc control vi kt thc l du ngoc vung [], khi d liu truyn t form n server s l mng

III.3.3. Ly thng tin ca form bng mng do ngi dng 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, bn thng mun kt hp form gi thng tin vi cc on script PHP x l thng tin. iu ny c th d dng thc hin bng cch cc kt hp cc cu trc iu khin r nhnh vi cc on m HTML. t on m HTML vo trong cu trc r nhnh, s dng kt hp cc khi lnh PHP (xem v d)

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 field lu trng thi


lu thng tin chung ca cc form gia cc ln submit (v d: S ln submit), cch n gin nht l s dng 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 dng nhiu khi PHP xen ln HTML l khng tt. Mt cch n gin v hiu qu hn l s dng Redirect dn hng ngi dng n cc trang thch hp (v d: Trang ng nhp nu ngi dng cha ng nhp, trang chc mng nu ngi dng ng nhp thnh cng) lm c vic ny, trc ht ta tm hiu c ch lm vic gia PHP script v client. u tin, giao tip vi client, PHP t ng gi cc thng tin header cho client. Tuy nhin, bn vn c th t gi header. dn hng client n trang khc, bn ch cn n gin i header bng hm header(). s dng hm header() bn phi m bo rng cho c d liu no c gi cho client (s dng hm header_sent() 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 Upload file


Ngi dng c th gi cc file (upload) ln server l mt chc nng khng th thiu i vi cc ng dng Web-based form c th upload file, bn phi xc nh form enctype: ENCTYPE="multipart/form-data Vi PHP, bn c th xc nh kch thc ln nht ca file upload bng cch t thm 1 hidden field c tn MAX_FILE_SIZE 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 Upload file (2)

Mng $_FILE
Element Contains Name of uploaded file Path to temporary file Size (in bytes) of uploaded file An error code corresponding to a PHP constant Example
test.gif /tmp/phprDfZvN

$ FILES['fupload']['name'] $_FILES['fupload']['tmp_name'] $_FILES['fupload']['size'] $_FILES['fupload']['error']

6835
UPLOAD_ERR_FORM _SIZE

$_FILES['fupload']['type']

MIME type of uploaded file (where given by client)

image/gif

Constant Name
UPLOAD_ERR_OK UPLOAD_ERR_INI_SIZE UPLOAD_ERR_FORM_SIZE

Valu e
0 1 2

Explanation No problem File size exceeds php.ini limit set in


upload_max_filesize

File size exceeds limit set in hidden element named MAX_FILE_SIZE File only partially uploaded File was not uploaded

UPLOAD_ERR_PARTIAL UPLOAD_ERR_NO_FILE

3 4

III.7. Form Upload file (3)

<?php if ($_REQUEST["submit"]=="upload!") { echo $_FILES["fupload"]["error"], "\n"; echo $_FILES["fupload"]["size"], "\n"; echo $_FILES["fupload"]["name"], "\n"; echo $_FILES["fupload"]["tmp_name"], "\n"; if ($_FILES["fupload"]["error"]==0) { $source = $_FILES["fupload"]["tmp_name"]; $dest = $_FILES["fupload"]["name"]; move_uploaded_file($source, $dest); } } ?> <form enctype="multipart/form-data" method="post"> <p> <input type="hidden" name="MAX_FILE_SIZE" value="102400" /> <input type="file" name="fupload" /><br/> <input type="submit" value="upload!" name="submit" /> </p> </form>

IV. Lm vic vi file


IV.1. S dng include() IV.2. S dng include_once() v include_path cho cc d n ln IV.3. Kim tra file IV.4. c, ghi file IV.5. Lm vic vi th mc

IV.1. S dng include()

Lnh include() cho php bn phi hp gia cc file trong mt PHP project, 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 dng chia s cc hm dng chung, cc on m chung trong mt project c nhiu file Nu khng tm thy file, include() thng bo warning nhng khng dng chng trnh PHP cung cp 1 lnh tng t include() l require(), lnh ny c s khc bit l s dng ngay chng trnh khi khng tm thy file

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

<!--File1.php-> <?php echo "This is from file 1\n"; ?> <!--File2.php -> <?php echo "This is from file 2\n"; include("file1.php"); include("file3.php"); echo "This is from file 2\n"; ?>

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


V include() thc hin li gi n file php, do bn c th tr v gi tr t file PHP c include <!--File11.php--> <?php return 4 + 4; ?> <!--File12.php--> <?php echo "This is from file 12\n"; $retVal = include("file11.php"); echo "Return value from file 11: \$retVal= $retVal\n"; echo "This is from file 12\n"; ?>

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

Bn c th t lnh include bn trong 1 cu trc iu kin hoc cu trc lp, khi ty theo iu kin ca cu trc m include() c c 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 include_once() v include_path cho cc d n ln


include_once() ging nh include(), tuy nhin c im khc bit l ch include 1 ln, ln sau nu gp li file ny th ko include na include_once() s dng cho cc hm th vin dng chung trnh trng hp khi nhiu file cng include n 1 file, sau cc file ny li include ln nhau (so snh vi #ifdefine trong file header ca ngn ng C) include_once() phn bit ch hoa, ch thng <?php include_once("a.php"); // this will include a.php include_once("A.php"); // this will include a.php again on Windows! ?>

IV.2. S dng include_once() v include_path cho cc d n ln (2)

Trong qu trnh lm vic, bn hn c nhiu hm c dng chung gia nhiu file trong 1 project, gia nhiu project. s dng cc hm ny, bn c th p dng cc cch sau:

include file theo ng dn tuyt i: Cch ny d v khi ci t trn my khc s khng tm thy file c include include file theo ng dn tng i: Cch ny tt hn, nhng mi khi i v tr ca file c include th phi sa li ti tt c cc file thc hin li gi include Cch tt nht l s dng include_path (thit lp trong file PHP.INI) i vi nhng file th vin dng chung c s dng nhiu (ging nh i vi ngn ng C)

IV.2. S dng include_once() v include_path cho cc d n ln (3)

thit lp include_path, bn c nhng cch sau:


thay i include_path trong PHP.INI dng lnh set_include_path()

<?php var_dump(get_include_path()); set_include_path('/inc'); // Works as of PHP 4.3.0 var_dump(get_include_path()); restore_include_path(); var_dump(get_include_path()); ?>

dng lnh ini_set()

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

IV.3. Kim tra file

file_exist(), is_file(), is_dir(), is_readable(), is_writeable(), is_executable(), filesize(), 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 file

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 file (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 "Read all file by fread......\n"; echo "$line"; $f = fopen("test.txt", "rb"); } $myfile = fread($f, filesize("test.txt")); fclose($f); echo $myfile; fclose($f); echo "Read all file......\n"; $myfile = file_get_contents("test.txt"); echo($myfile); ?>

IV.4. c, ghi file (3)

<?php $var1=10; $var2=100; $var3=100.3434; $var4="Test string"; $f=fopen("test.txt", "wt"); fwrite($f, sprintf("%d %10.3f %10.3lf\n\r", $var1, $var2, $var3)); fwrite($f, sprintf("%s", $var4)); fclose($f); $f=fopen("test.txt", "rt"); if (list($v1, $v2, $v3, $v4) = fscanf($f, "%d %f %lf\n\r%s")) { var_dump($v1); var_dump($v2); var_dump($v3); var_dump($v4); } $v4 = fgets($f); var_dump($v4); fclose($f); ?>

IV.4. c, ghi file (4)

<?php class AClass { }; $ob1 =& new AClass(); $ob1->a = 10; $ob1->b = 100.023; $ob1->c = "Test String"; var_dump($ob1); $f = fopen("test.txt", "wb"); fwrite($f, serialize($ob1)); fclose($f); $f = fopen("test.txt", "rb"); $ob2 = unserialize(fgets($f)); fclose($f); var_dump($ob2); ?>

IV.5. Lm vic vi th mc

mkdir(), rmdir(), opendir(), readdir(), closedir() <?php $dir=opendir("c:\\windows"); while ($file=readdir($dir)) { echo "$file\n"; } closedir($dir); ?>

V. PHP & CSDL


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

V.1. S dng PHP kt ni vi CSDL

C 2 cch kt ni PHP vi CSDL

S dng cc hm ring cho tng loi CSDL


u im: Tc cao do c thit k cho tng CSDL c th. Tn dng c u im ca tng loi CSDL Nhc im: Khng c tnh kh chuyn gia cc CSDL

S dng cc hm c lp CSDL (th vin PEAR DB)


u im: C th s dng trn nhiu CSDL khc nhau Nhc im: Chm hn phng php trn, khng tn dng c u im ca tng CSDL.

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

Ci t th vin PEAR

Yu cu: PHP phin bn 5.0 Ci t PHP Chy go-pear.bat Theo cc hng dn trong chng trnh (cc tham s ch cn t mc nh)

Nu khng ci t PEAR, m copy t my khc, phi thm vo C:/Windows/PHP.INI 2 dng nh di Cu hnh Zend Studio lm vic vi PEAR DB

Thm vo file $Zend_dir/bin/php5/php.ini 2 dng include_path=".;C:/php/pear" extension_dir="c:/php/ext" Copy file libMySQL.dll vo $Windows/$System (nu bn s dng IIS)

Cc bc ci t kiu m n lin

Ci IIS, ci Mysql 5.0, ci PHP Copy $\Mysql\bin\libMysql.dll n c:\windows\system32 Copy PHP.rar ln th mc c:/PHP Sa ni dung c:\windows\system32\PHP.INI, thm vo cc dng sau ( cui file)
include_path=".;C:/php/pear" extension_dir=" c:/php/ext" extension=php_mysql.dll

Sau , c th chy c trn local host (trn Zend th phi config thm, tt nht l ng 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)


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

V.2.1. Data source name


dsn=Data Source Name type://username:password@protocol+host spec/database V d:

Type Mysql Pgsql Ibase Msql Mssql MySQL

Database

PostgreSQL InterBase Mini SQL Microsoft SQL Server

mysql:///webdb mysql://localhost/webdb mysql://bondview@localhost/webdb mysql://bondview@tcp+localhost/webdb mysql://bondview:007@localhost/webdb

oci8
Odbc Sybase Ifx Fbsql

Oracle 7/8/8i
ODBC SyBase Informix FrontBase

V.2.2. Kt ni vi c s d liu

Khi c DSN, bn c th kt ni bng hm DB::connect vi c php sau:

$db = DB::connect(DSN [, options ]);

options c th l 1 gi tr Boolean hoc 1 $db = DB::connect($dsn, array('debug' => 1, 'optimize' => 'portability'));

mng

V.2.3. Kim tra li


Cc phng thc ca DB tr v DB_ERROR nu c li trong qu trnh thc hin Bn 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 bn l li, c th xem thng bo li bng phng thc $tenbien>getMessage() $db = DB::connect($datasource); if (DB::isError($db)) { die($db->getMessage( )); }

V.2.4. Thc thi query

thc thi query, s dng phng thc query() ca Database Object (i tng tr v khi bn kt ni thnh cng vi CSDL bng hm DB::connect() ); $db = DB::connect($datasource); $result = $db->query(sql); Cng tng t nh DB::connect(), bn c th kim tra li bng DB::isError() if (DB::iserror($result)) { die($result->getMessage()); }

V.2.5. Ly kt qu t query

$row = $result->fetchRow([ mode ]); Hm fetchRow() tr v mng cc gi tr trn dng hoc DB_ERROR (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 with the row } ?>

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


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


DB_FETCHMODE_ORDERED: Cc ct c lit k trn $row theo th t 0,1,2... DB_FETCHMODE_ASSOC : Cc ct c lit k vi kha l tn ca cc ct DB_FETCHMODE_OBJECT: Cc ct c lit k thnh cc trng ca i tng

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


V.3.1. Query template V.3.2. Prepare/Execute V.3.3. Cc hm tin ch V.3.4. Cc thng tin tr v t query() V.3.5. Metadata

V.3.1. Query template

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 hp c s dng du nhy) Trong trng hp ny, PHP cung cp 1 cng c hot ng cho php truyn tham s trong cu lnh SQL ging nh lnh printf, trong s dng cc k hiu

?: Cho s hoc string (du nhy s c b sung khi cn thit) |: Cho s hoc string (khng s dng du nhy) &: Tn file (dng cho cc trng BLOB)

<?php require("DB.php"); $db = DB::connect("mysql://root:root@localhost/dhxd"); $row = array("Nguyen Van", "A"); $db->query("INSERT INTO sv (hodem, ten) VALUES(?,?)", $row); ?>

V.3.2. Prepare/Execute

Khi bn thc hin nhiu cu lnh ging nhau, cch tt nht l dch cu lnh SQL trc khi thc hin bng phng thc prepare() Sau khi dch SQL, bn c th thc hin cu lnh SQL bng cch dng 2 lnh sau:

$response = $db->execute(compiled, values); (values: mng 1 chiu cc gi tr) $responses = $db->executeMultiple(compiled, values); (values: mng 2 chiu cc dng, mi dng l 1 mng 1 chiu cc gi tr)

<?php require("DB.php"); $db = DB::connect("mysql://root:root@localhost/dhxd"); $complied = $db->prepare("INSERT INTO sv (hodem, ten) VALUES(?,?)"); $rows=array( array("Nguyen Van", "A"), array("Nguyen Van", "B"), array("Nguyen Van", "C"), array("Nguyen Van", "D") ); foreach ($rows as $row) { $db->execute($complied, $row); } $db->executeMultiple($complied, $rows); ?>

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 c s dng: getOne(), 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()


Bn c th ly thng tin v cc dng, ct kt qu tr v t cu lnh SQL qua cc hm numRows(), numCols(), tableInfo(), 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 getListOf() s dng ly thng tin v users, databases, tables, views, functions (ph thuc vo s h tr ca CSDL m bn ang s dng) <?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 c s d liu h tr Transaction safe, s dng transaction safe trong PHP, bn s dng cc lnh commit(), rollback() c th rollback(), bn 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


VI.2. H thng template VI.3. Qun l output VI.4. Qun l li VI.5. Ti u ha

VI.2. H thng template


Trang Web c giao din d thay i l 1 tiu ch rt quan trng Nu kt hp 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 i giao din kh khn Mt phng php hiu qu l s dng cc file template (.HTML c thit k t cc chng trnh: DW, FrontPage...). Cc file template ny thng khng cha m PHP m ch c cc thng tin di dng quy c (thng l cc tn gi, gi tr c t theo 1 quy c nht nh, cc gi tr ny s c thay th khi chy chng trnh bng PHP)

VI.2. H thng template (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 l output


Thng th cc hm ghi thng tin ra browser. Tuy nhin c nhiu trng hp chng ta khng mun nh vy. Bn c th s dng vng m ra (output buffer) cc lnh ghi thng tin ghi d liu ln Cc hm vi output buffer: ob_start(), ob_get_length(), ob_get_contents(), ob_flush(), ob_end_flush(); ob_end_clean() <?php ob_start(); phpinfo(); $phpinfo = ob_get_contents(); ob_end_clean();

if (strpos($phpinfo, "module_pdf") === FALSE) { echo "You do not have PDF support in your PHP, sorry."; } else { echo "Congratulations, you have PDF support!"; } ?>

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

VI.4.1. Thng bo li

Thng thng, khi c li, thng bo li c in ra output C 3 mc thng bo: notices, warnings, errors Mc nh ca PHP l cc thng bo warning, error s c in ra browser, bn c th thay i trong PHP.INI hoc trong thi gian chy bng hm error_reporting() (cc tham s E_ERROR | E_PARSE | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR)

VI.4.1. Thng bo li (2)


Value E_ERROR E_WARNING Runtime errors Runtime warnings Meaning

E_PARSE
E_NOTICE E_CORE_ERROR E_CORE_WARNING E_COMPILE_ERROR E_COMPILE_WARNING E_USER_ERROR E_USER_WARNING E_USER_NOTICE

Compile-time parse errors


Runtime notices Errors generated internally by PHP Warnings generated internally by PHP Errors generated internally by the Zend scripting engine Warnings generated internally by the Zend scripting engine Runtime errors generated by a call to trigger_error( ) Runtime warnings generated by a call to trigger_error( ) Runtime warnings generated by a call to trigger_error( )

E_ALL

All of the above options

VI.4.2. Giu li

S dng ton t @ ngn khng cho output li ra browser Thit lp track_errors trong php.ini bt c cc thng bo li qua bin $php_errormsg ngn khng cho tt c cc thng bo li trn browser, s dng hm error_reporting(0) <?php ini_set("track_errors", "1"); $value = 2/0; $value = @(2/0); echo "$php_errormsg"; ini_restore("track_errors"); ?> <?php error_reporting(0); ini_set("track_errors", "1"); $value = 2/0; echo "$php_errormsg"; ini_restore("track_errors"); ?>

VI.4.3. Pht sinh li


Bn c th lm pht sinh li ngi dng bng hm trigger_error trigger_error(message [, type]); type: E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE (default)
<?php function divider($a, $b) { if($b == 0) { trigger_error('$b cannot be 0', _USER_ERROR); } } ?> return($a / $b);

VI.4.4. Hm x l li

Giu tt c cc li khng phi l mt phng n hay, qun l li tt hn, bn nn dng hm x l li (error handler) Error handler c thit lp bng hm set_error_handler(), khi phc li bng hm restore_error_handler()
<?php function my_handler($error, $errorstring, $filename, $line, $symbol) { echo "$error|$errorstring|$filename|$line\n"; } set_error_handler('my_handler'); echo 4/0; $f = file("linhtinh"); ?>

VI.4.5. Log li

VI.5. Ti u ha

VII. Hnh nh
VII.1. Yu cu phn mm VII.2. To v v nh VII.3. V Text VII.4. Co dn nh

VII.1. Yu cu phn mm

Vi PHP bn c th s dng cc hm graphic v ra cc hnh nh v lu tr di dng file (GIF, PNG, JPG) thc hin c chc nng ny, bn cn phi ci t b th vin GD (http://www.boutell.com/gd/ ) bit th vin GD c ci t hay cha, c th s dng hm phpinfo() hoc hm gd_info() i vi b PHP full (v5.0) c y th vin PEAR i km, chy GD bn ch vic thit lp trong file php.ini: extension=php_gd2.dll

VII.2. To v v nh

<!-- file: caro.php --> <?php $im = imagecreate(30, 30); $red = imagecolorallocate($im, 0xff, 0x00, 0x00); $blue = imagecolorallocate($im, 0x00,0x00,0xff); $black = imagecolorallocate($im, 0x00, 0x00, 0x00); imagefilledrectangle($im, 0, 0, 29, 29, $black); imagefilledrectangle($im, 0,0,15,15,$red); imagefilledrectangle($im, 15,15,29,29,$blue); imagejpeg($im); ?> <!-- file: 1.html --> <html> Day la caro <img src="caro.php"/> </html> <?php $im = imagecreate(30, 30); $red = imagecolorallocate($im, 0xff, 0x00, 0x00); $blue = imagecolorallocate($im, 0x00,0x00,0xff); $black = imagecolorallocate($im, 0x00, 0x00, 0x00); imagefilledrectangle($im, 0, 0, 29, 29, $black); imagefilledrectangle($im, 0,0,15,15,$red); imagefilledrectangle($im, 15,15,29,29,$blue); imagejpeg($im, "c:/test.jpg", 100); ?> <html> Day cung la caro: <img src = "c:/test.jpg"/> </html>

VII.2. To v v nh (2)

Cc hm thng s dng

resource imagecreate ( int x_size, int y_size ): To nh vi kch thc x_size * y_size, nh ko phi truecolor imagecolorallocate ( resource image, int red, int green, int blue ): S dng nh ngha 1 mu s xut hin trong nh. i vi nh s dng palette, ln gi u tin s cho mu l mu nn ca nh resource imagecreatetruecolor ( int x_size, int y_size ): To nh truecolor bool imagejpeg ( resource image [, string filename [, int quality]] ) bool imagepng ( resource image [, string filename] ) bool imagegif ( resource image [, string filename] )

VII.2. To v v nh (3)

ImageSetPixel(image, x, y, color); ImageLine(image, start_x, start_ y, end_x, end_ y, color); ImageDashedLine(image, start_x, start_ y, end_x, end_ y, color); ImageRectangle(image, tlx, tly, brx, bry, color); ImageFilledRectangle(image, tlx, tly, brx, bry, color); ImagePolygon(image, points, number, color); ImageFilledPolygon(image, points, number, color); ImageArc(image, center_x, center_ y, width, height, start, end, color); ImageFill(image, x, y, color); ImageFillToBorder(image, x, y, border_color, color);

VII.3. V Text

<?php $im = imagecreate(100,100); $white = imagecolorallocate($im, 0xff, 0xff, 0xff); $red = imagecolorallocate($im, 0xff, 0x00, 0x00); imagestring($im, 1, 0, 0, "HUCE", $red); imagestring($im, 2, 0, 10, "HUCE", $red); imagestring($im, 3, 0, 20, "HUCE", $red); imagestring($im, 4, 0, 30, "HUCE", $red); imagestring($im, 5, 0, 45, "HUCE", $red); imagestringup($im, 5, 50, 99, "University", $red); imagegif($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); //imagecopyresized($im2, $im, 0, 0, 0, 0, 200, 200, 100, 100); imagecopyresampled($im2, $im, 0, 0, 0, 0, 200, 200, 100, 100); imagegif($im2); ?>

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

VII.5.1. True color & color index

nh ca bn c to bi cc hm imagecreate() to nh s dng colorindex trn palette v imagecreatetruecolor () to nh truecolor (24bit/pixel) T GD2.0 tr ln, ta c th lm vic vi knh alpha (xem phn sau) ly mu ca im nh

$color = ImageColorAt(image, x, y); $values = ImageColorsForIndex(image, index);

Vi nh truecolor, cu trc mu gm: 7bit alpha, 8bit Red, 8bit Green, 8bit Blue (t tri qua phi). C th s dng cng thc sau

$a $r $g $b

= = = =

($col ($col ($col ($col

& & & &

0x7F000000) >> 24; 0x00FF0000) >> 16; 0x0000FF00) >> 8; 0x000000FF);

VII.5.2. Knh alpha


Knh alpha trong GD ch gm 7bit (gi tr t 0 n 127) s dng knh alpha s dng cc hm

ImageColorResolveAlpha() ImageAlphaBlending()

<?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
IX.1. To vn bn XML IX.2. c XML

IX.1. To vn bn XML

Cch n gin nht to vn bn XML l t li header ca trang PHP

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

Sau a thng tin ra browser bng cc hm echo, print... nh bnh thng

IX.2. c XML

<?php function start_element($inParser, $inName, &$inAttributes) { var_dump($inName); var_dump($inAttributes); } function end_element($inParser, $inName) { var_dump($inName); } $xml = xml_parser_create(); xml_set_element_handler($xml, "start_element", "end_element"); xml_parse($xml, "<xml><row name='row1' atr='attribute1'/></xml>"); ?>

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

También podría gustarte