You are on page 1of 103

i H c S Ph m Tp.

H Ch Minh

LP TRNH WEB PHP

Chng 02: PHP C B N

NI DUNG
Ph n 1: T ng quan v PHP Ph n 2: PHP c b n

Ni dung phn 1
1. Gi i thi u PHP
a. b. c. d. L ch s pht tri n PHP l g u i m M t s website dng PHP

2. Ho t ng c a Web Server
a. C ch b. V d

3. Yu c u ci t
a. Web server (Apache, IIS) b. Ph n m m PHP (trnh thng d ch PHP) c. H qu n tr c s d li u (mysql, SQL Server, Access)

4. Gi i php ci t tr n gi (WAMP, LAMP, XAMP WAMP, XAMP)

1. Gii thiu PHP Lch s


PHP : Rasmus Lerdorf in 1994 ( c pht tri n pht sinh cc form ng nh p s d ng giao th c HTTP c a Unix) PHP 2 (1995) : Chuy n sang ngn ng script x l trn 1995) server. H tr CSDL, Upload File, khai bo bi n, m ng, hm quy, cu i u ki n, bi u th c, PHP 3 (1998) : H tr ODBC, a h i u hnh, giao th c 1998) email (SNMP, IMAP), b phn tch m PHP (parser) c a Zeev Suraski v Andi Gutmans PHP 4 (2000) : Tr thnh m t thnh ph n c l p cho cc 2000) webserver. Parse i tn thnh Zend Engine. B sung cc tnh nng b o m t cho PHP PHP 5 (2005) : B sung Zend Engine II h tr l p trnh 2005) HT, XML, SOAP cho Web Services, SQLite Phin b n m i nh t c a PHP l version PHP 5.2.4 (www.php.net)
4

1. Gii thiu PHP PHP l g?


