Web Programming Step by Step, 2nd Edition

Lecture 11: Uploading Files

Reading: 6.4 - 6.5

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.

Valid HTML5 Valid CSS

Common site HTML/code

screenshot screenshot

Including files: include

include("filename");
include("header.html");      # repeated HTML content
include("shared-code.php");  # repeated PHP code

Including a common HTML file

<!DOCTYPE html>
<!-- this is top.html -->
<html><head><title>This is some common code</title>
...
include("top.html");      # this PHP file re-uses top.html's HTML content

Including a common PHP file

<?php
# this is common.php
function useful($x) { return $x * $x; }

function top() {
	?>
	<!DOCTYPE html>
	<html><head><title>This is some common code</title>
	...
	<?php
}
include("common.php");   # this PHP file re-uses common.php's PHP code
$y = useful(42);         # call a shared function
top();                   # produce HTML output
...

A form that submits to itself

<form action="" method="post">
	...
</form>

Processing a self-submitted form

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

Uploading files

<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>
  • 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

Uploading details

<input type="file" name="avatar" />

Processing uploaded file, example

$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";
}

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");

Printing an associative array

print_r($blackbook);
Array
(
    [jenny] => 206-867-5309
    [stuart] => 206-685-9138
    [marty] => 206-685-2181
)

Associative array functions

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

15.1: Form Validation

What is form validation?

A real form that uses validation

wamu

Client vs. server-side validation

Validation can be performed:

An example form to be validated

<form action="http://foo.com/foo.php" method="get">
	<div>
		City:  <input name="city" /> <br />
		State: <input name="state" size="2" maxlength="2" /> <br />
		ZIP:   <input name="zip" size="5" maxlength="5" /> <br />
		<input type="submit" />
	</div>
</form>

Basic server-side validation code

$city  = $_POST["city"];
$state = $_POST["state"];
$zip   = $_POST["zip"];
if (!$city || strlen($state) != 2 || strlen($zip) != 5) {
	print "Error, invalid city/state/zip submitted.";
}

The die function

die("error message text");

The header function

header("HTTP header text");   # in general
header("Location: url");      # for browser redirection

Using header to redirect between pages

header("Location: url");
$city  = $_POST["city"];
$state = $_POST["state"];
$zip   = $_POST["zip"];
if (!$city || strlen($state) != 2 || strlen($zip) != 5) {
	header("Location: start-page.php");   # invalid input; redirect
}

Another problem: Users submitting HTML content

The htmlspecialchars function

htmlspecialchars returns an HTML-escaped version of a string
$text = "<p>hi 2 u & me</p>";
$text = htmlspecialchars($text);   # "&lt;p&gt;hi 2 u &amp; me&lt;/p&gt;"