Left overs HTML forms GET and POST More about the HTML protocol

Transcription

Left overs HTML forms GET and POST More about the HTML protocol
Left overs
HTML forms
GET and POST
More about the HTML protocol
The <iframe> tag
• The <frameset> tag is NOT supported in HTML5! Showing 3 pages
in one web page
• The <iframe> tag specifies an inline frame
<frameset cols="25%,*,25%">
<frame src="frame_a.htm">
– An inline frame is used to embed another
<frame src="frame_b.htm">
<frame src="frame_c.htm">
document within the current HTML
</frameset>
document
– <iframe src="http://www.w3schools.com"></iframe>
• Use CSS to style the <iframe> (even to include scrollbars)
<html>
<head>
<title>iframe test</title>
</head>
<body>
<!-- the iframe page is embedded in the host page which is a rather common technique
on blogs, exercise/training and other social media sites -->
<iframe width='100%' height='400' frameborder='0'
src='http://hjoduse.cartodb.com/viz/79b0be82-4b14-11e3-adad-8371673a050e/
embed_map?title=true&description=true&search=false&shareable=false&cartodb_logo=true&
layer_selector=true&legends=true&scrollwheel=true&sublayer_options=1&sql=&zoom=2&
center_lat=56.26776108757582&center_lon=13.18359375'></iframe>
</body>
</html>
PHP classes and include
• Using classes are rather simple and works as in Java, C#, C++ etc.
• Include your include files (files with shared code) with the include or
include_once statement
<?php
# Include class file or any other php file
include_once "position.php";
# local lat and long
$lat = '';
$lng = '';
# file position.php
<?php
class Position
{
#var string
public $latitude;
public $longitude;
function __construct($latitude="", $longitude=""){
if(!empty($latitude))
$this->latitude($latitude);
if(!empty($longitude))
$this->longitude($longitude);
}
public function setPosition($latitude="",
$longitude="") {
if(!empty($latitude))
$this->latitude($latitude);
if(!empty($longitude))
$this->longitude($longitude);
}
public function getLatitude() {
return $this->latitude;
}
public function getLongitude() {
return $this->longitude;
}
# create the position object
$pos = new Position("60.45678", "15.45678");
# if we have public members we can do like this
$lat = $pos->latitude;
$lng = $pos->longitude;
# do something with the local variables
$lat = $lat - 0.1;
$lng = $lng + 0.1;
# if the members have been private we need a set method
$pos->setPosition($lat, $lng);
# if the members have been private we need get methods
$lat = $pos->getLatitude();
$lng = $pos->getLongitude();
#...
?>
}
?>
The local function scope
• Unlike JavaScript and most other program languages global
scope defined variables are not seen inside local functions
<?php
include "utils.php";
$a = 1; // global scope
$b = 2;
/* Global scope variables as the $a and $b variables and similar
the included utils.php will be available within the local script
However, within user-defined functions a local function scope is
Any variable used inside a function is by default limited to the
function test() {
echo $a; /* reference to local scope variable */
}
test(); // will not produce any output!
variables and functions in
file.
introduced.
local function scope. */
/* In PHP global variables must be declared global inside a function if they are going to be used in
that function. Otherwise use the $GLOBALS array or send/return variables to/from the function */
function sum() {
global $a, $b; // equivalent to
$b = $a + $b;
// using: $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}
sum();
// receiving function parameters
echo $b; // will output 3
function sum($a, $b){
?>
return $a + $b; //returning the result
}
echo sum($a, $b); // sending function arguments
Debug variables
• Syntax errors
– A syntax error in a PHP file will normally prevent the entire
program from running, Parse error: in xyz on line #
– Usually turned off to prevent clues about the application
• Coding errors
– Your best friend is the echo statement or functions as
var_dump()
– Configure server debugging and get it working
• Dumping local variables
# debug example
echo "XYZ = " . $room[1], "<br>";
exit();
<?php
echo "<html>";
echo "<body>";
$rooms[1] = "ABC";
$rooms[2] = "DEF";
$rooms[3] = "GHI";
echo "<pre>";
var_dump($rooms);
echo "</pre>";
echo "</body>";
echo "</html>";
?>
HTML Forms 1
• Forms are user interfaces for data input
• Main application - to provide user input for
– Programs and databases located on a web server
– Local (client-side) scripts associated with the form
• Server-based scripts/programs may return data to the
client as a web page
• Client-side scripts can read input data
– To validate the data, prior to sending to server
– To use in local processing which may output web page content
that is displayed on the client
• Examples
– Questionnaires to provide feedback on a web site
– E-commerce, to enter name, address, details of purchase and
credit-card number
– Run a database query and receive results
HTML Forms 2
• There are two ways of sending information into a
PHP program
– One is to use parameters on the URL, and retrieve them
with $_GET in PHP (in the form you set: method=”get”)
• Just as we did earlier with REST (hyperlinks) but the form
create the URL with parameters
– The other method, which is more powerful and secure is to
use a form with $_POST in PHP (in the form you set:
method=”post”)
• The data goes within the HTTP message body (not visible on
the browsers address field)
• To see (debug) what you send set: method=”get”
• There is a variety of form field types that you can
use, depending on the type of information that you're
requesting from a visitor
HTML Forms 3
• A form consists of
two main
components
– First, one or more
input fields into
which the visitor
types or clicks the
information you
have requested
– Second, a "submit"
button which, when
clicked, sends the
contents of the form
to a server-side
program for
processing in
whatever way it
wishes
Example form (post)
• Having designed a form, there are 3 more things you need to
do before it's ready for use
– Ensure that each form object is named properly
– Add an "action" to the <form> tag which is the server program
that processes the data
– Write some PHP code to handle the submitted forms
• When the site visitor presses the Submit button, the contents
of the form will be sent to a PHP program as a series of
variables (with values if they are used in the form)
• The names of those variables will be the names that you
have assigned to the objects in the form
<form method="post" action="breakfast.php">
<label>Name: </label> <input type="text" name="tb_name" size="40" />
<label>Bacon: </label> <input type="checkbox" name="cb_bacon" value="Y" />
<label>Boiled: </label> <input checked type="radio" name="rb_eggs" value="F" />
<label>Order your breakfast?</label> <input type="submit" value="Submit" />
</form>
The HTTP protocol


TCP/IP based request/response protocol
HTTP requests (known as methods)
– GET or POST

HTTP response
– In all cases a
resonse code
– will be returned

HTTP message
– Request/response
line - the http
method/status
– Header variables request metadata
– Message body content of message
GET and POST difference?
• The difference between METHOD="GET" (the default) and
METHOD="POST" is primarily defined in terms of form data encoding.
• The official recommendations say that "GET" should be used if and only if the
form processing is idempotent, which typically means a pure query form (we
do not change the back end data). Generally it is advisable to do so.
– There are, however, problems related to long URLs and non-ASCII
character repertoires which can make it necessary to use "POST" even
for idempotent processing.
• The HTML specifications technically define the difference between "GET" and
"POST" so that former means that form data is to be encoded (by a browser)
into a URL while the latter means that the form data is to appear within a
message body.
– But the specifications also give the usage recommendation that the
"GET" method should be used when the form processing is
"idempotent", and in those cases only.
• As a simplification, we might say that "GET" is basically for just getting
(retrieving) data whereas "POST" may involve anything, like storing or
updating data, ordering a product or sending E-mail.
Debug globals and server variables
• The $_SERVER
– Dumps out a tremendous amout of variables
– To long to list here
• Some useful examples
– get_defined_vars()
# dump server variables
echo "<pre>";
var_dump($_SERVER);
echo "</pre>";
echo "<pre>";
echo $_SERVER["REQUEST_URI"];
echo "</pre>";
# dump global variables
# and all other possible
# variables the the program
# knows about
echo "<pre>";
var_dump(get_defined_vars());
echo "</pre>";
["REQUEST_URI"]=>
string(16) "/myhome/test.php"
# not alls web servers pass this variable on
if (isset($_SERVER["HTTP_REFERER"])) {
echo "You came from ", $_SERVER["HTTP_REFERER"];
}
Debug POST form input 1
• Using get_defined_vars() - showing the empty() vs. isset() function
<form action="next.php" method="post">
<table>
<tr>
<td>Paul</td>
<td>Attuck</td>
<td>[email protected]</td>
<td><input checked type="checkbox"
name="cb_1" value="[email protected]" /></td>
</tr>
<tr>
<td>James</td>
<td>Bond</td>
<td>[email protected]</td>
<td><input type="checkbox"
name="cb_2" value="[email protected]" /></td>
</tr>
<tr>
<td>Name</td>
<td>Last</td>
<td>[email protected]</td>
<td><input type="checkbox"
name="cb_3" value="[email protected]" /></td>
</tr>
</table>
<input type="submit" name="submit" value="submit" />
</form>
Debug POST form input 2
• Using get_defined_vars() - showing the empty() vs. isset() function
<?php
echo "<pre>";
var_dump(get_defined_vars());
echo "</pre>";
for($i=1; $i <=3; $i++) {
$var = $_POST["cb_{$i}"];
//$var = FALSE;
//$var = 0;
# empty — Determine whether a variable is empty
# A variable is considered empty if it does
# not exist or if its value equals FALSE
// Evaluates to true if $var is empty
if (empty($var)) {
echo 'empty(): $var is either 0, empty,
or not set at all <br>';
}
// Evaluates as true if $var is set in any way
if (isset($var)) {
echo 'isset(): $var is set <br>';
}
}
?>
Form attributes
• The Global HTML attributes can also be used with the <form> tag
http://www.w3schools.com/tags/ref_standardattributes.asp
<input> element types
and other UI elements
•
•
•
•
•
•
•
•
•
•
•
•
text
checkbox
radio (buttons)
select (element with
options)
textarea (element)
password
button and button
(element)
submit
reset
hidden
file
image
All <input> element types
http://www.w3schools.com/tags/att_input_type.asp
• The new ones are HTML5 specific
• We will talk more about them later
Input element: type="text"
• The type attribute specifies the
type of user input
• The name attribute gives an
identifier to the input data
• The size attribute specifies the
length of the input field
• The value attribute specifies an
initial value for the text (optional)
<form method="post" action="comments.php">
<h2>Tell us what you think</h2>
Name <input name="name" type="text" size="20"><br>
Address <input name="address" type="text" size="30">
</form>
Input element: type="checkbox"
• Several checkboxes can be
selected
• The name attribute gives an
identifier to the input data
• The value attribute identifies
the value
• If the checked attribute is set
the box is initially checked
How did you hear about this web site?<br>
A friend
<input checked type="checkbox" name="cb_1" value="A friend"><br>
Search engine
<input type="checkbox" name="cb_2" value="Search engine"><br>
<!– etc ... -->
Input element: type="radio"
• Radio buttons are similar to
checkboxes, but only one can
be selected in a set/group
• The name attribute is used to
define a set/group of radio
buttons
• To select a radio button by
default, use the checked
attribute (for one button only)
How did you hear about this web site?<br>
A friend
<input checked type="radio" name="howdid" value="friend"><br>
Search engine
<input type="radio" name="howdid" value="engine"><br>
<!– etc -->
Input element: type="button"
• The name attribute uniquely
identifies a button
• The value attribute gives a
label to the button
• Actions can be associated with
buttons - more later when we
deal with client-side javascript
• onclick="JavaScriptCode"
onsubmit="JavaScriptCode"
Do you want to receive any further information:<br>
<input type="button" name="yes" value="Yes">
<input type="button" name="no" value="No"><br>
Input element: type="submit/reset"
• type="submit"
– clicking this button sends the
form data to the program (URL)
specified in the action
attribute of the form
– The enter keyboard key can
send form if form is in focus
• type="reset"
– clicking this button clears all
data entered so far
<form method="post" action="file.php">
<!– etc -->
Thank you<br>
<input type="submit" name="send" value="Send">
<input type="reset" name="clear" value="Clear"><br>
</form>
Input element: type="image"
• type="image"
– The image input tag uses an image as an input field.
– The image can be used as a submit button (with some
javascript code to submit the form when clicked) or to
collect data from the image itself (similar to an image
map, but in a form).
– The browser will submit the coordinates where the
user clicked on the image.
– It is usually better to use the <button> element (see
later)
<input type="image" src="b2.gif">
<input type="image" src="b2.gif" onsubmit="submit-form();">
<input type="image" src="b2.gif" onclick="alert('peekaboo');">
<!– will deliver the img_x and img_y for the image -->
<input type="image" src="b2.gif" name="img" value="submit">
Input element:
type="file/password/hidden"
• type="password"
– similar to type="text" except that the input is
echoed with asterisks (so not visible)
• type="file"
– provides a file dialogue box to specify a file which can
be sent to the server
• type="hidden"
– similar to text input, but the value attribute is used to
specify data that is to be sent to the server. Nothing
appears on the screen.
– The data might be set by a server program to keep
track of the details of a particular transaction.
The textarea element
• Used for multi-line text input
• Can hold an unlimited number
of characters
• The size of the input area is
specified with the cols and
rows attributes
• Any text placed inside the
element appears in the input
area (this can be deleted).
The textarea element
have many new
HTML5 attributes
Please write your comments:<br>
<textarea name="comments" rows="5" cols="20">
put text here
</textarea>
The select/option element
• The select element provides a
menu of options
• An option can be selected by
default using the selected
attribute (otherwise the first in the
list is initially selected)
●
The optgroup element is similar to
option (the *Cars, not selectable)
How do you rate this site?<br>
<select name="rating">
<option>Good</option>
<option selected>Bad</option>
<option>Ugly</option>
</select>
The button element
• The button tag defines a
versatile button element
• Inside a <button> element you can
put content, like text or images
• This is the difference between this element and buttons
created with the <input> element
• The button element have many new HTML5 attributes
Do you want to receive any further information:<br>
<button type="submit" name="yes" value="clicked">Yes</button>
<button type="submit" name="no" value="clicked">No</button>
<button type="submit" name="button1" value="clicked">
Submit Now<br/>
<img src="b2.gif" width="32" height="32" alt="submit" border="0" />
</button>
The global id attribute
• All Global HTML attributes
– http://www.w3schools.com/tags/ref_standardattributes.asp
• The id attribute specifies a unique id for an HTML element (the
value must be unique within the HTML document)
• Use the id attribute to manipulate text with JavaScript
<html>
<head>
<script>
function displayResult() {
document.getElementById("myHeader").innerHTML="Have a nice day!";
}
</script>
</head>
<body>
<h1 id="myHeader">Hello World!</h1>
<button onclick="displayResult()">Change text</button>
</body>
</html>
HTML Forms and result
breakfast.php
<?php
echo "<link href='style2.css' rel='stylesheet'>";
# in <head>
function checkbox_value($name) {
return (isset($_POST[$name]) ? 1 : 0);
}
if(!empty($_POST["tb_name"]))
$name = $_POST["tb_name"];
# Diner's name
else {
echo "Must give Diner's name"; die();
}
$name_san = preg_replace("/[^A-Za-z]/", "", $name);
if(checkbox_value("cb_eggs"))
$cb_eggs = $_POST["cb_eggs"];
else
$cb_eggs = "N";
# Will be Y if user wants eggs
# … omitted for brevity
$eggs_style = $_POST["rb_eggs"]; # Will be F, P or S
echo "<p>"
# … omitted for brevity
if ($cb_eggs == "Y") {
if ($eggs_style == "F") { echo "Fried eggs<br><br>"; }
if ($eggs_style == "P") { echo "Poached eggs<br><br>"; }
if ($eggs_style == "S") { echo "Scrambled eggs<br><br>"; }
}
echo "</p>";
?>
Populate a form from DB
Here's the code we originally used in form.html to create the menu:
Eggs <input type="checkbox" name="cb_eggs" value="Y" />
Bacon <input type="checkbox" name="cb_bacon" value="Y" />
Sausages <input type="checkbox" name="cb_sausages" value="Y" />
Beans <input type="checkbox" name="cb_beans" value="Y" />
And here's a PHP file version of it, based on an array of items that we have read from the database
<?php
for ($i = 0; $i < count($items); $i++) {
echo $items[$i];
echo "<input type='checkbox' name='cb_";
echo $items[$i] . "' value='Y' /> <br />";
}
# The ' is the same as \" and can be used inside strings
for ($i = 0; $i < count($items); $i++) {
echo $items[$i];
echo "<input type=\"checkbox\" name=\"cb_" ;
echo $items[$i] . "\" value=\"Y\" /> <br />";
}
# or as a third and maybe the best option
for ($i = 0; $i < count($items); $i++) {
echo $items[$i];
echo "<input type='checkbox' name='cb_{$items[$i]}' value='Y' /> <br />";
}
?>
For an array called $items[] that contains values of "eggs", "bacon", "sausages"
and "beans", this code will produce:
<input type='checkbox' name='cb_eggs' value='Y' />
<input type='checkbox' name='cb_bacon' value='Y' />
<input type="checkbox" name="cb_sausages" value="Y" />
<input type="checkbox" name="cb_beans" value="Y" />
Retrieving Textarea and
Dropdown Data
• A textarea's content is retrieved in the same way as a textbox
the same goes for the dropdown box etc.
• Use $_POST["ab_xyz"], where ab_xyz is the name of the
textarea, dropdown etc. as defined in the form
• CR (\r) and LF (\n) can be removed with preg_replace()
• Another option that you may find useful is a select with values
– $_POST[] will return 1, 2, 3 or 4 respectively instead of Spring,
Summer, ... which could be an advantage
<form method="post" action="script.php">
<textarea name="ta_comments" rows="4"
cols="20"></textarea>
<select name="dd_season">
<option>Spring</option>
<option>Summer</option>
<option>Autumn</option>
<option>Winter</option>
</select>
</form>
<select name="dd_season">
<option value="1">Spring</option>
<option value="2">Summer</option>
<option value="3">Autumn</option>
<option value="4">Winter</option>
</select>
Checkbox arrays
• When you're creating HTML forms, you'll often find yourself creating
a large set of checkboxes. We can use the auto increment feature for
arrays in PHP
• The $rooms array will contain only those checkboxes that were ticked
• If the visitor ticks boxes 2 and 4, the $rooms array will contain 2
elements (numbered 0 and 1) with values 2 and 4 respectively
Room 1 <input type="checkbox" name="rooms[]" value="1" /> <br>
Room 2 <input type="checkbox" name="rooms[]" value="2" /> <br>
Room 3 <input type="checkbox" name="rooms[]" value="3" /> <br>
Room 4 <input type="checkbox" name="rooms[]" value="4" /> <br>
$rooms = $_POST["rooms"];
$room_count = count($rooms);
echo "There were " . $room_count . " rooms chosen.<br>";
echo "The rooms you ticked were:<br>";
echo "<br>";
for ($i=0; $i <= count($rooms); $i++) {
echo $rooms[$i] . "<br>";
Feedback forms
<form action="formtoemail.php" method="post">
<table border="1" bgcolor="#ececec" cellspacing="5" width="550">
<tr><td>Name:</td><td>
<input type="text" size="40" name="name" style="width: 350px"></td></tr>
<tr><td>email address:</td><td>
<input type="text" size="40" name="email" style="width: 350px"></td></tr>
<tr><td valign="top">Comments:</td><td>
<textarea name="comments" rows="6" cols="50"></textarea></td></tr>
<tr><td></td><td>
<div align="right"> <input type="submit" value="Send" /> </div> </td></tr>
</table>
</form>
Sending the email
<?php
# formtoemail.php, note that you must have a SMTP server on the web server!
# $_REQUEST is a merging of $_GET and $_POST where $_POST overrides $_GET
$name = $_REQUEST['name'];
$to = "[email protected]";
$subject = "FormToEmail Comments";
# we need some filtering and validation, this is however not present here!
$message = $_REQUEST['comments'];
$headers = "From: " . $_REQUEST['email'];
$date = date("D");
$date .= " at ";
$date .= date("H:i");
$message = "Comments from " . $name . ", " . $date . ", " . $message;
# bool mail ( string $to , string $subject , string $message
# [, string $additional_headers [, string $additional_parameters ]] )
$m = mail($to, $subject, $message, $headers);
echo "Return code from mail was " . $m;
exit();
?>
# Return code from mail was 1
# Email: Comments from Hans Jones, Mon at 14:39, Hello Form!
Hidden form elements
• Can be used to ”remember” values on the webpage if the page
is reloaded – remember HTTP is a stateless protocol!
– A better method is to use session variables
• Can also be used to hide values in the form which are sent in
to adjust the running script in some way
• For example to know the time between the HTML form code
was loaded and when it is received in the FormToEmail.php
# creates something like: <input type="hidden" name="timecode" value="12345" />
<?php
$t = time(); # returns the number of seconds since 1970-01-01
echo "<input type='hidden' name='timecode' value='" . $t . "' />";
?>
echo $t . "<br />";
# at response check to see if the form was answered to quickly – spam-proofing
<?php
$timecode = $_POST["timecode"];
if($timecode + 5 > time())
# old time + 5 sec vs. current time
exit();
else { response time was not to short ... }
?>
HTTP request message
• The first line of every HTTP request consists of three items, separated by
spaces
– A verb indicating the HTTP method, the requested URL and the HTTP version being
used
• Other points of interest in the sample request (many other headers exists)
– The Referer header is used to indicate the URL from which the request originated
– The User-Agent header is used to provide information about the browser or other
client software that generated the request.
– The Host header specifies the hostname that appeared in the full URL being
accessed
– The Cookie header is used to submit additional parameters that the server has
issued to the client
– An empty line (\r\n) and an optional message body
GET /auth/488/YourDetails.ashx?uid=129 HTTP/1.1
Accept: application/x-ms-application, image/jpeg, application/xaml+xml,
image/gif, image/pjpeg, application/x-ms-xbap, application/x-shockwaveflash, */*
Referer: https://mdsec.net/auth/488/Home.ashx
Accept-Language: en-GB
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64;
Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR
3.0.30729; .NET4.0C; InfoPath.3; .NET4.0E; FDM; .NET CLR 1.1.4322)
Accept-Encoding: gzip, deflate
Host: mdsec.net
Connection: Keep-Alive
Cookie: SessionId=5B70C71F3FD4968935CDB6682E545476
HTTP response message
• The first line of every HTTP response consists of three items, separated by spaces
– The HTTP version being used, a numeric status code indicating the result of the
request and a textual “reason phrase” further describing the status of the response
• Other points of interest in the sample response (many other headers exists)
– The Server header contains a banner indicating the web server software being used,
and sometimes other details
– The Set-Cookie header issues the browser a further cookie; this is submitted back in
the Cookieheader of subsequent requests to this server
– The Pragma header instructs the browser not to store the response in its cache
– The Content-Type header indicates that the body of this message contains an HTML
document. Almost all HTTP responses contain a message body after the headers
– The Content-Length header indicates the length of the message body in bytes
– An empty line (\r\n) and an optional message body
HTTP/1.1 200 OK
Date: Tue, 19 Apr 2011 09:23:32 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
Set-Cookie: tracking=tI8rk7joMx44S2Uu85nSWc
X-AspNet-Version: 2.0.50727
Cache-Control: no-cache
Pragma: no-cache
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 1067
<!DOCTYPE html><head><title>Your details</title>
...
HTTP request methods 1
• HTTP defines methods to indicate the desired action to be performed
on the identified resource (the web server page)
• HEAD
– Asks for the response identical to the one that would correspond to a
GET request, but without the returned response body.
– This is useful for retrieving meta-information written in response
headers, without having to transport the entire content.
• GET
– Requests a representation of the specified resource.
– Requests using GET should only retrieve data and should have no other
effect.
• POST
– Submits data to be processed (e.g., from an HTML form) to the identified
resource.
– The data is included in the body of the request. This may result in the
creation of a new resource or the updates of existing resources or both.
• PUT
– Uploads a representation of the specified resource.
HTTP request methods 2
• DELETE
– Deletes the specified resource.
• TRACE
– Echoes back the received request, so that a client can see what (if any)
changes or additions have been made by intermediate servers.
• OPTIONS
– Returns the HTTP methods that the server supports for specified URL.
This can be used to check the functionality of a web server by requesting
'*' instead of a specific resource.
• CONNECT
– Converts the request connection to a transparent TCP/IP tunnel, usually
to facilitate SSL-encrypted communication (HTTPS) through an
unencrypted HTTP proxy.
• PATCH
– Is used to apply partial modifications to a resource.
• HTTP servers are required to implement at least the GET and HEAD
methods and, whenever possible, also the OPTIONS method.
HTTP cookies
• Cookies are a key part of the HTTP protocol that most web
applications rely on
– The cookie mechanism enables the server to send items of data to the
client, which the client stores and resubmits to the server
– A server issues a cookie using the Set-Cookie response header
– The user’s browser then automatically adds the Cookie header to
subsequent requests back to the same server
• Cookies normally consist of a name/value pair
• Multiple cookies can be issued by using multiple Set-Cookie
headers in the server’s response
• In addition to the cookie’s value, the Set-Cookie header can
include any of the following optional attributes
– expires, domain, path, secure and httponly
• More about cookies later when we deal with JavaScript
Set-Cookie: tracking=tI8rk7joMx44S2Uu85nSWc
Cookie: tracking=tI8rk7joMx44S2Uu85nSWc
HTTP status codes
• Each HTTP response message must contain a status code in
its first line, indicating the result of the request
• The status codes fall into five groups, according to the code’s
first digit
–
–
–
–
–
1xx— Informational.
2xx— The request was successful.
3xx— The client is redirected to a different resource.
4xx— The request contains an error of some kind.
5xx— The server encountered an error fulfilling the request.
• Some examples
–
–
–
–
100 Continue
200 OK, 201 Created
301 Moved Permanently
400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found,
405 Method Not Allowed
– 500 Internal Server Error, 503 Service Unavailable
More about forms and HTTP
• A typical form using method post can look like this
<form action="/secure/login.php?app=quotations" method="post">
username: <input type="text" name="username"><br>
password: <input type="password” name="password">
<input type="hidden" name="redir" value="/secure/home.php">
<input type="submit" name="submit" value="login">
</form>
• When the user enters values and click the submit button the browser
makes a request like the following
POST /secure/login.php?app=quotations HTTP/1.1
Host: wahh-app.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 39
Cookie: SESS=GTnrpx2ss2tSWSnhXJGyG0LJ47MXRsjcFM6Bd
username=daf&password=foo&redir=/secure/home.php&submit=login
• To control server side processing logic we can use
–
–
–
–
The data (username and password)
The target URL parameter (app)
The SESS cookie value
The hidden parameter (redir) value
Form enctype
• The preceding request contained a header specifying ContentType as: application/x-www-form-urlencoded
– This means that parameters are represented in the message body as
name/value pairs in the same way as an URL query string
• The other Content-Type you are likely to encounter is:
multipart/form-data
– An application can request that browsers use multipart encoding by
specifying this the enctype attribute
– With this form of encoding, the Content-Type header in the request also
specifies a random string that is used as a separator for the parameters
contained in the request body
• If the form specified multipart encoding, the resulting request
would look like the following
POST /secure/login.php?app=quotations HTTP/1.1
Host: wahh-app.com
Content-Type: multipart/form-data; boundary=------------7d71385d0a1a
Content-Length: 369
Cookie: SESS=GTnrpx2ss2tSWSnhXJGyG0LJ47MXRsjcFM6Bd
------------7d71385d0a1a
Content-Disposition: form-data; name=”username”
daf
Cont.
------------7d71385d0a1a
Content-Disposition: form-data; name=”password”
foo
------------7d71385d0a1a
Content-Disposition: form-data; name=”redir”
/secure/home.php
------------7d71385d0a1a
Content-Disposition: form-data; name=”submit”
login
------------7d71385d0a1a--
Debug with tools like
http://fiddler2.com/first-run
http://fiddler2.com/
HTTP Secure
• HTTPS is a URI scheme which has identical syntax
to the standard HTTP
• HTTPS signals the browser to use an added encryption layer of
SSL/TLS to protect the traffic
• SSL/TLS is especially suited for HTTP since it can provide some
protection even if only one side (typically the server) of the
communication is authenticated (by the client examining the server's
certificate)
• The main idea of HTTPS is to create a secure channel over an
insecure network
– This ensures reasonable protection from eavesdroppers and man-in-themiddle attacks, provided that adequate cipher suites are used and that
the server certificate is verified and trusted
• Because HTTPS piggybacks HTTP entirely on top of TLS, the
entirety of the underlying HTTP protocol can be encrypted
– This includes the request URL (which particular web page was
requested), query parameters, headers, and cookies (which often
contain identity information about the user)
Browser compatibility and
make the web faster
• Compatibility tables for support of HTML5, CSS3, SVG
and more in desktop and mobile browsers
– http://caniuse.com/
• Most of the time is spent
fetching images and other
resorces when loading a
page
– There is no point to
optimize the parts that
generate the HTML code
– Usually only responsible
for 20% of the time
• Performance guidelines
– http://developer.yahoo.com/performance/
– https://developers.google.com/speed/
Try to reduce HTTP requests!