University of Washington CSE 190M

Section 4: Forms

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

Exercise : Buggy HTML Form

The following HTML form has several mistakes that causes it not to submit its data correctly, as well as some poor design choices that make it unpleasant to the user. Look at the form, find the bug(s), and correct the problems.

<form action="wherever.php">
	UW NetID: <input type="text" id="uwnetid" size="8" /> <br />
	Year: <input type="checkbox" name="frosh"> Freshman</input>
	<label>
		<input type="checkbox" name="soph" /> Sophomore
		<input type="checkbox" name="junior" /> Junior
		<input type="checkbox" name="senior" /> Senior
	</label> <br />
	Student ID number:
	<!-- don't allow the user to type more than 7 characters -->
	<input type="text" name="studentid" size="7" /> <br /><br />
	Personal statement: Please type a roughly 500-word essay. <br />
	<input type="text" name="essay" size="500" />
</form>
	

Exercise Solution

<form action="http://webster.cs.washington.edu/params.php">
	UW NetID: <input type="text" id="uwnetid" size="8" maxlength="8" /> <br />
	Year:
	<label><input type="radio" name="year" /> Freshman</label> <br />
	<label><input type="radio" name="year" /> Sophomore </label> <br />
	<label><input type="radio" name="year" /> Junior </label> <br />
	<label><input type="radio" name="year" /> Senior </label> <br />
	Student ID number:
	<input type="text" name="studentid" size="7" maxlength="7"/> <br /><br />
	Personal statement: <br />
	<textarea name="essay" rows="10" cols="80">
		Please type a roughly 500-word essay.
	</textarea>
</form>
	

Exercise : Animal Gallery (by Alex Miller)

Given a directory of animal pictures (images.zip), write a PHP webpage animals.php which displays these pictures.

If no query parameter is set, then the page should simply display all of the images in the images directory. The user can set an animal query parameter to choose whether to display only puppy pictures or only kitty pictures. For example, if the user entered the following URL:

	.../animals.php?animal=puppy
	

Then the page should only display puppy pictures. You may assume that the animal query parameter is either kitty or puppy.

Exercise Solution

<div>
  <?php
  $animal = "";
  if (isset($_GET["animal"])) {
	  $animal = $_GET["animal"];
  }
  $files = glob("images/{$animal}*.jpeg");
  foreach ($files as $image) {
	 ?>
	 <img src="<?= $image ?>" alt="animal picture" />
	 <?php
  }
  ?>
</div>

Exercise : Login (by Morgan Doocy)

Write a form, login.html, which asks the user for a username and password. Then write a script, login.php, that will look in the file passwd.txt to see if the user's password matches. Each username/password pair will be stored on its own line in the form username:password.

If the password entered matches the password stored in the file for that user, login.php should display a message with a class of granted. Otherwise, it should display a message with a class of denied.

If the user checks "I'm a new user", then you should add the provided username and password to passwd.txt.

Exercise : Login (by Morgan Doocy)

screenshot of login.html filled out screenshot of login.php with access granted

Exercise Solution

<!DOCTYPE html>
<html>
   <head>
      <title>Login</title>
      <link rel="stylesheet" type="text/css" href="http://webster.cs.washington.edu/cse190m/sections/4/login/login.css" />
   </head>
   <body>
      <h1>Login</h1>
      <form action="login.php" method="post">
         <dl>
            <dt>Username:</dt>
            <dd><input type="text" name="username" /></dd>
            <dt>Password:</dt>
            <dd><input type="password" name="password" /></dd>
         </dl>
         <p><label><input type="checkbox" name="new" /> I am a new user.</label></p>
         <p><input type="submit" value="Log in" /></p>
      </form>
   </body>
</html>

Exercise Solution

<?php
	$user = $_POST["username"];
	$passwd = $_POST["password"];
	$new = isset($_POST["new"]);
	if ($new) {
      file_put_contents("passwd.txt", "$user:$passwd\n", FILE_APPEND);
   } else {
      $granted = false;
      $passwords = explode("\n", file_get_contents("passwd.txt"));
      foreach ($passwords as $line) {
         list($stored_user, $stored_pass) = explode(":", $line);
         if ($entered_user == $stored_user
         		&& $entered_pass == $stored_pass) {
            $granted = true;
            break;
         }
      }
   }
?>
	

Exercise Solution

<!DOCTYPE html>
<html>
	<head>
	<title>Login</title>
	<link rel="stylesheet" type="text/css"
		href="http://webster.cs.washington.edu/cse190m/sections/4/login/login.css" />
	</head>
	<body>
		<?php if ($new) { ?>
			<h1 class="granted">Welcome, <?= $entered_user ?>!</h1>
		<?php } else if ($granted) { ?>
			<h1 class="granted">Access granted</h1>
		<?php } else { ?>
			<h1 class="denied">Access denied!</h1>
		<?php } ?>
	</body>
