Lecture 10
More HTML Forms; Posting Data
Reading: 6.3 - 6.5
Except where otherwise noted, the contents of this presentation are Copyright 2010 Marty Stepp and Jessica Miller.
6.2: Form Controls
-
6.1: Form Basics
-
6.2: Form Controls
-
6.3: Submitting Data
-
6.4: Processing Form Data in PHP
groups of input fields with optional caption (block)
<fieldset>
<legend>Credit cards:</legend>
<input type="radio" name="cc" value="visa" checked="checked" /> Visa
<input type="radio" name="cc" value="mastercard" /> MasterCard
<input type="radio" name="cc" value="amex" /> American Express
</fieldset>
fieldset
groups related input fields, adds a border; legend
supplies a caption
Styling form controls
(6.2.9)
- attribute selector: matches only elements that have a particular attribute value
- useful for controls because many share the same element (
input
)
6.3: Submitting Data
-
6.1: Form Basics
-
6.2: Form Controls
-
6.3: Submitting Data
-
6.4: Processing Form Data in PHP
Problems with submitting data
<label><input type="radio" name="cc" /> Visa</label>
<label><input type="radio" name="cc" /> MasterCard</label> <br />
Favorite Star Trek captain:
<select name="startrek">
<option>James T. Kirk</option>
<option>Jean-Luc Picard</option>
</select> <br />
- this form submits to our handy params.php tester page
- the form may look correct, but when you submit it...
[cc] => on, [startrek] => Jean-Luc Picard
The value
attribute
<label><input type="radio" name="cc" value="visa" /> Visa</label>
<label><input type="radio" name="cc" value="mastercard" /> MasterCard</label> <br />
Favorite Star Trek captain:
<select name="startrek">
<option value="kirk">James T. Kirk</option>
<option value="picard">Jean-Luc Picard</option>
</select> <br />
value
attribute sets what will be submitted if a control is selected
[cc] => visa, [startrek] => picard
URL-encoding
(6.3.1)
- certain characters are not allowed in URL query parameters:
- examples:
" "
, "/"
, "="
, "&"
- when passing a parameter, it is URL-encoded
()
"Marty's cool!?"
→ "Marty%27s+cool%3F%21"
- you don't usually need to worry about this:
- the browser automatically encodes parameters before sending them
- the PHP
$_REQUEST
array automatically decodes them
-
... but occasionally the encoded version does pop up (e.g. in Firebug)
Submitting data to a web server
- though browsers mostly retrieve data, sometimes you want to submit data to a server
- Hotmail: Send a message
- Flickr: Upload a photo
- Google Calendar: Create an appointment
- the data is sent in HTTP requests to the server
- with HTML forms
- with Ajax (seen later)
- the data is placed into the request as parameters
HTTP GET
vs. POST
requests
(6.3.3)
-
GET
: asks a server for a page or data
- if the request has parameters, they are sent in the URL as a query string
-
POST
: submits data to a web server and retrieves the server's response
- if the request has parameters, they are embedded in the request's HTTP packet, not the URL
-
For submitting data, a
POST
request is more appropriate than a GET
GET
requests embed their parameters in their URLs
- URLs are limited in length (~ 1024 characters)
- URLs cannot contain special characters without encoding
- private data in a URL can be seen or modified by users
Form POST example
<form action="http://foo.com/app.php" method="post">
<div>
Name: <input type="text" name="name" /> <br />
Food: <input type="text" name="meal" /> <br />
<label>Meat? <input type="checkbox" name="meat" /></label> <br />
<input type="submit" />
<div>
</form>
GET or POST?
if ($_SERVER["REQUEST_METHOD"] == "GET") {
...
} elseif ($_SERVER["REQUEST_METHOD"] == "POST") {
...
}
- some PHP pages process both GET and POST requests
- to find out which kind of request we are currently processing,
look at the global $_SERVER
array's "REQUEST_METHOD"
element
The htmlspecialchars
function
- text from files / user input / query params might contain <, >, &, etc.
- we could manually write code to strip out these characters
- better idea: allow them, but escape them
$text = "<p>hi 2 u & me</p>";
$text = htmlspecialchars($text);
6.4: Processing Form Data in PHP
-
6.1: Form Basics
-
6.2: Form Controls
-
6.3: Submitting Data
-
6.4: Processing Form Data in PHP
"Superglobal" arrays
(6.4.1)
Array |
Description |
$_REQUEST
|
parameters passed to any type of request |
$_GET ,
$_POST
|
parameters passed to GET and POST requests |
$_SERVER ,
$_ENV
|
information about the web server |
$_FILES
|
files uploaded with the web request |
$_SESSION ,
$_COOKIE
|
"cookies" used to identify the user (seen later) |
-
PHP superglobal arrays contain information about the current request, server, etc.:
-
These are special kinds of arrays called associative arrays.
Associative arrays
(6.4.1)
$blackbook = array();
$blackbook["marty"] = "206-685-2181";
$blackbook["stuart"] = "206-685-9138";
...
print "Marty's number is " . $blackbook["marty"] . ".\n";
Uploading files
(6.3.4)
<form action="http://webster.cs.washington.edu/params.php"
method="post" enctype="multipart/form-data">
Upload an image as your avatar:
<input type="file" name="avatar" />
<input type="submit" />
</form>
- add a file upload to your form as an
input
tag with type
of file
- must also set the
enctype
attribute of the form
- it makes sense that the form's request method must be
post
(an entire file can't be put into a URL!)
- form's
enctype
(data encoding type) must be set to multipart/form-data
or else the file will not arrive at the server
Processing an uploaded file in PHP
(6.4.3)
-
uploaded files are placed into global array
$_FILES
, not $_REQUEST
- each element of
$_FILES
is itself an associative array, containing:
name
: the local filename that the user uploaded
type
: the MIME type of data that was uploaded, such as image/jpeg
size
: file's size in bytes
tmp_name
: a filename where PHP has temporarily saved the uploaded file
- to permanently store the file, move it from this location into some other file
Uploading details
<input type="file" name="avatar" />
- example: if you upload
borat.jpg
as a parameter named avatar
,
$_FILES["avatar"]["name"]
will be "borat.jpg"
$_FILES["avatar"]["type"]
will be "image/jpeg"
$_FILES["avatar"]["tmp_name"]
will be something like "/var/tmp/phpZtR4TI"
Processing uploaded file, example
$username = $_REQUEST["username"];
if (is_uploaded_file($_FILES["avatar"]["tmp_name"])) {
move_uploaded_file($_FILES["avatar"]["tmp_name"], "$username/avatar.jpg");
print "Saved uploaded file as $username/avatar.jpg\n";
} else {
print "Error: required file not uploaded";
}
- functions for dealing with uploaded files:
-
is_uploaded_file(filename)
returns TRUE
if the given filename was uploaded by the user
-
move_uploaded_file(from, to)
moves from a temporary file location to a more permanent file
- proper idiom: check
is_uploaded_file
, then do move_uploaded_file
Including files: include
(5.4.2)
include("filename");
include("header.php");
- inserts the entire contents of the given file into the PHP script's output page
- encourages modularity
- useful for defining reused functions needed by multiple pages
Functions
(5.4.1)
function name(parameterName, ..., parameterName) {
statements;
}
function bmi($weight, $height) {
$result = 703 * $weight / $height / $height;
return $result;
}
- parameter types and return types are not written
- a function with no
return
statements is implicitly "void"
- can be declared in any PHP block, at start/end/middle of code
Calling functions
name(expression, ..., expression);
$w = 163;
$h = 70;
$my_bmi = bmi($w, $h);
- if the wrong number of parameters are passed, it's an error
Variable scope: global and local vars
$school = "UW";
...
function downgrade() {
global $school;
$suffix = "(Wisconsin)";
$school = "$school $suffix";
print "$school\n";
}
- variables declared in a function are local to that function; others are global
- if a function wants to use a global variable, it must have a
global
statement
- but don't abuse this; mostly you should use parameters
Default parameter values
function name(parameterName = value, ..., parameterName = value) {
statements;
}
function print_separated($str, $separator = ", ") {
if (strlen($str) > 0) {
print $str[0];
for ($i = 1; $i < strlen($str); $i++) {
print $separator . $str[$i];
}
}
}
print_separated("hello");
print_separated("hello", "-");
- if no value is passed, the default will be used (defaults must come last)
Extra stuff about associative arrays
-
6.1: Form Basics
-
6.2: Form Controls
-
6.3: Submitting Data
-
6.4: Processing Form Data in PHP
-
More about associative arrays
Creating an associative array
$name = array();
$name["key"] = value;
...
$name["key"] = value;
$name = array(key => value, ..., key => value);
$blackbook = array("marty" => "206-685-2181",
"stuart" => "206-685-9138",
"jenny" => "206-867-5309");
- can be declared either initially empty, or with a set of predeclared key/value pairs
Printing an associative array
print_r($blackbook);
Array
(
[jenny] => 206-867-5309
[stuart] => 206-685-9138
[marty] => 206-685-2181
)
print_r
function displays all keys/values in the array
var_dump
function is much like print_r
but prints more info
- unlike
print
, these functions require parentheses
if (isset($blackbook["marty"])) {
print "Marty's phone number is {$blackbook['marty']}\n";
} else {
print "No phone number found for Marty Stepp.\n";
}
foreach
loop and associative arrays
foreach ($blackbook as $key => $value) {
print "$key's phone number is $value\n";
}
jenny's phone number is 206-867-5309
stuart's phone number is 206-685-9138
marty's phone number is 206-685-2181
- both the key and the value are given a variable name
- the elements will be processed in the order they were added to the array