09 udpt - session, cookie, file, mail - updated

63
LOGO ng dng phân tán – Xây dng UD Web Chđề 9 Cookies, Session, File, Email GV: Nguyễn Trường Sơn 1

Upload: maria-bong

Post on 09-Nov-2015

223 views

Category:

Documents


1 download

DESCRIPTION

Ứng dụng phân tán PHP

TRANSCRIPT

  • LOGO

    ng dng phn tn Xy dng UD Web

    Ch 9

    Cookies, Session, File, Email

    GV: Nguyn Trng Sn

    1

  • Ni dung

    K thut Upload File bng PHP S dng Cookie trong PHP S dng Session trong PHP K thut gi mail bng PHP

    2

  • Ni dung

    K thut Upload File bng PHP S dng Cookie trong PHP S dng Session trong PHP K thut gi mail bng PHP

    3

  • K thut Upload File bng PHP

    C ch Upload File Cc bc thc hin upload le Kim tra li, nh dng, kch thc File upload Mt s li khi upload le Vn quyn truy cp le Vn gii hn kch thc le upload

    4

  • Webserver

    Internet or Intranet

    Yu cu trang upload.php

    Disk driver

    file

    Upload.php $_FILES["file"]["name"] $_FILES["file"]["type"] $_FILES["file"]["size"] $_FILES["file"]["tmp_name"] $_FILES["file"]["error"] move_uploaded_file(tmpName, savedName) file_exists(savedName)

    5

    ..

  • Cc bc cn thit upload file

    Thit k form upload le Ly thng en le upload Di chuyn tp en t th mc tm sang th mc upload

    6

  • 1. Thit k Form Upload File

    Thit lp thuc inh Form Method = POST Enctype = mul0part/form-data

    7

    Browse le

    Trng hp j1 - Upload 1 tp tin:

  • 1. Thit k Form Upload File

    Browse le 1 Browse le 2 Browse le 3

    Trng hp 2 - Upload nhiu tp tin CCH 1:

    8

  • 1. Thit k Form Upload File

    Browse les

    Trng hp 3 - Upload nhiu tp tin CCH 2:

    9

  • 2. Ly thng tin file upload

    $_FILES: mng cha thng en cc le upload

    Trng hp 1: Upload 1 tp en $_FILES ['userle'] : thng en le ca 1 le eld Cc thuc inh:

    name type tmp_name error size

    10

  • 2. Ly thng tin file upload

    Trng hp 2: Upload nhiu tp en Cch 1 $_FILES : cha mng cc le Truy xut thng en cc tp en bng cch duyt mng hoc truy

    xut tng le eld

    Cc thuc inh: name type tmp_name error size

    11

    foreach ($_FILES as $file) { echo "name: " . $file['name'] . ""; echo "type: " . $file['type'] . ""; echo "tmp_name: " . $file['tmp_name'] . ""; echo "error: " . $file['error'] . ""; echo "size: " . $file['size'] . ""; echo ""; }

  • 2. Ly thng tin file upload

    Trng hp 3: Upload nhiu tp en Cch 2 $_FILES ['userle'] : mng cc le

    12

    $file = $_FILES["userfile"]; $n = count($file['name']); for($i = 0; $i < $n; $i++) { echo "name: " . $file['name'][$i] . ""; echo "type: " . $file['type'][$i] . ""; echo "tmp_name: " . $file['tmp_name'][$i] . ""; echo "error: " . $file['error'][$i] . ""; echo "size: " . $file['size'][$i] . ""; echo ""; }

    Truy xut cc thuc inh ca le $i: name [$i] type [$i] tmp_name [$i] error [$i] size [$i]

  • V d

    13

  • V d

    14

  • 3. Di chuyn tp tin t th mc tm sang th mc upload

    move_uploaded_le (tmp_name, saved_name)

    15

  • Kim tra li, nh dng, kch thc File upload

    Lu : $_FILES[""]["type"]

    "image/gif" "image/jpeg" Firefox nhn y l le jpeg "image/pjpeg" IE nhn y l le jpeg

    $_FILES[""]["size"] : Kch thc le inh theo byte

    $_FILES[""]["error"] : M li khi upload File = 0 : Khng c li > 0 : C li

    16

  • Mt s li khi upload file

    M li Hng s ngha

    0 UPLOAD_ERR_OK There is no error

    1 UPLOAD_ERR_INI_SIZE The uploaded le exceeds the upload_max_lesize direceve in php.ini

    2 UPLOAD_ERR_FORM_SIZE The uploaded le exceeds the MAX_FILE_SIZE direceve that was specied in the HTML form

    3 UPLOAD_ERR_PARTIAL The uploaded le was only pareally uploaded

    4 UPLOAD_ERR_NO_FILE No le was uploaded

    6 UPLOAD_ERR_NO_TMP_DIR Missing a temporary folder

    7 UPLOAD_ERR_CANT_WRITE Failed to write le to disk

    17

  • Vn v quyn truy cp File

    PHP Warning: move_uploaded_le(upload/14.jpg) [func0on.move-uploaded-le]: failed to open stream: Permission denied in.

    Cp quyn cho th mc /upload

    Account IUSR_XXX

    Lu : Ch cp quyn ghi cho th mc cn thit Khng cp quyn ghi cho th mc WebRoot

    18

  • Vn gii hn kch thc file upload

    Thay i cc tham s trong tp en php.ini: upload_max_lesize (mc nh l 2M) post_max_size (mc nh l 8M)

    Gii hn bng form: Thm tham s MAX_FILE_SIZE trc le eld control

    19

  • Mt s hm qun l file / th mc

    readdir le_exists is_dir is_le unlink rmdir mkdir

    20

  • Ni dung

    K thut Upload File bng PHP S dng Cookie trong PHP S dng Session trong PHP K thut gi mail bng PHP

    21

  • Cookie V d m u

    Chc nng nh mt khu

    22

    Ln ng nhp 1: 1. Ngi dng vo trang ng nhp 2. Ngi dng nhp thng 0n v tn ng

    nhp, mt khu 3. Chn chc nng nh mt khu 4. Thc hin ng nhp v thnh cng

    Ln ng nhp 2: 1. Ngi dng vo trang ng nhp 2. H thng hin th giao din ng

    nhp c sn tn ng nhp v mt khu

    COOKIE

  • Cookie C ch hot ng

    cookie

    setcookie

    $_COOKIE[fieldName]

    Client

    Chc nng nh mt khu

    Webserver

    Lu username & password

    23

    Ln ng nhp 1: 1. Ngi dng vo trang ng nhp 2. Ngi dng nhp thng ;n v tn ng

    nhp, mt khu 3. Chn chc nng nh mt khu 4. Thc hin ng nhp 5. H thng lu mt khu ln my nh

    ca ngi dng

    Ln ng nhp 2: 1. Ngi dng vo trang ng nhp +

    thng 0n ca ngi dng (tn ng nhp, mt khu) c gi ln Server.

    2. H thng hin th giao din ng nhp c sn tn ng nhp v mt khu

  • Cookie Gii thiu

    L 1 tp en c server lu xung my ca client Mi ln client gi request 1 trang web, ng thi s gi km le cookie lu ln trc ln server

    Cc iu khin x l thng en (lu, ly) do server thc hin Thng c s dng lu thng en c nhn ca client

    Webserver

    cookie

    setcookie

    $_COOKIE

    Client

    24

  • Cookie C php s dng

    Lnh ghi cookie setcookie (name, value, expire, path, domain); setrawcookie (name, value, expire, path, domain);

    name : Tn cookie value : Gi tr cookie expire : Ngy/khong thi gian ht hn ht hn ca cookie. path : The path on the server in which the cookie will be available

    on. domain : The domain that the cookie is available. secure : 0 hoc 1

    Ly gi tr cookie: $_COOKIE["cookieName"]

    Xa cookie: setcookie("cookieName", "", time() -3600)

    25

  • Cookie C php s dng

    path: quy nh phm vi chp nhn cookies ca website. / : cookie s c chp nhn ti tt c cc trang ca website /dir_1/dir_2//dir_n/ : cookie s c chp nhn ti cc trang trong th mc dir_n v trong cc th mc con ca n.

    Mc nh path = th mc ca tp en c lnh gn gi tr cookies.

    26

  • Cookie C php s dng

    Gn mt mng trong cookie:

    27

  • V d

    28

    setcookies.php viewcookies.php

  • V d - setcookies.php

    29

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

  • V d - setcookies.php

    30

    20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35

    Set/clear cookies | View Set cookies Key: Value:

  • V d - viewcookies.php

    31

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

    Set/clear cookies | View View Cookies

  • Cookie Mt s ng dng

    Nh mt khu T ng ng nhp Lu trng thi ca ngi dng (gi hng, )

    32

  • Ni dung

    K thut Upload File bng PHP K thut gi mail bng PHP S dng Cookie trong PHP S dng Session trong PHP

    33

  • Session

    L thng en v client c server lu trn my ca server S dng session lu nh danh duy nht cho tng client Mc ch lu bin d liu dng chung cho nhiu trang trong 1 phin lm vic ca client

    Webserver

    Cookie: PHPSESSID

    session_start

    $_SESSION[sessionVar]

    Client

    34

  • Session C php s dng

    Khi ng Session session_start(); Bt buc phi xut hin trc th

    Ghi & c gi tr Session $_SESSION["sessionVar"] = value $_SESSION["sessionVar"][ ] = array() if (isset($_SESSION["sessionVar"])

    echo $_SESSION["sessionVar"];

    Hy Bin trong Session unset($_SESSION["sessionVar"]);

    Hy c Session session_destroy();

    35

  • Session Cu hnh

    Cu hnh trong php.ini ini_set('parameterName', 'value');

    Gi trc hm session_start();

    parameterName Default session.auto_start 0 Khng t ng session.cookie_lifetime 0 Thi gian tn ti cho

    cookie (mc nh l n khi ng browser)

    session.name PHPSESSID Tn session (m s c dng t tn cho cookie)

    36

  • Parameter Name Default Ghi ch

    session.save_path "" denes the argument which is passed to the save handler. If you choose the default les handler, this is the path where the les are created. Defaults to /tmp.

    session.name "PHPSESSID" species the name of the session which is used as cookie name. It should only contain alphanumeric characters. Defaults to PHPSESSID.

    session.save_handler "les" denes the name of the handler which is used for storing and retrieving data associated with a session. Defaults to les.

    session.auto_start "0" species whether the session module starts a session automaecally on request startup. Defaults to 0 (disabled).

    session.gc_probability "1" in conjunceon with session.gc_divisor is used to manage probability that the gc (garbage colleceon) rouene is started. Defaults to 1

    session.gc_divisor "100" coupled with session.gc_probability denes the probability that the gc (garbage colleceon) process is started on every session iniealizaeon. The probability is calculated by using gc_probability/gc_divisor, e.g. 1/100 means there is a 1% chance that the GC process starts on each request. session.gc_divisor defaults to 100.

    session.gc_maxlifeeme "1440" species the number of seconds aer which data will be seen as 'garbage' and cleaned up. Garbage colleceon occurs during session start. session.serialize_handler "php"

    session.cookie_lifeeme "0" species the lifeeme of the cookie in seconds which is sent to the browser. The value 0 means "unel the browser is closed." Defaults to 0. See also session_get_cookie_params() and session_set_cookie_params(). Since the cookie is returned by the browser, it is not prolonged to suce the lifeeme. It must be sent manually by setcookie().

    session.cookie_path "/" species path to set in session_cookie. Defaults to /. See also session_get_cookie_params() and session_set_cookie_params().

    session.cookie_domain "" species the domain to set in session_cookie. Default is none at all meaning the host name of the server which generated the cookie according to cookies specicaeon. See also session_get_cookie_params() and session_set_cookie_params().

    session.cookie_secure "" species whether cookies should only be sent over secure conneceons. Defaults to o. This seng was added in PHP 4.0.4. See also session_get_cookie_params() and session_set_cookie_params().

    session.cookie_hponly "" Marks the cookie as accessible only through the HTTP protocol. This means that the cookie won't be accessible by scripeng languages, such as JavaScript. This seng can eectly help to reduce idenety the through XSS aacks (although it is not supported by all browsers).

    37

  • Parameter Name Default Ghi ch

    session.use_cookies "1" species whether the module will use cookies to store the session id on the client side. Defaults to 1 (enabled).

    session.use_only_cookies "1" species whether the module will only use cookies to store the session id on the client side. Enabling this seng prevents aacks involved passing session ids in URLs. This seng was added in PHP 4.3.0.

    session.referer_check "" contains the substring you want to check each HTTP Referer for. If the Referer was sent by the client and the substring was not found, the embedded session id will be marked as invalid. Defaults to the empty string.

    session.entropy_le "" gives a path to an external resource (le) which will be used as an addieonal entropy source in the session id creaeon process. Examples are /dev/random or /dev/urandom which are available on many Unix systems.

    session.entropy_length "0" species the number of bytes which will be read from the le specied above. Defaults to 0 (disabled).

    session.cache_limiter "nocache" species cache control method to use for session pages (none/nocache/private/private_no_expire/public). Defaults to nocache. See also session_cache_limiter().

    session.cache_expire "180" species eme-to-live for cached session pages in minutes, this has no eect for nocache limiter. Defaults to 180. See also session_cache_expire(). session.use_trans_sid "0" whether transparent sid support is enabled or not. Defaults to 0 (disabled).

    session.bug_compat_42 "1" PHP versions 4.2.3 and lower have an undocumented feature/bug that allows you to iniealize a session variable in the global scope, albeit register_globals is disabled. PHP 4.3.0 and later will warn you, if this feature is used, and if session.bug_compat_warn is also enabled. This feature/bug can be disabled by disabling this direceve.

    session.bug_compat_warn "1" PHP versions 4.2.3 and lower have an undocumented feature/bug that allows you to iniealize a session variable in the global scope, albeit register_globals is disabled. PHP 4.3.0 and later will warn you, if this feature is used by enabling both session.bug_compat_42 and session.bug_compat_warn.

    session.hash_funceon "0" session.hash_funcVon allows you to specify the hash algorithm used to generate the session IDs. '0' means MD5 (128 bits) and '1' means SHA-1 (160 bits).

    session.hash_bits_per_character "4" allows you to dene how many bits are stored in each character when convereng the binary hash data to something readable. The possible values are '4' (0-9, a-f), '5' (0-9, a-v), and '6' (0-9, a-z, A-Z, "-", ",").

    url_rewriter.tags species which HTML tags are rewrien to include session id if transparent sid support is enabled. Defaults to a=href,area=href,frame=src,input=src,form=fakeentry,eldset= 38

  • Session V d : m s ln duyt trang web

    39

  • Session - ng dng cho Login

    Lm th no ngn khng cho ngi dng truy cp vo cc trang web nu cha ng nhp?

    tng Dng cc bin Session lu trng thi ng nhp ca ngi

    dng: $_SESSION["IsLogin"] = true/false : Lu trng thi ng nhp $_SESSION["Username"]: Lu Tn ng nhp $_SESSION["Authen0ca0on"]: Lu Loi quyn ng nhp

    40

  • Session - ng dng Login

    Login

    Page 1

    Page 2

    Page 3

    Page 4

    Session: + IsLogin + Username + Authenecaion Type

    41

  • Session - ng dng cho Login

    1.To trang login.htm yu cu ngi dng ng nhp.

    2. To trang xlLogin.php x l thng en ng nhp t trang login.htm Kt ni vi CSDL, kim tra thng en ng nhp c hp l hay

    khng ? Nu khng hp l th cho redirect v trang login.htm. Nu hp l th dng mt bin trong Session lu trng thi login

    thnh cng V d: $_SESSION["IsLogin"] = true. Lu : Phi t gi tr mc nh cho bin Session ny l false khi

    khi to mt Session (xem v d slide sau).

    3.To trang logout.php l trang x l khi ngi dng logout Reset trng thi login l cha ng nhp ($_SESSION["IsLogin"] = false).

    42

  • Session - ng dng cho Login

    4. Trong tt c cc trang mun bo mt, thm on m sau kim tra ngi dng ng nhp hay cha, nu cha th redirect li trang login.htm hoc trang thng bo li .

    5. Ngoi ra c th lu mt s thng en khc trong session: $_SESSION ["Username"], $_SESSION ["Usertype"]

  • Internet or Intranet

    Web Server

    Database Server

    Client 3

    Client 2

    Client 1

    Cookie3

    Cookie2

    Cookie1

    Session 2 Session 3

    Session 1

    Thng tin chia s V tr lu tr

    Thi gian tn ti

    S client S trang web s dng

    Database/File Server Di Nhiu Nhiu Session Server Ngn 1 Nhiu Cookies Client Di 1 Nhiu

    44

    So snh : Session Cookie Database

  • Ni dung

    K thut Upload File bng PHP S dng Cookie trong PHP S dng Session trong PHP K thut gi mail bng PHP

    45

  • C ch gi / nhn email

    Cc thnh phn: Mail client:

    My thc hin gi mail My nhn email

    Mail server: Thc hin vic gi email, lu gi email

    DNS Server: My phn gii tn min

    2 loi Mail client: Desktop based client Web based client

    46

  • C ch gi / nhn email

    Sender composes a message using Email client

    1

    2 Senders Email Client uploads messages to SMTP Server

    SMTP server uses DNS server to locate recipients domain

    3

    The message arives at receiving server and is placed in recipients mailbox >ile/folder

    5 Recipients Email Client checks mailbox for new messages and downloads messages. 6

    The message traverses Internet

    4

    SMTP Server

    SMTP / POP3/ IMAP Server 47

  • Cu hnh Email Client

    Gmail Yahoo Mail

    48

  • Web vs. Desktop based Mail Client

    49

  • K thut gi email

    Cc thng en cn thit: Thng en ngi gi Thng en ngi nhn Ni dung thng ip a ch mail server thc hin vic gi email

    Cc k thut ph bin: PHP mail() Non Authenecaeon PHP PEAR package SMTP Authenecaeon PHP Mailer SMTP Authenecaeon

    50

  • Mail server Mail Client

    Internet or Intranet

    Internet or Intranet

    Web Server

    mail(to,subject,message)

    K thut gi email

    51

  • S dng PHP mail ()

    S dng SMTP Server + hm th vin ca PHP mail(to, subject, message, headers, parameters)

    Trong :

    Key Species

    TO a ch email ngi nhn

    SUBJECT Tiu Email (KHNG c cha k t xung dng)

    MESSAGE Ni dung Email

    HEADERS Thng en thm (vd: FROM, BCC, CC,) Cc thng en ny nn phn cch nhau bng k t xung dng (\r\n)

    PARAMETERS Tham s cu hnh cho ng dng gi mail

    52

  • S dng PHP mail ()

    Cu hnh SMTP mc nh trong PHP (php.ini)

    Default ngha SMTP localhost DSN hoc IP Address ca SMTP Server smtp_port 25 Port ca SMTP sendmail_from NULL a ch ngi gi

    53

  • S dng PHP mail (): V d

  • Mt s mail server thng dng

    MS Exchange MDeamon hMailServer

    55

  • 1. S dng PEAR package Mail.php require_once(Mail.php);

    2. Khi to th hin gi mail s dng Mail::factory() $smtpMail = Mail::factory(smtp, $params);

    $params["host"] = "hostname"; $params["auth"] = true; $params["username"] = "smtp_username"; $params["password"] = "smtp_password";

    3. Gi mail s dng hm send() $mail = $smtpMail -->send($to, $headers, $message)

    $headers['From'] = '[email protected]'; $headers['To'] = $to; $headers['Subject'] = 'Test message'; $headers['Cc'] = '[email protected]'; $headers['Reply-To'] = '[email protected]';

    4. Kim tra li gi mail if (PEAR::isError($mail ))

    echo($mail ->getMessage()); 56

    S dng PEAR Package

  • 57

    S dng PEAR Package: V d

  • S dng PHPMailer Gmail server

    58

  • S dng PHPMailer Yahoo mail server

    59

  • V d: sendmail-phpmailer-simple.php

    60

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

  • V d: sendmail-phpmailer-simple.php

    61

  • Mt s v d v gi mail

    Gi mail kch hot ti khon

    Gi mail thng bo ng k ti khon thnh cng

    Gi mail ho n mua hng

    Gi mail thng bo khi c sn phm mi

    62

  • Gi mail ho n mua hng

    63