PHP c pht tri n t ngn ng k ch b n (script) v i m c ch xy d ng trang Web c Personal Page). nhn (Personal Home Page Sau c pht tri n thnh m t ngn ng hon ch nh v c a chu ng trn ton th gi i trong vi c pht tri n cc ng d ng Web. PHP l m t ngn ng thng d ch. L ngn ng server-side script, tng t nh ASP, JSP, th c thi pha Server. T p tin PHP c ph n m r ng l .php C php tng t ngn ng C & Perl
5

1. Gii thiu PHP u im


(Multi - Platform)
Web Servers: Apache, Microsoft Servers Netscape Enterprise Server IIS, Caudium,

H i u hnh UNIX (HP-UX, OpenBSD, Solaris, hnh: Linux), Mac OSX, Windows NT/98/2000/XP/2003/vista H QTCSDL Adabas D, dBase, Empress, FilePro QTCSDL: (read-only), Hyperwave, IBM DB2, Informix, Ingres, InterBase, FrontBase, mSQL, Direct MS-SQL, MySQL, ODBC, Oracle (OCI7 and OCI8), Ovrimos, PostgreSQL, SQLite, Solid, Sybase, Velocis, Unix dbm
6

1. Gii thiu PHP u im


PHP c s d ng r ng ri trn mi tr ng pht tri n web

1. Gii thiu PHP Mt s website dng PHP

2. Hot ng ca Web Server

C CH HOT NG
9

2. Hot ng ca Web Server


Apache v IIS c xy d ng p ng cc yu c u (request) cc t p tin HTML Khng hi u cch th c thi m PHP pha server Apache s d ng cc modules hi u cch th c thi cc o n m vi t b ng PHP IIS s d ng t p l nh ISAPI - Internet Server Application Programming Interface - hi u cc l nh c a PHP v ASP Ngoi ra, c Apache v IIS u h tr nhi u module khc ph c v cho vi c tri n khai ng d ng web m t cch hi u qu
10

2. Hot ng ca Web Server


<html> <head> <title>PHP Test</title> </head> <body> <?php echo '<p>Hello World</p>'; ?> </body> </html> <html> <head> <title>PHP Test</title> </head> <body> <p>Hello World</p> </body> </html>

hello.php

output

11

2. Hot ng ca Web Server

12

3. Yu cu ci t
Download Apache Server
Download Apache for free here: http://httpd.apache.org/download.cgi

Download PHP
Download PHP for free here: http://www.php.net/downloads.php

Download MySQL Database


Download MySQL for free here: http://www.mysql.com/downloads/index.html

13

4. Gii php trn gi


LAMP Linux

WAMP Windows

XAMPP Windows/Linux

14

Phn 2: PHP cn bn

Ni dung phn 2
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. PHP v HTML Cu l nh PHP Ghi ch trong PHP Khai bo bi n Ki u d li u Ton t C u trc i u khi n Hm Ph m vi c a bi n Bi n tnh Lm vi c v i file v th m c L p i t ng trong PHP
16

1. PHP v HTML

17

2. Cu lnh PHP
Pht bi u:
Cc cu l nh php cch nhau b i d u ; Khng phn bi t kho ng tr ng, tab hay k t xu ng dng.

V d :

18

3. Ghi ch trong PHP


Ghi ch c a PHP tng t nh c a C++ v Perl C 3 lo i ghi ch:
S d ng // ghi ch // S d ng # ghi ch # S d ng /* */ ghi ch

V d : <? print cho m i ngu i.; //print dng xu t chu i ?> <?=$bien; <?=$bien; ?> #tng t nh <? print $bien; ?> 19

4. Khai bo bin
C php: $ten_bien = value; Khng khai bo ki u d li u Bi n t ng c kh i t o khi gn gi tr l n u Tn bi n
Bao g m cc k t (A..Z, a..z), k s (0..9),_ Khng c b t u b ng k s (0..9) Phn bi t ch hoa ch th ng

V d :
ng c php: $hoten, $_pass Sai c php: $2host
20

4. Khai bo bin
Variable variables
Cho php thay i tn bi n Vd
<? $varname=Bien_moi; $$varname= xyz; //$Bien_moi= xyz ?>

H ng s - Constants
<?
define("MY_CONST", 10); echo MY_CONST;

?>
21

5. Kiu d liu
boolean integer double string array object M t bi n trong PHP c th lu b t k ki u d li u no
22

5. Kiu d liu
Chuy n i ki u d li u Cch 1 (automatic)
$var = 100 + 15; $var = 100 + 15.0; $var = 39. Steps;//Ch

Cch 2 (datatype) $var Cch 3 settype($var, datatype)

VD:

23

5. Kiu d liu
Ki m tra ki u d li u gettype is_string is_integer is_array is_double is_object V d
$var = test; if (isset($var)) echo Variable is Set; if (empty($var)) echo Variable is Empty;
24

isset unset empty

5. Kiu d liu
M t s hm x l s

Tra H ng D n V d : trong PHP Manual // Pht sinh m t m m ng u nhin $seed = (float) microtime()*100000000; // Kh i t o b pht sinh s ng u nhin srand($seed); // In s ng u nhin print rand(); // Gi tr ng u nhin t 0 n getmaxrand( ) print rand(1, 6); // Gi tr ng u nhin t 1 n 6
25

5. Kiu d liu
Ki u string
Ton t n i chu i .
$str=Hello . World!; //$str = Hello World!;

Phn bi t d u nhy n, d u nhy kp


$user = Mr Bean; print Hi $user; // Hi $user print Hi $user;// Hi Mr Bean print Hi. $user;// ???? print Hi. $user;// ????

26

5. Kiu d liu: Kiu chui (tt)


Gi i h n b i nhy n () ho c kp () Chu i t trong nhy kp b thay th v x l k t thot. Trong nhy n th khng. V d :
$a = Hello; $b = $a world; //tng ng $b=Hello world $c = $a world; //$c=$a world (khng thay i)

27

5. Kiu d liu: Kiu chui (tt)


lm r cc bi n trong chu i, c n bao bi n vo gi a c p ngo c nh n { }
$a = He; $b = $allo; //l i v PHP hi u l $allo $c = {$a}llo; //ng ($c = Hello)

28

5. Kiu d liu: Kiu chui (tt)


K t thot: \
S d ng vi t cc k t c bi t trong chu i VD: C n c chu i: Ng i ta ni PHP r t t t $a = Ng i ta ni PHP r t t t; //Sai $a = Ng i ta ni \PHP r t t t\; //ng M t s k t Ngoi ra:

ph i s

d ng k t

thot: $, \,

\n: Xu ng dng \r: tr v u dng \t: d u tab


29

5. Kiu d liu: Kiu chui (tt)


Ki u ti li u (heredoc):
Cho php vi t 1 chu i trn nhi u dng. Khng c n s d ng k t thot: Cch vi t: $bi n = <<<K_hi u n i dung trn nhi u dng K_hi u; Ch : K_hi u ph i c vi t k t u tin c a dng V d : $a = <<<EOD y l chu i n m trn nhi u dng s d ng c php ki u ti li u heredoc EOD;
30

5. Kiu d liu: Kiu chui (tt)


<?php Ki u Heredoc $str = <<<EOA Example of string <br> spanning multiple lines<br> using heredoc syntax.<br> EOA;//khng c c kho ng tr ng u dng echo($str); $name = mr bean"; $d = date("d/m/y"); $str = <<<EOQ This is a lecture of $name.<br> Ngay $d<br> EOQ; echo($str); ?>
31

Cc hm x

l chu i

Cc x l c b n
strlen($chu strlen($chu i) substr($chu substr($chu i, $v tr, $chi u_di) strtoupper ($chu i) strtolower ($chu i) iconv(m ngu n, m ch, $chu i) trim($chu trim($chu i, k t mu n c t) ltrim($chu ltrim($chu i, k t mu n c t) rtrim($chu rtrim($chu i, k t mu n c t)

32

Cc hm x
Tm ki m

l chu i

strpos($chu strpos($chu i, $chu i_con, $v _tr_b t u) strrpos ($chu i, $chu i_con, $v _tr_b t u)

So snh
strcmp($chu strcmp($chu i_1, $chu i_2) strncmp($chu strncmp($chu i_1, $chu i_2, $chi u_di) strcasecmp($chu strcasecmp($chu i_1, $chu i_2) strncasecmp($chu strncasecmp($chu i_1, $chu i_2, $chi u_di) strnatcmp($chu strnatcmp($chu i_1, $chu i_2) strnatcasecmp($chu strnatcasecmp($chu i_1, $chu i_2)

33

5. Kiu d liu
<?php $n = 43951789; $u = -43951789; $c = 65; // ASCII 65 is 'A' printf("%%b = '%b'\n", $n); printf("%%c = '%c'\n", $c); printf("%%d = '%d'\n", $n); printf("%%e = '%e'\n", $n); printf("%%u = '%u'\n", $n); printf("%%u = '%u'\n", $u); printf("%%f = '%f'\n", $n); printf("%%o = '%o'\n", $n); printf("%%s = '%s'\n", $n); printf("%%x = '%x'\n", $n); printf("%%X = '%X'\n", $n); printf("%%+d = '%+d'\n", $n); printf("%%+d = '%+d'\n", $u); ?>

Hm printf
%b = '10100111101010011010101101' %c = 'A' %d = '43951789' %e = '4.39518e+7' %u = '43951789' %u = '4251015507' %f = '43951789.000000' %o = '247523255' %s = '43951789' %x = '29ea6ad' %X = '29EA6AD' %+d = '+43951789'

%+d = '-43951789' 34

5. Kiu d liu
<?php $input = "Alien"; echo str_pad($input, echo str_pad($input, echo str_pad($input, echo str_pad($input, ?> 10); 10, "-=", STR_PAD_LEFT); 10, "_", STR_PAD_BOTH); 6 , "___"); // // // // produces produces produces produces "Alien " "-=-=-Alien" "__Alien___" "Alien_"

Hm str_pad
STR_PAD_RIGHT : Thm vo bn ph i (m c nh) STR_PAD_LEFT : Thm vo bn tri STR_PAD_BOTH : Thm c hai pha

35

5. Kiu d liu
<?php $array = array('lastname', 'email', 'phone'); $comma_separated = implode(",", $array); echo $comma_separated; // lastname,email,phone ?>

<?php // Example 1 $pizza = "piece1 piece2 piece3 piece4 piece5 piece6"; $pieces = explode(" ", $pizza); echo $pieces[0]; // piece1 echo $pieces[1]; // piece2 // Example 2 $data = "foo:*:1023:1000::/home/foo:/bin/sh"; list($user,$pass,$uid,$gid,$gecos,$home,$shell) = explode(":", $data); echo $user; // foo echo $pass; // * ?>

X l chu i

36

5. Kiu d liu
M ng (Array Array)
<?php $colors = array('red', 'blue', 'green', 'yellow'); sort($colors); foreach ($colors as $color) { echo "Do you like $color?<br>"; Do you like blue? } Do you like green? $num = count($colors); Do you like red? echo We have $num items<br>; Do you like yellow? We have 4 items ?>

37

5. Kiu d liu
M ng (Array Array)
<?php // PHP 5 foreach ($colors as &$color) { $color = strtoupper($color); } unset($color); /* ensure that following writes to $color will not modify the last array element */ // Workaround for older versions (phin b n tr c PHP 5) foreach ($colors as $key => $color) { Array $colors[$key] = strtoupper($color); ( } [0] => RED print_r($colors); ?>
) [1] => BLUE [2] => GREEN [3] => YELLOW

38

5. Kiu d liu
<?php $a = array("a" => "apple", "b" => "banana"); $b = array("a" => "pear", "b" => "strawberry", "c" => "cherry"); $c = $a + $b; // Union of $a and $b echo "Union of \$a and \$b: \n"; var_dump($c); $c = $b + $a; // Union of $b and $a echo "Union of \$b and \$a: \n"; var_dump($c); ?>

Union of $a and $b: array(3) { ["a"]=> string(5) "apple" ["b"]=> string(6) "banana" ["c"]=> string(6) "cherry" }

Union of $b and $a: array(3) { ["a"]=> string(4) "pear" ["b"]=> string(10) "strawberry" ["c"]=> string(6) "cherry" }
39

5. Kiu d liu
<?php /* Suppose that $var_array is an array returned from wddx_deserialize */ $size = "large"; $var_array = array("color" => "blue", "size" => "medium", "shape" => "sphere"); extract($var_array, EXTR_PREFIX_SAME, "wddx"); echo "$color, $size, $shape, $wddx_size\n"; ?>

blue, large, sphere, medium

40

5. Kiu d liu
<?php $info = array('coffee', 'brown', 'caffeine'); // Listing all the variables list($drink, $color, $power) = $info; echo "$drink is $color and $power makes it special.\n"; // Listing some of them list($drink, , $power) = $info; echo "$drink has $power.\n"; // Or let's skip to only the third one list( , , $power) = $info; echo "I need $power!\n"; // list() doesn't work with strings list($bar) = "abcde"; var_dump($bar); // NULL ?> 41

Cc hm x l mng

S px p
Theo gi tr
sort($m sort($m ng) / asort($m ng) asort($m rsort($m rsort($m ng) / arsort($m ng) arsort($m natsort($m natsort($m ng) / natcasesort($m ng) natcasesort($m chu i usort($m usort($m ng, hm_so_snh) // t uasort($m uasort($m ng, hm_so_snh) // t // tng d n // gi m d n // tng d n, dng cho nh ngha th nh ngha th t t

Theo kha
ksort($m ksort($m ng) krsort($m krsort($m ng) uksort($m uksort($m ng, hm_so_snh) // tng d n // gi m d n // t nh ngha th t

42

Cc hm x l mng
N i ghp hai m ng
array_merge($m array_merge($m ng1, $m ng2) array_combine($m array_combine($m ng1, $m ng2) array_intersect($m array_intersect($m ng1, $m ng2)

Tm ki m
array_search($gi_tr array_search($gi_tr , $m ng)

43

6. Ton t

44

6. Ton t
Ex
$a == $b $a === $b $a != $b $a <> $b $a !== $b $a < $b $a > $b $a <= $b $a >= $b Equal Identical Not equal Not equal Not identical Less than Greater than Less than or equal to Greater than or equal to

Name
TRUE if $a is equal to $b.

Result

TRUE if $a is equal to $b, and they are of the same type. (PHP 4) 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) 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.

45

7. Cu trc iu khin

i u ki n if i u khi n switch Vng l p for Tng t Vng l p while Vng l p do.. While Vng l p foreach T kha break, continue

nh C++

46

Cu lnh if if (bi u th c i u ki n) n) kh i l nh 1 else kh i l nh 2

47

7. Cu trc iu khin
R nhnh v i if else
if ($a > $b) { echo "a > b"; $a = $b; } else { echo "a <= b"; $b = $a; }

48

Cu lnh switch
switch (bi u th c) c) { case bi u th c 1: kh i l nh 1 case bi u th c 2: kh i l nh 2 ... case bi u th c n: kh i l nh n default: default: kh i l nh cu i }
49

7. Cu trc iu khin
R nhnh v i switch case
switch ($a) { case 0: echo "a = 0"; break; case 1: echo "a = 1"; break; }

50

Vng lp while/do...while
while (bi u th c i u ki n) n) kh i l nh Hay: do kh i l nh while (bi u th c i u ki n); n)

51

7. Cu trc iu khin
L p v i while & do while
while ($i++ < 5) { switch ($i) { case 2: echo "At 2"; case 5: echo "At 5"; default: break; } }

break; break 2;

52

Vng lp for
for (bi u th c 1; bi u th c 2; bi u th c 3) 1; kh i l nh
bi u th c 1: th c hi n 1 l n khi b t u vng l p bi u th c 2: i u ki n l p, c xem xt tr c m i l nl p bi u th c 3: th c hi n sau m i l n l p

53

7. Cu trc iu khin
L p v i for & foreach
for ($i=1, $j=0; $i<=10; $j+=$i, print $i, $i++); $arr = array(1, 2, 3, 4); foreach ($arr as &$value) { $value = $value * 2; } $arr = array("one", "two", "three"); foreach ($arr as $key => $value) { echo "Key: $key; Value: $value"; }

54

Cc lnh ngt lp break


Ngng v thot ra kh i vng l p hi n t i

continue
Ngng th c hi n l n l p hi n hnh chuy n sang l n l p ti o theo

55

7. Cu trc iu khin
<?php $arr = array(1, 2, 3, 4); foreach ($arr as &$value) { $value = $value * 2; } // $arr is now array(2, 4, 6, 8) unset($value); // break the reference with the last element ?> <?php $arr = array("one", "two", "three"); reset($arr);// reset pointer, start again on first element while (list(, $value) = each($arr)) { echo "Value: $value<br />\n"; } foreach ($arr as $value) { echo "Value: $value<br />\n"; } ?> 56

7. Cu trc iu khin
<?php $arr = array("one", "two", "three"); reset($arr); while (list($key, $value) = each($arr)) { echo "Key: $key; Value: $value<br />\n"; } foreach ($arr as $key => $value) { echo "Key: $key; Value: $value<br />\n"; } ?> Key: 0; Value: one Key: 1; Value: two Key: 2; Value: three Key: 0; Value: one Key: 1; Value: two Key: 2; Value: three
57

8. Hm
<?php function takes_array($input) { echo "$input[0] + $input[1] = ", $input[0]+$input[1]; } $input = array(4,7); takes_array($input); ?> <?php 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.' ?> 58

lu : d u &

8. Hm
nh ngha
<?php <?php function tn_hm([danh sch tham s ...]) tn_hm( ...]) { [thn hm ...] } ?>

G i hm
Nh p tn hm (khng phn bi t ch in hoa-th ng) v hoacung c p y cc tham s c n thi t trong c p d u ()

59

8. Hm
K t thc v tr k t qu
L nh return dng k t thc v tr k t qu cng nh quy n i u hi n l i cho ni g i hm. N u khng c hm. l nh return th m c nh hm tr v gi tr NULL. NULL. Mu n tr v hn m t gi tr th ph i dng m ng

Truy n tham s
M c nh cc tham s c truy n vo bn trong hm theo phng php tham tr . Tr ng h p mu n thay i tr c ti p trn cc tham s truy n th ng i ta dng phng php tham chi u, thm d u & tr c tn tham s (khi nh ngha) cng nh tn bi n c truy n lm tham (khi g i hm)

60

8. Hm
Tham s c gi tr m c nh
Tng t cch khai bo v gn gi tr u tin cho bi n, thng th ng lo i tham s ny nn t cu i trong danh sch tham s Khi g i hm n u b tr ng t i v tr tham s c gi tr m c nh th m c nhin gi tr m c nh c dng cho tham s

Hm c s l ng tham s khng xc nh
Khai bo danh sch tham s r ng () S d ng cc hm sau l y danh sch cc tham s : func_num_args(): s l ng tham s khi hm c g i func_get_arg(i): gi tr cc tham s th i c truy n (b t u t 0) func_get_args(): danh sch t t c cc tham s

61

8. Hm
Bi n tnh
Thm t kha static khi khai bo bi n c kh i t o (v gn gi tr ) m t l n u tin duy nh t trong su t qu trnh th c thi c a script

S d ng bi n ton c c
Khai bo l i bi n ton c c v i t kha global (bn trong hm) c th s d ng c bi n ton c c ny bn trong hm S d ng cc hm sau l y danh sch cc tham s : func_num_args(): func_num_args(): s l ng tham s khi hm c g i func_get_arg(i): func_get_arg(i): gi tr cc tham s th i c truy n (b t u t 0) func_get_args(): danh sch t t c cc tham s

62

8. Hm
Ph m vi
C gi tr s d ng trong ton script, ngay c tr c v sau khi nh ngha

L ng hm
Cho php nh ngha l ng hm, th m ch l ng bn trong m t c u trc i u khi n (if, switch, while/do, while) Lo i hm ny c ph m vi trong ton script v khng th nh ngha l i

63

8. Hm
<?php function makecoffee($type = "cappuccino") { return "Making a cup of $type.\n"; } echo makecoffee(); echo makecoffee(null); echo makecoffee("espresso"); ?>
<?php function makecoffee($types = array("cappuccino"), $coffeeMaker = NULL) { $device = is_null($coffeeMaker) ? "hands" : $coffeeMaker; return "Making a cup of ".join(", ", $types)." with $device.\n"; } echo makecoffee(); echo makecoffee(array("cappuccino", "lavazza"), "teapot"); ?>

64

8. Hm
<?php function makeyogurt($type = "acidophilus", $flavour) { return "Making a bowl of $type $flavour.\n"; } echo makeyogurt("raspberry");// won't work as expected ?>

<?php function makeyogurt($flavour, $type = "acidophilus") { return "Making a bowl of $type $flavour.\n"; } echo makeyogurt("raspberry"); ?> // works as expected

65

8. Hm
<?php function square ($num) { return $num * $num; } echo square (4);//outputs '16 ?> <?php function &returns_reference() { return $someref; } $newref=&returns_reference(); ?>

<?php function small_numbers() { return array (0, 1, 2); } list($zero,$one,$two)=small_numbers(); ?>

66

8. Hm
<?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() ?>

67

8. Hm
<?php class Foo { function Variable() { $name = 'Bar'; $this->$name(); // This calls the Bar() method } function Bar() { echo "This is Bar"; } } $foo = new Foo(); $funcname = "Variable"; $foo->$funcname(); // This calls $foo->Variable() ?> 68

9. Phm vi ca bin
<?php $a = 1; $b = 2; function Sum() { global $a, $b; $b = $a + $b; } Sum(); echo $b; ?> <?php $a = 1; $b = 2; function Sum() { $GLOBALS["b"] = $GLOBALS["a"] + $GLOBALS["b"]; } Sum(); echo $b; ?>

69

9. Phm vi ca bin
<?php $a = 1; include "b.inc"; ?> Ph m vi c a bi n [a] c tc d ng trong c b.inc ---------------------------------------------<?php $a = 1; // global scope function Test() { echo $a;// reference to local scope variable } Test(); ?> Bi n [a] ngoi v trong hm Test khc nhau
70

9. Phm vi ca bin
Tn bi n $GLOBALS $_SERVER $_GET $_POST $_COOKIE $_FILE $_ENV M t
ch a t t c cc bi n ton c c m o n script c c b c th truy c p ch a thng tin v mi tr ng c a web server ch a thng tin c a yu c u d ng GET ch a thng tin c a yu c u d ng POST ch a thng tin t HTTP cookie ch a thng tin t vi c t i t p tin ln ki u POST ch a thng tin v mi tr ng th c thi c a o n script

$_REQUEST ch a thng tin nh p vo c a ng i dng $_SESSION


ch a thng tin c a cc session c ng k
71

10. Bin tnh


<?php function Test() { $a = 0; echo $a; $a++; } Test(); Test(); ?> <?php function Test() { static $a = 0; echo $a; $a++; } Test(); Test(); ?>

?
72

11. Lm vic vi tp tin v th mc


1. S d ng include() 2. S d ng include_once() 3. S d ng include_path cho cc d n l n 4. Ki m tra file 5. c, ghi file 6. Lm vi c v i th m c

73

11. Lm vic vi tp tin v th mc


L nh include() cho php b n ph i h p gi a cc file trong m t PHP project, ko gi ng nh c php #include c a ngn ng C, l nh ny khng chn m l nh vo file m th c thi file php gi ng nh c php g i hm include() s d ng chia s cc hm dng chung, cc o n m chung trong m t project c nhi u file N u khng tm th y file, include() thng bo warning nhng khng d ng chng trnh PHP cung c p 1 l nh tng t include() l require(), l nh ny c s khc bi t l s d ng ngay chng trnh khi khng tm th y file
74

11. Lm vic vi tp tin v th mc


//vars.php <?php $color = 'green'; $fruit = 'apple'; ?> //test.php <?php echo "A $color $fruit"; // A include 'vars.php'; echo "A $color $fruit"; // A green apple ?>

V include() th c hi n l i g i n file php, php, do b n c th tr v gi tr t file PHP c include


<!--File1.php--> <?php return 4 + 4; ?> -----------------------------------<!--File2.php--> <?php echo "This is from file 2<br>"; $retVal = include("file1.php"); echo Value file 1: $retVal<br>"; echo "This is from file 2\n"; ?> 75

11. Lm vic vi tp tin v th mc


C th t l nh include bn trong 1 c u trc i u ki n ho c c u trc l p, Khi ty theo i u ki n c a c u trc m include() c c th c hi n hay khng, 1 hay nhi u l n Vi c ny gip h tr cho vi c thi t k ki n

trc trang web t t hn.


76

11. Lm vic vi tp tin v th mc


include_once() gi ng nh include(), tuy nhin c i m khc bi t l ch include 1 l n, l n sau n u g p l i file ny th ko include n a include_once() phn bi t ch hoa, ch th ng
<?php include_once("a.php"); // this will include a.php include_once("A.php"); // this will include a.php again on Windows! ?>

V phn bi t ch hoa/th ng nn include_one chn thm l n th hai


77

11. Lm vic vi tp tin v th mc


include file theo ng d n tuy t i: Cch ny d v khi ci t trn my khc s khng tm th y file c include include file theo ng d n tng i: Cch ny t t hn, nhng m i khi i v tr c a file c include th ph i s a l i t i t t c cc file th c hi n l i g i include Cch t t nh t l s d ng include_path (thi t l p trong file PHP.INI) i v i nh ng file th vi n dng chung c s d ng nhi u (gi ng nh i v i ngn ng C)
78

11. Lm vic vi tp tin v th mc


thay i include_path trong PHP.INI dng l nh 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 l nh 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")); ?> 79

11. Lm vic vi tp tin v th mc


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/>"; print "$file was modified on ".date( "D d M Y g:i A", filemtime( $file))."<br/>"; print "$file was changed on".date( "D d M Y g:i A", filectime($file))."<br/>"; } outputFileTestInfo("c:\\windows\\system32\\cmd.exe"); ?> 80

11. Lm vic vi tp tin v th mc


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

81

11. Lm vic vi tp tin v th mc


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

echo "Read line by line......\n"; $f = fopen("test.txt", "rt"); echo "Read all file......\n"; $myfile = while (!feof($f)) { file_get_contents("test.txt"); $line = fgets($f); echo($myfile); echo "$line"; } ?> fclose($f);

82

11. Lm vic vi tp tin v th mc


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

11. Lm vic vi tp tin v th mc


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

11. Lm vic vi tp tin v th mc


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

85

Bi tp
Vi t m t script th c hi n cng vi c sau:
Yu c u ng i dng nh p vo m t s nguyn em so snh s v a nh p v i m t s nguyn cho tr c N u b ng th xu t ra cu chc m ng ng i dng on ng con s b m t Ng c l i th th thng bo k t qu l con s v a nh p l l n hay b hn con s b m t v yu c u nh p l i cho n khi nh p ng

86

12. Lp v i tng trong PHP Khai bo l p Hm t o Ph m vi K th a Hm serialize,unserialize


87

12. Lp v i tng trong PHP


Khai bo

Hm t o

88

12. Lp v i tng trong PHP


Khai bo l p
class tn_l p { cc thu c tnh v phng th c }

T o v h y m t i t ng
$tn_bi n = new tn_l p(); i t ng s t ng b h y khi khng cn tham chi u no n n $tn_bi n = NULL; NULL;

89

12. Lp v i tng trong PHP


Cc t

kha khai bo:

public: public: c th s d ng bn ngoi l p private: private: ch s d ng c c b bn trong l p protected: protected: s d ng c b i cc l p k th a

M t s quy t c chung:
Khng th khai bo hai method trng tn Method ph i c khai bo ngay bn trong khai bo l p Dng bi n gi $this truy xu t cc member v method trong l p Dng ton t -> truy xu t n member v method

90

12. Lp v i tng trong PHP


Khai bo constructor v destructor
public function __construct(danh sch tham s ) __construct(danh { kh i t o gi tr cc member }
constructor c t ng th c hi n khi i t ng c t o

public function __destruct() __destruct() { d nd p }


destructor c t ng th c hi n khi i t ng b h y
91

91

12. Lp v i tng trong PHP

92

L p trnh h ng i t ng: constant Khai bo


const TN_H NG = gi tr ;

Truy xu t
tn_l p::TN_H NG p::TN_H seft::TN_H seft::TN_H NG // ngoi l p // trong l p

93

L p trnh h ng i t ng: static member Khai bo


static $thu c_tnh

Truy xu t
tn_l p::$thu c_tnh // ngoi l p seft::$thu c_tnh // trong l p

94

L p trnh h ng i t ng: static method Khai bo


static function phng_th c()

Truy xu t
tn_l p::phng_th c() // ngoi l p seft:: phng_th c() // trong l p

95

L p trnh h ng i t ng: l p con


Khai bo l p con
class l p_con extends l p_cha { cc thu c tnh v phng th c } T t c cc member v method c khai bo public hay protected trong l p cha c th a k v c th s d ng trong l p con

96

L p trnh h ng i t ng:
phng th c n p ch ng G i m t method l p cha
parent::phng_th parent::phng_th c()
B ng cch nh ngha l i m t phng th c c l p cha, t t c cc l i g i n phng th c ny m khng ch nh r nh trn s c hi u l g i phng th c c cng tn c a l p con

97

L p trnh h ng i t ng:s ng:s


Khai bo l p tr u t ng
abstract class l p_tr u_t ng { // cc thu c tnh abstract public function phng_th c_tr u_t ng(); // cc phng th c khc }

a hnh

Khng th t o i t ng tr c ti p t l p tr u t ng L p con b t bu c ph i nh ngha cc phng th c tr u t ng c a l p cha


98

L p trnh h ng i t ng: ngn k th a v n p ch ng L p khng th k th a


final class khng_th _k _th a { }

Phng th c khng th n p ch ng
final public function khng_th _n p_ch ng() { }

99

L p trnh h ng i t ng: interface


Khai bo Interface
interface giao_di n { public function phng_th c(); }

Khai bo l p theo m u Interface


abstract class tn_l p implements giao_di n { } Cc l p s d ng Interface hay k th a t m t l p s d ng Interface b t bu c ph i nh ngha t t c cc phng th c trong Interface
100

12. Lp v i Tng trong PHP

101

12. Lp v i Tng trong PHP


1. Hm serialize() dng lu tr i tng, hm tr v mt chui cc byte lu thng tin ca i tng 2. 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 Ngoc Thuy Hang"; $luu = serialize($ob1); echo "$luu <br>"; $ob2 = unserialize($luu); var_dump($ob2); ?>
102

Cu hi v tho lun

103

You might also like