Except where otherwise noted, the contents of this document are Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst. All rights reserved. Any redistribution, reproduction, transmission, or storage of part or all of the contents in any form is prohibited without the author's expressed written permission.
URL?name=value&name=value...
http://www.google.com/search?q=Obama http://example.com/student_login.php?username=stepp&id=1234567
username
has value stepp
, and sid
has value 1234567
<form>
<form action="destination URL"> form controls </form>
action
attribute gives the URL of the page that will process this form's dataaction
's URL
<form action="http://www.google.com/search"> <div> Let's search Google: <input name="q" /> <input type="submit" /> </div> </form>
div
<input>
<!-- 'q' happens to be the name of Google's required parameter -->
<input type="text" name="q" value="Colbert Report" />
<input type="submit" value="Booyah!" />
input
element is used to create many UI controls
name
attribute specifies name of query parameter to pass to servertype
can be button
, checkbox
, file
, hidden
, password
, radio
, reset
, submit
, text
, ...value
attribute specifies control's initial text<input>
<input type="text" size="10" maxlength="8" /> NetID <br /> <input type="password" size="16" /> Password <input type="submit" value="Log In" />
input
attributes: disabled
, maxlength
, readonly
, size
, value
size
attribute controls onscreen width of text fieldmaxlength
limits how many characters user is able to type into field<textarea>
a multi-line text input area (inline)
<textarea rows="4" cols="20"> Type your comments here. </textarea>
textarea
tag (optional)rows
and cols
attributes specify height/width in charactersreadonly
attribute means text cannot be modified<input>
yes/no choices that can be checked and unchecked (inline)
<input type="checkbox" name="lettuce" /> Lettuce <input type="checkbox" name="tomato" checked="checked" /> Tomato <input type="checkbox" name="pickles" checked="checked" /> Pickles
on
:
http://webster.cs.washington.edu/params.php?tomato=on&pickles=on
checked="checked"
attribute in HTML to initially check the box<input>
sets of mutually exclusive choices (inline)
<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
name
attribute (only one can be checked at a time)value
for each one or else it will be sent as value on
<label>
<label><input type="radio" name="cc" value="visa" checked="checked" /> Visa</label> <label><input type="radio" name="cc" value="mastercard" /> MasterCard</label> <label><input type="radio" name="cc" value="amex" /> American Express</label>
label
element can be targeted by CSS style rules<select>
,
<option>
menus of choices that collapse and expand (inline)
<select name="favoritecharacter"> <option>Jerry</option> <option>George</option> <option selected="selected">Kramer</option> <option>Elaine</option> </select>
option
element represents each choiceselect
optional attributes: disabled
, multiple
, size
selected
attribute sets which one is initially chosen<select>
for lists<select name="favoritecharacter[]" size="3" multiple="multiple"> <option>Jerry</option> <option>George</option> <option>Kramer</option> <option>Elaine</option> <option selected="selected">Newman</option> </select>
multiple
attribute allows selecting multiple items with shift- or ctrl-click
[]
if you allow multiple selections
option
tags can be set to be initially selected
<optgroup>
<select name="favoritecharacter"> <optgroup label="Major Characters"> <option>Jerry</option> <option>George</option> <option>Kramer</option> <option>Elaine</option> </optgroup> <optgroup label="Minor Characters"> <option>Newman</option> <option>Susan</option> </optgroup> </select>
Name: <input type="text" name="name" /> <br /> Food: <input type="text" name="meal" value="pizza" /> <br /> <label>Meat? <input type="checkbox" name="meat" /></label> <br /> <input type="reset" />
value
attributeI changed the form's HTML code ... but when I refresh, the page doesn't update!
<input type="text" name="username" /> Name <br /> <input type="text" name="sid" /> SID <br /> <input type="hidden" name="school" value="UW" /> <input type="hidden" name="year" value="2048" />
$base = $_GET["base"]; $exp = $_GET["exponent"]; $result = pow($base, $exp); print "$base ^ $exp = $result";
http://example.com/exponent.php?base=3&exponent=4
<?php foreach ($_GET as $param => $value) { ?> <p>Parameter <?= $param ?> has value <?= $value ?></p> <?php } ?>
http://example.com/print_params.php?name=Marty+Stepp&sid=1234567
Parameter name has value Marty Stepp
Parameter sid has value 1234567
print_r
or var_dump
on $_GET
or $_POST
for debugging
<fieldset>
,
<legend>
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 captionelement[attribute="value"] { property : value; property : value; ... property : value; }
input[type="text"] { background-color: yellow; font-weight: bold; }
input
)<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 />
[cc] => on, [startrek] => Jean-Luc Picard
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
" "
, "/"
, "="
, "&"
"Marty's cool!?"
→ "Marty%27s+cool%3F%21"
$_GET
and $_POST
arrays automatically decode themGET
vs. POST
requests
GET
: asks a server for a page or data
POST
: submits data to a web server and retrieves the server's response
POST
request is more appropriate than a GET
GET
requests embed their parameters in their URLs<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>
if ($_SERVER["REQUEST_METHOD"] == "GET") { # process a GET request ... } elseif ($_SERVER["REQUEST_METHOD"] == "POST") { # process a POST request ... }
$_SERVER
array's "REQUEST_METHOD"
elementhtmlspecialchars
function
htmlspecialchars
|
returns an HTML-escaped version of a string |
$text = "<p>hi 2 u & me</p>";
$text = htmlspecialchars($text); # "<p>hi 2 u & me</p>"
Array | Description |
---|---|
$_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) |
$blackbook = array(); $blackbook["marty"] = "206-685-2181"; $blackbook["stuart"] = "206-685-9138"; ... print "Marty's number is " . $blackbook["marty"] . ".\n";
"marty"
maps to value "206-685-2181"
print "Marty's number is {$blackbook['marty']}.\n";
<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>
input
tag with type
of file
enctype
attribute of the formpost
(an entire file can't be put into a URL!)enctype
(data encoding type) must be set to multipart/form-data
or else the file will not arrive at the server$_FILES
, not $_POST
$_FILES
is itself an associative array, containing:
name
: the local filename that the user uploadedtype
: the MIME type of data that was uploaded, such as image/jpeg
size
: file's size in bytestmp_name
: a filename where PHP has temporarily saved the uploaded file
<input type="file" name="avatar" />
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"
$username = $_POST["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"; }
is_uploaded_file(filename)
TRUE
if the given filename was uploaded by the user
move_uploaded_file(from, to)
is_uploaded_file
, then do move_uploaded_file
include
include("filename");
include("header.php");
function name(parameterName, ..., parameterName) { statements; }
function bmi($weight, $height) { $result = 703 * $weight / $height / $height; return $result; }
return
statements is implicitly "void"name(expression, ..., expression);
$w = 163; # pounds $h = 70; # inches $my_bmi = bmi($w, $h);
$school = "UW"; # global ... function downgrade() { global $school; $suffix = "(Wisconsin)"; # local $school = "$school $suffix"; print "$school\n"; }
global
statement
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"); # h, e, l, l, o print_separated("hello", "-"); # h-e-l-l-o
$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");
print_r($blackbook);
Array ( [jenny] => 206-867-5309 [stuart] => 206-685-9138 [marty] => 206-685-2181 )
if (isset($blackbook["marty"])) { print "Marty's phone number is {$blackbook['marty']}\n"; } else { print "No phone number found for Marty Stepp.\n"; }
name(s) | category |
---|---|
isset , array_key_exists
|
whether the array contains value for given key |
array_keys , array_values
|
an array containing all keys or all values in the assoc.array |
asort , arsort
|
sorts by value, in normal or reverse order |
ksort , krsort
|
sorts by key, in normal or reverse order |
foreach
loop and associative arraysforeach ($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
<form action="" method="post"> ... </form>
action
to the page's own URL (or blank)
if ($_SERVER["REQUEST_METHOD"] == "GET") { # normal GET request; display self-submitting form ?> <form action="" method="post">...</form> <?php } elseif ($_SERVER["REQUEST_METHOD"] == "POST") { # POST request; user is submitting form back to here; process it $var1 = $_POST["param1"]; ... }
$_SERVER
array to see which request you're handlingweb service: software functionality that can be invoked through the internet using common protocols
MIME type | related file extension |
---|---|
text/plain | .txt |
text/html | .html, .htm, ... |
text/css | .css |
text/javascript | .js |
text/xml | .xml |
image/gif | .gif |
image/jpeg | .jpg, .jpeg |
video/quicktime | .mov |
application/octet-stream | .exe |
header
header("Content-type: type/subtype");
header("Content-type: text/plain"); print("This output will appear as plain text now!\n");
header
function to specify non-HTML output
base
and exponent
and outputs base
raised to the exponent
power. For example, the following query should output 81
:
http://example.com/exponent.php?base=3&exponent=4
header("Content-type: text/plain"); $base = $_GET["base"]; $exp = $_GET["exponent"]; $result = pow($base, $exp); print $result;
$_SERVER
superglobal arrayindex | description | example |
---|---|---|
$_SERVER["SERVER_NAME"] |
name of this web server | "webster.cs.washington.edu" |
$_SERVER["SERVER_ADDR"] |
IP address of web server | "128.208.179.154" |
$_SERVER["REMOTE_HOST"] |
user's domain name | "hsd1.wa.comcast.net" |
$_SERVER["REMOTE_ADDR"] |
user's IP address | "57.170.55.93" |
$_SERVER["HTTP_USER_AGENT"] |
user's web browser | "Mozilla/5.0 (Windows; ..." |
$_SERVER["HTTP_REFERER"] |
where user was before this page | "http://www.google.com/" |
$_SERVER["REQUEST_METHOD"] |
HTTP method used to contact server | "GET" or "POST" |
phpinfo();
to see a complete list
# suppose my web service accepts a "type" query parameter ...
<?php if ($_GET["type"] == "html") { ?>
<ul>
<?php foreach ($students as $kid) { ?>
<li> <?= $kid ?> </li>
<?php } ?>
</ul>
<?php } ?>
... header("Content-type: text/xml"); print("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); ?><books> <?php foreach ($books as $title) { ?> <book title="<?= $title ?>" /> <?php } ?> </books>
text/xml
or application/xml
<?xml
line) first
print
ed
print
) are not ideal, because they could be confused for normal output
.status
property
HTTP code | Meaning |
---|---|
200 | OK |
301-303 | page has moved (permanently or temporarily) |
400 | illegal request |
403 | you are forbidden to access this page |
404 | page not found |
500 | internal server error |
complete list |
header("HTTP/1.1 code description");
if ($_POST["foo"] != "bar") {
# I am not happy with the value of foo; this is an error
header("HTTP/1.1 400 Invalid Request");
die("An HTTP error 400 (invalid request) occurred.");
}
if (!file_exists($input_file_path)) { header("HTTP/1.1 404 File Not Found"); die("HTTP error 404 occurred: File not found ($input_file_path)"); }
header
can also be used to send back HTTP error codes
header("HTTP/1.1 403 Forbidden");
header("HTTP/1.1 404 File Not Found");
header("HTTP/1.1 500 Server Error");
function require_params($params) {
# allow calling as a varargs function
$params = func_get_args();
foreach ($params as $param) {
if (!isset($_POST[$param])) {
header("HTTP/1.1 400 Invalid Request");
die("HTTP/1.1 400 Invalid Request: missing required parameter $param");
}
}
}
func_get_args
function allows a function to accept a varying # of params