1 / 63

Chapter 4: State Management

Chapter 4: State Management. Overview. Introduction Transmitting data Keeping states Taking use of HTTP Headers Appendix: HTTP. Introduction (1). Static web pages vs. dynamic web pages Static web pages Static web pages are seldom changed after it first created.

annick
Download Presentation

Chapter 4: State Management

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 4: State Management

  2. Overview • Introduction • Transmitting data • Keeping states • Taking use of HTTP Headers • Appendix: HTTP

  3. Introduction (1) • Static web pages vs. dynamic web pages • Static web pages • Static web pages are seldom changed after it first created. • Suitable for some data that never changes. • Ex. manuals, specs, pictures, movies… • Benefit: easy to cache, good performance. • Problem: information shown may be not so suitable for everybody. • Dynamic web pages • Dynamic web pages usually changes with • who, where, when, … • Suitable for showing some personal info. • Ex. phone bills, news, current weather, selling tickets, … • Benefit: VIP Service for everyone • Problem: hard to cache, higher server hardware cost. • To balance it is more important!

  4. Introduction (2) • State Management • Dynamic web pages have to keep in touch with users. • Functions required: • Transmitting data from client to server. • How to make clients transmit data • How to get data transmitted by client • Keeping states. • In memory. (gone with browser closed) • Storing in client. (cookie) • Storing in Server. (session, file, database, …)

  5. Request Web Server User Input Browser Response PHP Transmitting Data (1) • Two important issues • To make clients transmit data • URL Support • HTML Support • To get data transmitted by client • Predefined Super-global variables in PHP. • Flow

  6. Transmitting Data (2) • URL Support • Attach name&value at the end of url http://host/filepath?name1=value1&var2=value2&var3=value3… • Ex. http://tphp.cs.nctu.edu.tw/my.php?name=chwong&age=25 • HTML Support • Adding html tags to support it. • Defining where data will be transmitted to. • <form> … </form> • For putting data. • <intput type=…> • <select>…</select> • <option>…</option> • <textarea>… <textarea>

  7. Transmitting Data (3) • Format <formname=“formname” method=“GET|POST” action=“URL”> <inputtype=…> <select> <option>… </option> </select> <textarea>…</textarea> <input type=“submit” …> </form> • GET vs. POST: See Appendix • GET is same as “URL support” in HTTP Transmission.

  8. Transmitting Data (4) • Example <html><head><title>Form HTML code</title></head> <body> <form method="post" action="ex4-1.php"> Name: <input type="text" name="NAME”><br> Social ID: <input type="password" name="SID" maxlength="10"><br> Gender: <input type="radio" name="GENDER“ value=“Gentleman checked>Gentleman <input type="radio" name="GENDER“ value=“lady”>Lady<br> Occupation: <select name="JOB"> <option value="1">Student</option> <option value="2">SOHO</option> <option value="3">Theater</option> <option value="4">Police</option> <option value="5">Others</option> </select><br> Introduction yourself: <textarea name="INTRO"></textarea><p> <input type="submit" value=“Send"> <input type="reset" value=“Reset"> </form></body></html>

  9. Transmitting Data (5) • Predefined Super-global variables in PHP. • Two variables are useful here • _GET, _POST $_GET[“varname”], $_POST[“varname”] Note: varname should be the same you write in html • Example http://tphp.cs.nctu.edu.tw/4-1.php?name=chwong Array ( [name] => chwong ) print_r($_GET);

  10. Transmitting Data (6) <form name="4-1" method="GET" action="4-1.php"> <input type="text" name="name"> <input type="submit" value="Submit"> </form> • Difference • URL after click “Submit” button GET: http://tphp.cs.nctu.edu.tw/4-1.php?name=chwong POST: http://tphp.cs.nctu.edu.tw/4-1.php Array ( [name] => chwong ) print_r($_GET); <form name="4-1" method=“POST" action="4-1.php"> <input type="text" name="name"> <input type="submit" value="Submit"> </form> Array ( [name] => chwong ) print_r($_POST);

  11. Transmitting Data (7) • A lot of text • <textarea name=“varname” rows=“value” cols=“value” wrap=“off|virtual|physical”> • Example: … <form action="ex4-1_2.php"> <textarea name="TEXT"> </textarea><br> <input type="submit" value="Send"> … <?php echo "Your text: ".$_GET["TEXT"]; ?>

  12. Transmitting Data (8) • Check box • <input name=“varname” type=“checkbox” checked value=“input_value”> • Select button • <input name=“varname” type=“radio” checked value=“input_value”> • Example: <form action="ex4-1_3.php"> <input type="radio" name="gender" value="boy" checked>Boy <input type="radio" name="gender" value="girl">Girl<p> <input type="checkbox" name="Lang1" value="C/C++">C/C++ <input type="checkbox" name="Lang2" value="PHP" checked>PHP <input type="checkbox" name="Lang3" value="HTML">HTML<p> <input type="submit" value="Send"> </form> …

  13. Transmitting Data (9) <?php echo "Your gender: ".$_GET["gender"]."<p>"; echo "Language: <br>"; for ($i = 1; $i <= 3; $i++) { if ( !is_null ($_GET["Lang$i"]) ) { echo $_GET["Lang$i"], "<br>"; } } ?>

  14. Transmitting Data (10) • Selection From Lists <select name=“varname” multiple size=“list_size”> <option value=“intput_value”>Text1</option> <option value=“intput_value” checked>Text2</option> </select> • Example: <form action="ex4-1_4.php"> <select name="Lang"> <option value="C/C++">C/C++</option> <option value="HTML">HTML</option> <option value="Perl">Perl</option> <option value="PHP">PHP</option> </select> <input type="submit" value="Send"> </form> <?php echo "Language: $_GET[Lang]"; ?>

  15. Transmitting Data (11) • Hidden Data • <input name=“varname” type=“hidden” value=“input_value”> <form action="ex4-1_4.php"> Hello. Do you want to see secret? Just send it. <input type="hidden" name="HiddenKey" value="hahaha"> <input type="submit" value="Send"> </form> <?php echo "Language: $_GET[HiddenKey]"; ?>

  16. Transmitting Data (12) • Practicing • Creating a simple member register page, and using <form>, <input>, <select> to collection personal information you want to know. • Creating a dynamic page to take over above information and display it on your browser • http://tphp.cs.nctu.edu.tw/tphp/pr4-1_1.html • http://tphp.cs.nctu.edu.tw/tphp/pr4-1_1.txt • http://tphp.cs.nctu.edu.tw/tphp/pr4-1_1php.php • http://tphp.cs.nctu.edu.tw/tphp/pr4-1_1php.txt

  17. Transmitting Data (13) • Auto-creating array variables in PHP from GET or POST. • PHP also understands arrays in the context of form variables. • You may group related variables together , or use this feature to retrieve values from a multiple select input. • In PHP 3, the array form variable usage is limited to single-dimensional arrays. As of PHP 4, no such restriction applies. • Association array format at HTML • name=“variable[association_name]” • Index array format at HTML • name=“variable[]” • 2-dim array at HTML • name=“variable[x][y]”

  18. Transmitting Data (14) • Re-writing example at page14 using multiple select box: • It gets incorrect information. <form action="ex4-1_4.php"> <select name="Lang" multiple size="5"> <option value="C/C++">C/C++</option> <option value="HTML">HTML</option> <option value="Perl">Perl</option> <option value="PHP">PHP</option> </select> <input type="submit" value="Send"> </form> <?php echo "Language: $_GET[Lang]"; ?>

  19. Transmitting Data (15) • If the HTML form has used the same key name, in php, the superglobal “_POST” or “_GET” will replace the last value of the same key name. • Must use array variables to solve this problem.

  20. Transmitting Data (16) • Re-writing example of last page using index array variable. <form action="ex4-1_4.php"> <select name="Lang[]" multiple size="5"> <option value="C/C++">C/C++</option> <option value="HTML">HTML</option> <option value="Perl">Perl</option> <option value="PHP">PHP</option> </select> <input type="submit" value="Send"> </form> <?php echo "Language: <br>"; foreach ($_GET["Lang"] as $val) { echo "$val<br>"; } ?>

  21. Transmitting Data (17) • Re-writing example at page 12 using index array variables <form action="ex4-1_3.php"> <input type="checkbox" name="Lang[]" value="C/C++">C/C++ <input type="checkbox" name="Lang[]" value="PHP" checked>PHP <input type="checkbox" name="Lang[]" value="HTML">HTML<p> <input type="submit" value="Send"> </form> … <?php echo "Language: <br>"; foreach ($_GET["Lang"] as $val) { echo "$val<br>"; } ?>

  22. Transmitting Data (18) • Example with using 2-dem index array. <form action="ex4-1_6.php"> Name: <input type="text" name="Person[0][Name]"><br> Gender: <input type="text" name="Person[0][Gender]"><br> Age: <input type="text" name="Person[0][Age]"><p> Name: <input type="text" name="Person[1][Name]"><br> Gender: <input type="text" name="Person[1][Gender]"><br> Age: <input type="text" name="Person[1][Age]"><p> Name: <input type="text" name="Person[2][Name]"><br> Gender: <input type="text" name="Person[2][Gender]"><br> Age: <input type="text" name="Person[2][Age]"><p> <input type="submit" value="Send"> </form>

  23. Transmitting Data (19) <?php foreach ($_GET["Person"] as $data) { echo "Name: $data[Name]<br>"; echo "Gender: $data[Gender]<br>"; echo "Age: $data[Age]<p>"; } ?>

  24. Transmitting Data (20) • Practicing • Using PHP loop to produce a HTML page which can be inputted 5 record of personal information, creating another PHP page to take over those information, and showing it on browser. • http://tphp.cs.nctu.edu.tw/tphp/pr4-1_2a.php • http://tphp.cs.nctu.edu.tw/tphp/pr4-1_2a.txt • http://tphp.cs.nctu.edu.tw/tphp/pr4-1_2b.php • http://tphp.cs.nctu.edu.tw/tphp/pr4-1_2b.txt

  25. Keeping States (1) • Approaches • In memory. (gone with browser closed) • Storing in client. • cookie • Storing in Server. • session, file, database, …

  26. Keeping States (2) • Cookie • Little size files stores in client side, transmitted in HTTP Headers. • Using cookie in PHP • Adding cookie • Syntax setcookie (name[, value[, expire[, path[, domain[, secure[, httponly]]]]]]); • The first three parameters are most often used. • Name – cookie name • Value – cookie content • Expire – the time cookie expires • Note: Do not store sensitive information. • How to make expire time? • This is a Unix timestamp so is in number of seconds since the epoch (January 1 1970 00:00:00 GMT) . • Useful function: strtotime() • Ex. strtotime(“+10 days”, time());

  27. Keeping States (3) • Getting contents in cookie • Using the superglobal: _COOKIE _COOKIE["name"]; • Example <?php //ex4-2_1a.php setcookie("NAME", "ystseng"); echo $_COOKIE["NAME"]; ?> <?php //ex4-2_1b.php echo “My name is $_COOKIE[NAME].”; ?>

  28. Keeping States (4) • Removing cookie • Method1: Setting a past time to the expire time. • Ex. setcookie("name", "", time()-3600); this will set expire time to 1 hours before • Method2: Assigning an empty string to cookie. • Example • http://tphp.cs.nctu.edu.tw/tphp/ex4-2_2.php <?php if ($_COOKIE[“COUNT"] === null) { setcookie("COUNT", "1"); $count = 1; } else { $count = $_COOKIE["COUNT"] + 1; setcookie("COUNT", $count == 5 ? "" : $count); } echo "Counter: ".$count; ?>

  29. Keeping States (5) • SetCookie function must be called before any output is sent to the browser. • Example: <?php echo "Setting cookie"; setcookie("NAME", "ystseng"); ?>

  30. Keeping States (6) • Cookie data is then available in the appropriate cookie data arrays. • Example: <?php setcookie("NAME[0]", "ystseng"); setcookie("NAME[1]", "chwong"); setcookie("NAME[2]", "manic"); echo nl2br(print_r($_COOKIE["NAME"], true)); ?>

  31. Keeping States (7) • Session • Something like cookie, but stores in the server-side. • A visitor accessing your web site is assigned a unique id, the so-called session id. • This is either stored in a cookie on the user side or is propagated in the URL. • The session support allows you to register arbitrary numbers of variables to be preservedacross requests.

  32. Keeping States (8) • Creating session storage in server-side. • When a visitor accesses your site, PHP will check automatically value of “session.auto_start” in php.ini. • If session.auto_start is set to 1, it will auto create a session storage. • Other way, explicitly through session_start() or implicitly through session_register() • If a specific session id has been sent with the request, the prior saved environment is recreated. • Adding session • Syntax session_register("varname1", "varname2", …) • It can register one or more global variables with the current session $_SESSION["varname"] = value; • Using superglobal “_SESSION” to assign value

  33. Keeping States (9) • Getting contents in session • Using the superglobal: _SESSION _SESSION["name"]; • Example <?php //ex4-2_5.php session_start(); session_register("NAME"); $_SESSION["NAME"] = "ystseng"; echo "My name is $_SESSION[NAME]."; ?>

  34. Keeping States (10) • Removing session • Default is until the browser is closed. (You can set this value in php.ini) • You can un-register specified global variable from the current session or destory current session storage. • session_unregister("varname"); or $_SESSION["vername"] = ""; • Unregister a global variable from the current session. • session_destroy(); • Destroys all data registered to a session. • Ex: <?php //ex4-2_6.php session_unregister("NAME"); echo "My name is $_SESSION[NAME]."; ?>

  35. Keeping States (11) • Ex: <?php //ex4-2_7a.php session_start(); session_register("NAME"); session_register("AGE"); $_SESSION["NAME"] = "Peter"; $_SESSION["AGE"] = "18"; echo "My name is $_SESSION[NAME].<br>"; echo "My age is $_SESSION[AGE]."; ?>

  36. Keeping States (12) <?php //ex4-2_7b.php session_start(); session_destroy(); echo "My name is $_SESSION[NAME].<br>"; echo "My age is $_SESSION[AGE]."; ?>

  37. Keeping States (13) • Session still support array variable, but the statement is different with cookie. • Example: <?php session_register("NAME"); $_SESSION["NAME"][0] = "Peter"; $_SESSION["NAME"][1] = "Bill"; echo nl2br(print_r($_SESSION["NAME"], true)); ?>

  38. Keeping States (14) • Practicing • Using last dynamic html page of last practicing at page 24, and storing all information data into cookie. Producing another PHP page to fetch all information data from cookie. • Using last dynamic html page of last practicing at page 24, and storing all information data into session. Producing another PHP page to fetch all information data from session. • http://tphp.cs.nctu.edu.tw/tphp/pr4-2_1a.php • http://tphp.cs.nctu.edu.tw/tphp/pr4-2_1a.txt • http://tphp.cs.nctu.edu.tw/tphp/pr4-2_1b.php • http://tphp.cs.nctu.edu.tw/tphp/pr4-2_1b.txt • http://tphp.cs.nctu.edu.tw/tphp/pr4-2_1c.php • http://tphp.cs.nctu.edu.tw/tphp/pr4-2_1c.txt

  39. Taking use of HTTP Headers (1) • HTTP header • HTTP header is another method of transmitting data. • Ex: CGI parameter, browser parameter of client-side…etc. • Actually, session id, cookies, and GET method are be transmitted by HTTP header. • Key and value of “GET” is written in URL, but URL data will be transmitted by HTTP request. Hence, It still be sent by header. • In HTTP spec, A HTTP request or reply are split two part. One is header, the other is body (content). Header must be transmitted first, then back-to-back body (content). • Therefore, session_start() and setcookie(), header() function must write before all content data.

  40. Taking use of HTTP Headers (2) • If you want to add other header in HTTP header block, you can use header() this function to done this job. • header() • Send a raw HTTP header • Syntax header(string, [, replace [, http_response_code]]) • string: raw header data • replace: indicates whether the header should replace a previous similar header, or add a second header of the same type, By default it will replace. • http_response_code: force the HTTP response code to the specified value.

  41. Taking use of HTTP Headers (3) • Useful header string • Location: • The Location response-header field is used to redirect the recipient to a location. • Ex: • header(“Location: http://tw.yahoo.com/”); • Content-type: • Specified output file will be which mime file type • Ex: • header(“Content-type: application/pdf”); • header(“Content-type: text/plain”);

  42. Taking use of HTTP Headers (4) • Cache-Control: • The cache-control field will control browser how to operator the cache about this page. • Ex: • header(“Cache-control: no-cache”);

  43. Taking use of HTTP Headers (5) • PHP Superglobals • PHP provides a large number of predefined variables to any script which it runs. • PHP provides an additional set of predefined arrays containing variables from the web server (if applicable), the environment, and user input. • There is no mechanism in PHP for user-defined superglobals. Many of these variables, however, cannot be fully documented as they are dependent upon which server is running, the version and setup of the server, and other factors. • Some of these variables will not be available when PHP is run on the command line. • Superglobals cannot be used as variable variables inside functions or class methods.

  44. Taking use of HTTP Headers (6) • $GLOBALS • Contains a reference to every variable which is currently available within the global scope of the script. • The variable names are the keys of the array. • You don't need to do a global $GLOBALS; • Example: <?php function counter() { $count = 100; } counter(); $name = "Peter"; echo $GLOBALS["name"]; echo $GLOBALS["count"]; ?>

  45. Taking use of HTTP Headers (7) • $_GET & $_POST • An associative array of variables passed to the current script via the HTTP GET/POST method. Automatically global in any scope. • You don't need to do a global $_GET or $_POST; • Example: <?php //ex4-3_2.php?NAME1=Peter&NAME2=Mary&NAME3=Martin echo nl2br(print_r($_GET, true)); ?>

  46. Taking use of HTTP Headers (8) • $_COOKIE • An associative array of variables passed to the current script via HTTP cookies. Automatically global in any scope. • You don't need to do a global $_COOKIE; • $_SESSION • An associative array containing session variables available to the current script. • You don't need to do a global $_SESSION;

  47. Taking use of HTTP Headers (9) • $_REQUEST • An associative array consisting of the contents of $_GET, $_POST, and $_COOKIE. • You don't need to do a global $_REQUEST; • Example: <?php //ex4-3_2.php?NAME1=Peter&NAME2=Mary&NAME3=Martin echo nl2br(print_r($_REQUEST, true)); ?>

  48. Taking use of HTTP Headers (10) • $_FILES • An associative array of items uploaded to the current script via the HTTP POST method. Automatically global in any scope. • You don't need to do a global $_FILES; • “upload_max_filesize” configuration parameter in php.ini. Setting maximum allowed size for uploaded files.

  49. Taking use of HTTP Headers (11) • Example: • HTML <form enctype="multipart/form-data" action="ex4-3_4php.php" method="post"> Send this file: <input name="sendfile" type="file"> <input type="submit" value="Upload"> </form>

  50. Taking use of HTTP Headers (12) • PHP • move_uploaded_file • Moves an uploaded file to a new location • Syntax move_uploaded_file(src_file, dst_file); • Destination location must be able to write by everyone. <?php echo nl2br(print_r($_FILES, true)); ?>

More Related