CSSE 290 Web Programming

Lecture 8: PHP Objects, Form Basics

Reading: 5.4, 6.1 - 6.3

Attribution: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.

Otherwise noted: Claude Anderson was given permission to modify the slides for CSSE 290 at Rose-Hulman by author Jessica Miller. The authors' original slides, based on Web Programming Step by Step, can be seen at http://webstepbook.com.
Some of the examples in some days' slides are from David Fisher at Rose-Hulman, who was kind enough to allow me to use them. My intention is to mark these examples with [DSF].

Valid HTML Valid CSS!

Administrivia

PHP Objects

Why use Classes and Objects?

Constructing and Using Objects

# construct an object
$name = new ClassName(parameters);

# access an object's field (if the field is public)
$name->fieldName

# call an object's method
$name->methodName(parameters);
$zip = new ZipArchive();
$zip->open("moviefiles.zip");
$zip->extractTo("images/");
$zip->close();

Object Use Example: Fetch a File from the Web

# Create an HTTP request to fetch student.php
$req = new HttpRequest("student.php", HttpRequest::METH_GET);
$params = array("first_name" => $fname, "last_name" => $lname);
$req->addPostFields($params);

# Send request and examine result
$req->send();
$http_result_code = $req->getResponseCode();   # 200 means OK
print "$http_result_code\n";
print $req->getResponseBody();

Class Declaration Syntax

class ClassName {
	# fields - data inside each object
	public $name;    # public field
	private $name;   # private field
	
	# constructor - initializes each object's state
	public function __construct(parameters) {
		statement(s);
	}
	
	# method - behavior of each object
	public function name(parameters) {
		statements;
	}
}

Class Definition Example

<?php
class Point {
	public $x;
	public $y;
	
	# equivalent of a Java constructor
	public function __construct($x, $y) {
		$this->x = $x;
		$this->y = $y;
	}
	
	public function distance($p) {
		$dx = $this->x - $p->x;
		$dy = $this->y - $p->y;
		return sqrt($dx * $dx + $dy * $dy);
	}
	
	# equivalent of Java's toString method
	public function __toString() {
		return "(" . $this->x . ", " . $this->y . ")";
	}
}
?>

Class Usage Example

<?php
# This code could go into a file named use_point.php
include("Point.php");

$p1 = new Point(0, 0);
$p2 = new Point(4, 3);
print "Distance between $p1 and $p2 is " . $p1->distance($p2) . "\n\n";

var_dump($p2);   # var_dump prints detailed state of an object
?>
Distance between (0, 0) and (4, 3) is 5

object(Point)[2]
  public 'x' => int 4
  public 'y' => int 3

Basic Inheritance

class ClassName extends ClassName {
	...
}
class Point3D extends Point {
	public $z;
	
	public function __construct($x, $y, $z) {
		parent::__construct($x, $y);
		$this->z = $z;
	}
	
	...
}

Static Methods, Fields, and Constants

static $name = value;    # declare a static field
const $name = value;     # declare a static constant
# Declare a static method
public static function name(parameters) {
	statements;
}
ClassName::methodName(parameters);  # call a static method (outside class)
self::methodName(parameters);       # call a static method (within class)

Abstract Classes and Interfaces

interface InterfaceName {
	public function name(parameters);
	public function name(parameters);
	...
}

class ClassName implements InterfaceName { ...
abstract class ClassName {
	abstract public function name(parameters);
	...
}

Form Basics

Web data

Recap: Query Strings and Parameters

URL?name=value&name=value...
http://www.google.com/search?q=deficit
http://example.com/student_login.php?username=gandalf&id=1234567

Query Parameters: $_GET, $_POST

$user_name = $_GET["username"];
$id_number = (int) $_GET["id"];
$eats_meat = FALSE;
if (isset($_GET["meat"])) {
	$eats_meat = TRUE;
}

HTML Forms

HTML form

HTML Form: <form>

<form action="destination URL">
	form controls
</form>

A Simple Form Example

<form action="http://www.google.com/search">
	<div>
		Let's search Google:
		<input name="q" />
		<input type="submit" />
	</div>
</form>

6.2: Form Controls

Form Controls: <input>

<!-- 'q' happens to be the name of Google's required parameter -->
<input type="text" name="q" value="Rose-Hulman" />
<input type="submit" value="Go fish!" />

Text Fields: <input>

<input type="text" size="10" maxlength="8" /> NetID <br />
<input type="password" size="16" /> Password
<input type="submit" value="Log In" />

Text Boxes: <textarea>

A multi-line text input area (inline)

<textarea rows="4" cols="20">
Type your comments here.
</textarea>

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

Radio Buttons: <input>

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

Text Labels: <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>

Drop-down List: <select>, <option>

Menus of choices that collapse and expand (inline)

<select name="favoritebeatle">
	<option>Paul</option>
	<option>George</option>
	<option selected="selected">Ringo</option>
	<option>John</option>
</select>

Using <select> for Lists

<select name="favoritebeatle[]" size="5" multiple="multiple">
	<option>John</option>
	<option>George</option>
	<option>Paul</option>
	<option>Pete*</option>
	<option>Stu*</option>
	<option selected="selected">Ringo</option>
</select>

* See http://en.wikipedia.org/wiki/Fifth_Beatle

Option groups: <optgroup>

<select name="favoritebeatle">
	<optgroup label="long-term members">
	<option>John</option>
	<option>George</option>
	<option>Paul</option>
	<option>Ringo</option>
	</optgroup>
	<optgroup label="Temporary members">
		<option>Pete</option>
		<option>Stu</option>
	</optgroup>
</select>

Reset Button

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" />
<input type="submit" value="Order now!" />

Common UI Control Error

Hidden Input Parameters

<input type="text" name="username" /> Name <br />
<input type="text" name="sid" /> SID <br />
<input type="hidden" name="school" value="RHIT" />
<input type="hidden" name="year" value="2016" />

Grouping Input Fields: <fieldset>, <legend>

A group of input controls with an 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>
<input type="submit" />

Styling Form Controls

element[attribute="value"] {
	property : value;
	property : value;
	...
	property : value;
}
input[type="text"] {
	background-color: yellow;
	font-weight: bold;
}

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

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

URL-encoding

6.4: Processing Form Data in PHP

Example: Exponents (from last session)

$base = $_GET["base"];
$exp = $_GET["exponent"];
$result = pow($base, $exp);
print "$base ^ $exp = $result";
http://example.com/exponent.php?base=3&exponent=4
3 ^ 4 = 81

Print All Parameters (from last session)

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

Exercise: Work with your partner (finish on your own?)

form display 8
display  32 hinnts

Exercise: Traverse a Directory System

Write PHP code that recursively traverses a folder and all its subfolders, counting the number of files of a specic type (both the root folder and the type can be constants in your program)

mp3_count

Below I show some of my PHP code, all but the function body(mine is 11 lines long). Feel free to use this code or not. glob is useful; print and print_r can help with debuging. I strongly recommend that you do pair programming with your partner


mp3_count code 1
mp3_count code 2