</html>

Exercise : Show Twos (by Alex Miller)

Write a PHP function show_twos that takes a single integer as a parameter and outputs its factors of 2 with accompanying HTML. For example:

show_twos(68);
show_twos(18);
show_twos(68);
show_twos(120);

should produce

<strong>68 =</strong> 2 * 2 * 17<br/>
<strong>18 =</strong> 2 * 9<br/>
<strong>68 =</strong> 2 * 2 * 17<br/>
<strong>120 =</strong> 2 * 2 * 2 * 15<br/>

as output.

Exercise Solution

<?php
function showTwos($n) { ?>
   <strong><?= $n ?> =</strong>
   <?php
   while ($n % 2 == 0) {
      print "2 *";
      $n = $n / 2;
   }
   ?>
   <?= $n ?><br />
   <?php
}
showTwos(7);
showTwos(18);
showTwos(68);
showTwos(120);
?>
	

Exercise : Captions (by Morgan Doocy)

Write a form, caption.html, which asks the user to select a photo to display and two lines of caption. Then write a script, caption.php, that will accept the submitted information and display the photo and captions on-screen:

Provide several photo URLs to select from in the form of a dropdown menu. Give the options in the dropdown user-friendly labels, but make the user's final selection result in an absolute URL being submitted to the server script. For the img's alt text, use a combination of both caption lines.

Exercise : Captions (by Morgan Doocy)

screenshot of caption.html filled out screenshot of caption.php

Exercise Solution

<form action="caption.php" enctype="multipart/form-data" method="post">
	<dl>
		<dt>Image:</dt>
		<dd>
			<select name="image">
				<option value="http://tinyurl.com/8x4ouqu">Cupcake</option>
				<option value="http://tinyurl.com/6uqgufv">Leo Strutting</option>
			</select>
		</dd>
		<dt>Line 1:</dt>
		<dd><input type="text" name="line1" /></dd>
		<dt>Line 2:</dt>
		<dd><textarea name="line2" rows="2" cols="30"></textarea></dd>
	</dl>
	<p><input type="submit" value="Captionate!" /></p>
</form>
	

Exercise Solution

<?php
   $image = $_POST["image"];
   $line1 = $_POST["line1"];
   $line2 = $_POST["line2"];
?>
<p>
	<img id="image" src="<?= $image ?>" alt="<?= "$line1. $line2" ?>" />
</p>
<h1 id="line1"><span><?= $line1 ?></span></h1>
<p id="line2"><?= $line2 ?></p>
	

Exercise : Calculations (by Alex Miller)

Given an input file input.txt, Write a PHP page calculations.php that reads in the file and calculates the result for each line in the file. For example, the result for the line:

divide:8 2 2

would be:

8 / 2 / 2 = 2

Exercise Solution

<ul><?php
	$lines = file("input.txt");
	foreach ($lines as $line) {
		$split = split(":", $line);
		$numbers = split(" ", $split[1]);
		$sum = $numbers[0];
		for ($i = 1; $i < sizeof($numbers); $i++) {
			if ($split[0] == "add") {
				$sum += $numbers[$i];
			} else if ($split[0] == "multiply") {
				$sum *= $numbers[$i];
			} else if ($split[0] == "subtract") {
				$sum -= $numbers[$i];
			} else if ($split[0] == "divide") {
				$sum /= $numbers[$i];
			}
		} ?>
	<li><?= $line ?> = <?= $sum ?></li>
<?php } ?></ul>
	

Exercise : Complaint Generator

Write an HTML form, complaint.html, that allows the user to generate complaint letters. The user will specify the first/last name of the person to complain about, the person's gender, and how many sentences of complaints to generate. Test your form by having it initially submit its data to params.php. The following should be the appearance of your form:
expected form output

Exercise : Complaint Generator

Once your form submits properly, write a PHP page letter.php on the server to process this form data. On the server there is a file sentence.txt containing a bunch of complaint sentences. Your PHP code should read this file, randomly pick sentences from it, and turn these into a complaint letter. The file has one sentence per line. You will need to personalize the letter by inserting the person's name and other information into it. The following are the patterns you will need to replace:

Exercise : Complaint Generator

You can use the str_replace function to help you replace the above patterns in the text. If you write the code correctly, you can replace each placeholder with a single call. When you're finished with your page, it should look like the following:

expected form output

Exercise Solution

Your finished code might look like the following sample solution, written by TA Stefanie Hatcher: