63
Chapter 4: State Chapter 4: State Management Management

Chapter 4: State Management. Training Course, CS, NCTU 2 Overview Introduction Transmitting data Keeping states Taking use of HTTP Headers Appendix:

  • View
    215

  • Download
    1

Embed Size (px)

Citation preview

Chapter 4: State ManagementChapter 4: State Management

Tra

inin

g C

ou

rse, C

S, N

CTU

2

OverviewOverview

Introduction Transmitting data Keeping states Taking use of HTTP Headers Appendix: HTTP

Tra

inin

g C

ou

rse, C

S, N

CTU

3

Introduction (1)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!

Tra

inin

g C

ou

rse, C

S, N

CTU

4

Introduction (2)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, …)

Tra

inin

g C

ou

rse, C

S, N

CTU

5

Transmitting Data (1)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

User Input Browser Web Server

PHP

Request

Response

Tra

inin

g C

ou

rse, C

S, N

CTU

6

Transmitting Data (2)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>

Tra

inin

g C

ou

rse, C

S, N

CTU

7

Transmitting Data (3)Transmitting Data (3)

• Format<form name=“formname” method=“GET|POST” action=“URL”>

<input type=…>

<select>

<option>… </option>

</select>

<textarea>…</textarea>

<input type=“submit” …>

</form>

• GET vs. POST: See Appendix GET is same as “URL support” in HTTP Transmission.

Tra

inin

g C

ou

rse, C

S, N

CTU

8

Transmitting Data (4)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>

Tra

inin

g C

ou

rse, C

S, N

CTU

9

Transmitting Data (5)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);

Tra

inin

g C

ou

rse, C

S, N

CTU

10

Transmitting Data (6)Transmitting Data (6)

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

<form name="4-1" method="GET" action="4-1.php"><input type="text" name="name"><input type="submit" value="Submit">

</form>

print_r($_GET);

<form name="4-1" method=“POST" action="4-1.php"><input type="text" name="name"><input type="submit" value="Submit">

</form>

print_r($_POST);

Array( [name] => chwong)

Array( [name] => chwong)

Tra

inin

g C

ou

rse, C

S, N

CTU

11

Transmitting Data (7)Transmitting Data (7)

• A lot of text <textarea name=“varname” rows=“value” cols=“value” wrap=“off|virtu

al|physical”>

• Example:…<form action="ex4-1_2.php"><textarea name="TEXT"></textarea><br><input type="submit" value="Send">…

<?php echo "Your text: ".$_GET["TEXT"];?>

Tra

inin

g C

ou

rse, C

S, N

CTU

12

Transmitting Data (8)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>…

Tra

inin

g C

ou

rse, C

S, N

CTU

13

Transmitting Data (9)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>"; }

}?>

Tra

inin

g C

ou

rse, C

S, N

CTU

14

Transmitting Data (10)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]";?>

Tra

inin

g C

ou

rse, C

S, N

CTU

15

Transmitting Data (11)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]";?>

Tra

inin

g C

ou

rse, C

S, N

CTU

16

Transmitting Data (12)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

Tra

inin

g C

ou

rse, C

S, N

CTU

17

Transmitting Data (13)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]”

Tra

inin

g C

ou

rse, C

S, N

CTU

18

Transmitting Data (14)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]";?>

Tra

inin

g C

ou

rse, C

S, N

CTU

19

Transmitting Data (15)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.

Tra

inin

g C

ou

rse, C

S, N

CTU

20

Transmitting Data (16)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>"; }?>

Tra

inin

g C

ou

rse, C

S, N

CTU

21

Transmitting Data (17)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>"; }?>

Tra

inin

g C

ou

rse, C

S, N

CTU

22

Transmitting Data (18)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>

Tra

inin

g C

ou

rse, C

S, N

CTU

23

Transmitting Data (19)Transmitting Data (19)

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

Tra

inin

g C

ou

rse, C

S, N

CTU

24

Transmitting Data (20)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

Tra

inin

g C

ou

rse, C

S, N

CTU

25

Keeping States (1)Keeping States (1)

Approaches• In memory. (gone with browser closed)

• Storing in client. cookie

• Storing in Server. session, file, database, …

Tra

inin

g C

ou

rse, C

S, N

CTU

26

Keeping States (2)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());

Tra

inin

g C

ou

rse, C

S, N

CTU

27

Keeping States (3)Keeping States (3)

• Getting contents in cookie Using the superglobal: _COOKIE

_COOKIE["name"];

Example

<?php //ex4-2_1b.php echo “My name is $_COOKIE[NAME].”;?>

<?php //ex4-2_1a.php setcookie("NAME", "ystseng"); echo $_COOKIE["NAME"];?>

Tra

inin

g C

ou

rse, C

S, N

CTU

28

Keeping States (4)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;?>

Tra

inin

g C

ou

rse, C

S, N

CTU

29

Keeping States (5)Keeping States (5)

• SetCookie function must be called before any output is sent to the browser.

• Example:

<?php echo "Setting cookie"; setcookie("NAME", "ystseng");?>

Tra

inin

g C

ou

rse, C

S, N

CTU

30

Keeping States (6)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));?>

Tra

inin

g C

ou

rse, C

S, N

CTU

31

Keeping States (7)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 preserved across requests.

Tra

inin

g C

ou

rse, C

S, N

CTU

32

Keeping States (8)Keeping States (8)

• Creating session storage in server-side. When a visitor accesses your site, PHP will check automatically value o

f “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

Tra

inin

g C

ou

rse, C

S, N

CTU

33

Keeping States (9)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].";?>

Tra

inin

g C

ou

rse, C

S, N

CTU

34

Keeping States (10)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 o

r 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].";?>

Tra

inin

g C

ou

rse, C

S, N

CTU

35

Keeping States (11)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]."; ?>

Tra

inin

g C

ou

rse, C

S, N

CTU

36

Keeping States (12)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]."; ?>

Tra

inin

g C

ou

rse, C

S, N

CTU

37

Keeping States (13)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));?>

Tra

inin

g C

ou

rse, C

S, N

CTU

38

Keeping States (14)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

Tra

inin

g C

ou

rse, C

S, N

CTU

39

Taking use of HTTP Headers (1)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.

Tra

inin

g C

ou

rse, C

S, N

CTU

40

Taking use of HTTP Headers (2)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.

Tra

inin

g C

ou

rse, C

S, N

CTU

41

Taking use of HTTP Headers (3)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”);

Tra

inin

g C

ou

rse, C

S, N

CTU

42

Taking use of HTTP Headers (4)Taking use of HTTP Headers (4)

Cache-Control:– The cache-control field will control browser how to operator the cache abo

ut this page.

– Ex:

» header(“Cache-control: no-cache”);

Tra

inin

g C

ou

rse, C

S, N

CTU

43

Taking use of HTTP Headers (5)Taking use of HTTP Headers (5)

PHP Superglobals• PHP provides a large number of predefined variables to any script w

hich it runs. • PHP provides an additional set of predefined arrays containing varia

bles 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.

Tra

inin

g C

ou

rse, C

S, N

CTU

44

Taking use of HTTP Headers (6)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"];?>

Tra

inin

g C

ou

rse, C

S, N

CTU

45

Taking use of HTTP Headers (7)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));?>

Tra

inin

g C

ou

rse, C

S, N

CTU

46

Taking use of HTTP Headers (8)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;

Tra

inin

g C

ou

rse, C

S, N

CTU

47

Taking use of HTTP Headers (9)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));?>

Tra

inin

g C

ou

rse, C

S, N

CTU

48

Taking use of HTTP Headers (10)Taking use of HTTP Headers (10)

$_FILES• An associative array of items uploaded to the current script via the H

TTP 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.

Tra

inin

g C

ou

rse, C

S, N

CTU

49

Taking use of HTTP Headers (11)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>

Tra

inin

g C

ou

rse, C

S, N

CTU

50

Taking use of HTTP Headers (12)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));?>

Tra

inin

g C

ou

rse, C

S, N

CTU

51

Taking use of HTTP Headers (13)Taking use of HTTP Headers (13)

• Re-writing last php page for uploaded file

<?php $file = "upload/".$_FILES["sendfile"]["name"]; if (move_uploaded_file($_FILES["sendfile"]["tmp_name"], $file)) echo "http://tphp.cs.nctu.edu.tw/tphp/$file";?>

Tra

inin

g C

ou

rse, C

S, N

CTU

52

Taking use of HTTP Headers (14)Taking use of HTTP Headers (14)

$_SERVER• _SERVER is an array containing information such as headers, paths,

and script locations.

• The entries in this array are created by the webserver.

• There is no guarantee that every webserver will provide any of these.

• You don't need to do a global $_SERVER;

• Useful elements in $_SERVER. PHP_SELF :

– The filename of the currently executing script, relative to the document root.

– Ex: http://tphp.cs.nctu.edu.tw/tphp/ex4-3_5.php, would be /tphp/ex4-3_5.php

– __FILE__ constant contains the full path and filename of the current file.

Tra

inin

g C

ou

rse, C

S, N

CTU

53

Taking use of HTTP Headers (15)Taking use of HTTP Headers (15)

SERVER_ADDR:– The IP address of the server under which the current script is executing.

SERVER_NAME:– The name of the server host under which the current script is executing. If

the script is running on a virtual host, this will be the value defined for that virtual host.

REQUEST_METHOD:– Which request method was used to access the page; i.e. 'GET', 'HEAD',

'POST', 'PUT'.

QUERY_STRING:– The query string, if any, via which the page was accessed.

DOCUMENT_ROOT:– The document root directory under which the current script is executing, as

defined in the server's configuration file.

Tra

inin

g C

ou

rse, C

S, N

CTU

54

Taking use of HTTP Headers (16)Taking use of HTTP Headers (16)

HTTP_REFERER:– The address of the page (if any) which referred the user agent to the current

page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.

HTTP_USER_AGENT:– Contents of the User-Agent: header from the current request, if there is one.

This is a string denoting the user agent being which is accessing the page.

– You can use this value with get_browser() to tailor your page's output to the capabilities of the user agent.

REMOTE_ADDR:– IP address from which the user is viewing the current page.

REMOTE_PORT:– The port being used on the user's machine to communicate with the web ser

ver.

Tra

inin

g C

ou

rse, C

S, N

CTU

55

Taking use of HTTP Headers (17)Taking use of HTTP Headers (17)

• Example:

<?php echo "You come from $_SERVER[REMOTE_ADDR] "; echo "and has browsing $_SERVER[SERVER_ADDR]";?>

Tra

inin

g C

ou

rse, C

S, N

CTU

56

Taking use of HTTP Headers (18)Taking use of HTTP Headers (18)

$_ENV• These variables are imported into PHP's global namespace from the

environment under which the PHP parser is running.

• Many are provided by the shell under which PHP is running.

• You don't need to do a global $_ENV;

• Example:<?php echo nl2br(print_r($_ENV, true));?>

Tra

inin

g C

ou

rse, C

S, N

CTU

57

Taking use of HTTP Headers (19)Taking use of HTTP Headers (19)

Practicing• Creating a PHP page to collect client-side information which you

want to know and storing it into session or cookie. Using another PHP page to show it on browser.

Tra

inin

g C

ou

rse, C

S, N

CTU

58

Q&AQ&A

Appendix: HTTPAppendix: HTTP

Tra

inin

g C

ou

rse, C

S, N

CTU

60

HTTP (1)HTTP (1)

HTTP: Hypertext Transfer Protocol• RFCs: (HTTP 1.1)

http://www.faqs.org/rfcs/rfc2068.html

http://www.faqs.org/rfcs/rfc2616.html (Updated Version)

• Useful Reference: http://jmarshall.com/easy/http/

• A network protocol used to deliver virtually all files and other data on the World Wide Web.

HTML files, image files, query results, or anything else.

• Client-Server Architecture A browser is an HTTP client because it sends requests to an HTTP serv

er (Web server), which then sends responses back to the client.

Tra

inin

g C

ou

rse, C

S, N

CTU

61

HTTP (2)HTTP (2)

• Clients: Send Requests to Servers Action “path or URL” Protocal

– Actions: GET, POST, HEAD

– Ex. GET /index.php HTTP/1.1

Headers– Header_Name: value

– Ex.

From: [email protected]

(blank line) Data …

• Servers: Respond to the clinets Status:

– 200: OK

– 404: Not Found

– …

– Ex. HTTP/1.1 200 OK

Headers– Same as clients

– Ex.

Content-Type: text/html

(blank line) Data…

Tra

inin

g C

ou

rse, C

S, N

CTU

62

Get vs. PostGet vs. Post

Get vs. Post (client side)• Get:

Parameters in URLGET http://tphp.cs.nctu.edu.tw/get.php?a=1&b=3 HTTP/1.1

No data content Corresponding in HTML files

– Link URL: http://tphp.cs.nctu.edu.tw/get.php?a=1&b=3– Using Form:

<form method=“GET” action=“get.php”> … </form>

• Post: Parameters in Data Content

POST http://tphp.cs.nctu.edu.tw/post.php HTTP/1.1 Corresponding in HTML files

– Using Form:

<form method=“POST” action=“post.php”> … </form>

Tra

inin

g C

ou

rse, C

S, N

CTU

63

HTTP HeadersHTTP Headers

What HTTP Headers can do?[Ref] http://www.cs.tut.fi/~jkorpela/http.html

• Content information (type, date, size, encoding, …)

• Cache control

• Authentication

• URL Redirection

• Transmitting cookies

• Knowing where client come from

• Knowing what software client use

• …